Release 4.48
[org-mode.git] / org.el
blobb9dbc6a0fe9c329a620f4b41b9c911f23c519e8c
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.48
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.48
65 ;; - Agenda views can be made in batch mode from the command line.
66 ;; - `org-store-link' does the right thing in dired-mode.
67 ;; - File links can contain environment variables (thanks to Ed Hirgelt).
68 ;; - Full Emacs 21 compatibility has been restored.
69 ;; - Bug fixes.
71 ;; Version 4.47
72 ;; - Custom commands may produce an agenda which contains several blocks,
73 ;; each block created by a different agenda command.
74 ;; - Agenda commands can be restricted to the current file, region, subtree.
75 ;; - The timeline command must now be called through the agenda
76 ;; dispatcher (C-c a L). `C-c C-r' no longer works.
77 ;; - Agenda items can be sorted by tag. The *last* tag is used for this.
78 ;; - The prefix and the sorting strategy for agenda items can depend
79 ;; upon the agenda type.
80 ;; - The handling of `mailto:' links can be customized, see the new
81 ;; variable `org-link-mailto-program'.
82 ;; - `mailto' links can specify a subject after a double colon,
83 ;; like [[mailto:carsten@orgmode.org::Org-mode is buggy]].
84 ;; - In the #+STARTUP line, M-TAB completes valid keywords.
85 ;; - In the #+TAGS: line, M-TAB after ":" inserts all currently used tags.
86 ;; - Again full Emacs 21 support: Checkboxes and publishing are fixed.
87 ;; - More minor bug fixes.
88 ;;
89 ;; Version 4.45
90 ;; - Checkbox lists can show statistics about checked items.
91 ;; - C-TAB will cycle the visibility of archived subtrees.
92 ;;; - Documentation about checkboxes has been moved to chapter 5.
93 ;; - Bux fixes.
95 ;; Version 4.44
96 ;; - Clock table can be done for a limited time interval.
97 ;; - Obsolete support for the old outline mode has been removed.
98 ;; - Bug fixes and code cleaning.
100 ;; Version 4.43
101 ;; - Bug fixes
102 ;; - `s' key in the agenda saves all org-mode buffers.
104 ;; Version 4.41
105 ;; - Shift-curser keys can modify inactive time stamps (inactive time
106 ;; stamps are the ones in [...] brackets.
107 ;; - Toggle all checkboxes in a region/below a headline.
108 ;; - Bug fixes.
110 ;;; Code:
112 (eval-when-compile
113 (require 'cl)
114 (require 'calendar))
115 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
116 ;; the file noutline.el being loaded.
117 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
118 ;; We require noutline, which might be provided in outline.el
119 (require 'outline) (require 'noutline)
120 ;; Other stuff we need.
121 (require 'time-date)
122 (require 'easymenu)
124 ;;; Customization variables
126 (defvar org-version "4.47"
127 "The version number of the file org.el.")
128 (defun org-version ()
129 (interactive)
130 (message "Org-mode version %s" org-version))
132 ;; Compatibility constants
133 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
134 (defconst org-format-transports-properties-p
135 (let ((x "a"))
136 (add-text-properties 0 1 '(test t) x)
137 (get-text-property 0 'test (format "%s" x)))
138 "Does format transport text properties?")
140 (defgroup org nil
141 "Outline-based notes management and organizer."
142 :tag "Org"
143 :group 'outlines
144 :group 'hypermedia
145 :group 'calendar)
147 (defgroup org-startup nil
148 "Options concerning startup of Org-mode."
149 :tag "Org Startup"
150 :group 'org)
152 (defcustom org-startup-folded t
153 "Non-nil means, entering Org-mode will switch to OVERVIEW.
154 This can also be configured on a per-file basis by adding one of
155 the following lines anywhere in the buffer:
157 #+STARTUP: fold
158 #+STARTUP: nofold
159 #+STARTUP: content"
160 :group 'org-startup
161 :type '(choice
162 (const :tag "nofold: show all" nil)
163 (const :tag "fold: overview" t)
164 (const :tag "content: all headlines" content)))
166 (defcustom org-startup-truncated t
167 "Non-nil means, entering Org-mode will set `truncate-lines'.
168 This is useful since some lines containing links can be very long and
169 uninteresting. Also tables look terrible when wrapped."
170 :group 'org-startup
171 :type 'boolean)
173 (defcustom org-startup-align-all-tables nil
174 "Non-nil means, align all tables when visiting a file.
175 This is useful when the column width in tables is forced with <N> cookies
176 in table fields. Such tables will look correct only after the first re-align.
177 This can also be configured on a per-file basis by adding one of
178 the following lines anywhere in the buffer:
179 #+STARTUP: align
180 #+STARTUP: noalign"
181 :group 'org-startup
182 :type 'boolean)
184 (defcustom org-startup-with-deadline-check nil
185 "Non-nil means, entering Org-mode will run the deadline check.
186 This means, if you start editing an org file, you will get an
187 immediate reminder of any due deadlines.
188 This can also be configured on a per-file basis by adding one of
189 the following lines anywhere in the buffer:
190 #+STARTUP: dlcheck
191 #+STARTUP: nodlcheck"
192 :group 'org-startup
193 :type 'boolean)
195 (defcustom org-insert-mode-line-in-empty-file nil
196 "Non-nil means insert the first line setting Org-mode in empty files.
197 When the function `org-mode' is called interactively in an empty file, this
198 normally means that the file name does not automatically trigger Org-mode.
199 To ensure that the file will always be in Org-mode in the future, a
200 line enforcing Org-mode will be inserted into the buffer, if this option
201 has been set."
202 :group 'org-startup
203 :type 'boolean)
205 (defcustom org-CUA-compatible nil
206 "Non-nil means use alternative key bindings for S-<cursor movement>.
207 Org-mode used S-<cursor movement> for changing timestamps and priorities.
208 S-<cursor movement> is also used for example by `CUA-mode' to select text.
209 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
210 alternative bindings. Setting this variable to t will replace the following
211 keys both in Org-mode and in the Org-agenda buffer.
213 S-RET -> C-S-RET
214 S-up -> M-p
215 S-down -> M-n
216 S-left -> M--
217 S-right -> M-+
219 If you do not like the alternative keys, take a look at the variable
220 `org-disputed-keys'.
222 This option is only relevant at load-time of Org-mode. Changing it requires
223 a restart of Emacs to become effective."
224 :group 'org-startup
225 :type 'boolean)
227 (defvar org-disputed-keys
228 '((S-up [(shift up)] [(meta ?p)])
229 (S-down [(shift down)] [(meta ?n)])
230 (S-left [(shift left)] [(meta ?-)])
231 (S-right [(shift right)] [(meta ?+)])
232 (S-return [(shift return)] [(control shift return)]))
233 "Keys for which Org-mode and other modes compete.
234 This is an alist, cars are symbols for lookup, 1st element is the default key,
235 second element will be used when `org-CUA-compatible' is t.")
237 (defun org-key (key)
238 "Select a key according to `org-CUA-compatible'."
239 (nth (if org-CUA-compatible 2 1)
240 (or (assq key org-disputed-keys)
241 (error "Invalid Key %s in `org-key'" key))))
243 (defcustom org-ellipsis nil
244 "The ellipsis to use in the Org-mode outline.
245 When nil, just use the standard three dots. When a string, use that instead,
246 and just in Org-mode (which will then use its own display table).
247 Changing this requires executing `M-x org-mode' in a buffer to become
248 effective."
249 :group 'org-startup
250 :type '(choice (const :tag "Default" nil)
251 (string :tag "String" :value "...#")))
253 (defvar org-display-table nil
254 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
256 (defgroup org-keywords nil
257 "Keywords in Org-mode."
258 :tag "Org Keywords"
259 :group 'org)
261 (defcustom org-deadline-string "DEADLINE:"
262 "String to mark deadline entries.
263 A deadline is this string, followed by a time stamp. Should be a word,
264 terminated by a colon. You can insert a schedule keyword and
265 a timestamp with \\[org-deadline].
266 Changes become only effective after restarting Emacs."
267 :group 'org-keywords
268 :type 'string)
270 (defcustom org-scheduled-string "SCHEDULED:"
271 "String to mark scheduled TODO entries.
272 A schedule is this string, followed by a time stamp. Should be a word,
273 terminated by a colon. You can insert a schedule keyword and
274 a timestamp with \\[org-schedule].
275 Changes become only effective after restarting Emacs."
276 :group 'org-keywords
277 :type 'string)
279 (defcustom org-closed-string "CLOSED:"
280 "String used as the prefix for timestamps logging closing a TODO entry."
281 :group 'org-keywords
282 :type 'string)
284 (defcustom org-clock-string "CLOCK:"
285 "String used as prefix for timestamps clocking work hours on an item."
286 :group 'org-keywords
287 :type 'string)
289 (defcustom org-comment-string "COMMENT"
290 "Entries starting with this keyword will never be exported.
291 An entry can be toggled between COMMENT and normal with
292 \\[org-toggle-comment].
293 Changes become only effective after restarting Emacs."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-quote-string "QUOTE"
298 "Entries starting with this keyword will be exported in fixed-width font.
299 Quoting applies only to the text in the entry following the headline, and does
300 not extend beyond the next headline, even if that is lower level.
301 An entry can be toggled between QUOTE and normal with
302 \\[org-toggle-fixed-width-section]."
303 :group 'org-keywords
304 :type 'string)
306 (defgroup org-structure nil
307 "Options concerning the general structure of Org-mode files."
308 :tag "Org Structure"
309 :group 'org)
311 (defgroup org-cycle nil
312 "Options concerning visibility cycling in Org-mode."
313 :tag "Org Cycle"
314 :group 'org-structure)
316 (defcustom org-cycle-global-at-bob t
317 "Cycle globally if cursor is at beginning of buffer and not at a headline.
318 This makes it possible to do global cycling without having to use S-TAB or
319 C-u TAB. For this special case to work, the first line of the buffer
320 must not be a headline - it may be empty ot some other text. When used in
321 this way, `org-cycle-hook' is disables temporarily, to make sure the
322 cursor stays at the beginning of the buffer.
323 When this option is nil, don't do anything special at the beginning
324 of the buffer."
325 :group 'org-cycle
326 :type 'boolean)
328 (defcustom org-cycle-emulate-tab t
329 "Where should `org-cycle' emulate TAB.
330 nil Never
331 white Only in completely white lines
332 whitestart Only at the beginning of lines, before the first non-white char.
333 t Everywhere except in headlines
334 If TAB is used in a place where it does not emulate TAB, the current subtree
335 visibility is cycled."
336 :group 'org-cycle
337 :type '(choice (const :tag "Never" nil)
338 (const :tag "Only in completely white lines" white)
339 (const :tag "Before first char in a line" whitestart)
340 (const :tag "Everywhere except in headlines" t)
343 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
344 org-optimize-window-after-visibility-change)
345 "Hook that is run after `org-cycle' has changed the buffer visibility.
346 The function(s) in this hook must accept a single argument which indicates
347 the new state that was set by the most recent `org-cycle' command. The
348 argument is a symbol. After a global state change, it can have the values
349 `overview', `content', or `all'. After a local state change, it can have
350 the values `folded', `children', or `subtree'."
351 :group 'org-cycle
352 :type 'hook)
354 (defgroup org-edit-structure nil
355 "Options concerning structure editing in Org-mode."
356 :tag "Org Edit Structure"
357 :group 'org-structure)
359 (defcustom org-odd-levels-only nil
360 "Non-nil means, skip even levels and only use odd levels for the outline.
361 This has the effect that two stars are being added/taken away in
362 promotion/demotion commands. It also influences how levels are
363 handled by the exporters.
364 Changing it requires restart of `font-lock-mode' to become effective
365 for fontification also in regions already fontified.
366 You may also set this on a per-file basis by adding one of the following
367 lines to the buffer:
369 #+STARTUP: odd
370 #+STARTUP: oddeven"
371 :group 'org-edit-structure
372 :group 'org-font-lock
373 :type 'boolean)
375 (defcustom org-adapt-indentation t
376 "Non-nil means, adapt indentation when promoting and demoting.
377 When this is set and the *entire* text in an entry is indented, the
378 indentation is increased by one space in a demotion command, and
379 decreased by one in a promotion command. If any line in the entry
380 body starts at column 0, indentation is not changed at all."
381 :group 'org-edit-structure
382 :type 'boolean)
384 (defcustom org-insert-heading-hook nil
385 "Hook being run after inserting a new heading."
386 :group 'org-edit-structure
387 :type 'boolean)
389 (defcustom org-enable-fixed-width-editor t
390 "Non-nil means, lines starting with \":\" are treated as fixed-width.
391 This currently only means, they are never auto-wrapped.
392 When nil, such lines will be treated like ordinary lines.
393 See also the QUOTE keyword."
394 :group 'org-edit-structure
395 :type 'boolean)
397 (defgroup org-sparse-trees nil
398 "Options concerning sparse trees in Org-mode."
399 :tag "Org Sparse Trees"
400 :group 'org-structure)
402 (defcustom org-highlight-sparse-tree-matches t
403 "Non-nil means, highlight all matches that define a sparse tree.
404 The highlights will automatically disappear the next time the buffer is
405 changed by an edit command."
406 :group 'org-sparse-trees
407 :type 'boolean)
409 (defcustom org-show-hierarchy-above t
410 "Non-nil means, show full hierarchy when showing a spot in the tree.
411 Turning this off makes sparse trees more compact, but also less clear."
412 :group 'org-sparse-trees
413 :type 'boolean)
415 (defcustom org-show-following-heading t
416 "Non-nil means, show heading following match in `org-occur'.
417 When doing an `org-occur' it is useful to show the headline which
418 follows the match, even if they do not match the regexp. This makes it
419 easier to edit directly inside the sparse tree. However, if you use
420 `org-occur' mainly as an overview, the following headlines are
421 unnecessary clutter."
422 :group 'org-sparse-trees
423 :type 'boolean)
425 (defcustom org-occur-hook '(org-first-headline-recenter)
426 "Hook that is run after `org-occur' has constructed a sparse tree.
427 This can be used to recenter the window to show as much of the structure
428 as possible."
429 :group 'org-sparse-trees
430 :type 'hook)
432 (defgroup org-plain-lists nil
433 "Options concerning plain lists in Org-mode."
434 :tag "Org Plain lists"
435 :group 'org-structure)
437 (defcustom org-cycle-include-plain-lists t
438 "Non-nil means, include plain lists into visibility cycling.
439 This means that during cycling, plain list items will *temporarily* be
440 interpreted as outline headlines with a level given by 1000+i where i is the
441 indentation of the bullet. In all other operations, plain list items are
442 not seen as headlines. For example, you cannot assign a TODO keyword to
443 such an item."
444 :group 'org-plain-lists
445 :type 'boolean)
447 (defcustom org-plain-list-ordered-item-terminator t
448 "The character that makes a line with leading number an ordered list item.
449 Valid values are ?. and ?\). To get both terminators, use t. While
450 ?. may look nicer, it creates the danger that a line with leading
451 number may be incorrectly interpreted as an item. ?\) therefore is
452 the safe choice."
453 :group 'org-plain-lists
454 :type '(choice (const :tag "dot like in \"2.\"" ?.)
455 (const :tag "paren like in \"2)\"" ?\))
456 (const :tab "both" t)))
458 (defcustom org-auto-renumber-ordered-lists t
459 "Non-nil means, automatically renumber ordered plain lists.
460 Renumbering happens when the sequence have been changed with
461 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
462 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
463 :group 'org-plain-lists
464 :type 'boolean)
466 (defcustom org-provide-checkbox-statistics t
467 "Non-nil means, update checkbox statistics after insert and toggle.
468 When this is set, checkbox statistics is updated each time you either insert
469 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
470 with \\[org-ctrl-c-ctrl-c\\]."
471 :group 'org
472 :type 'boolean)
474 (defgroup org-archive nil
475 "Options concerning archiving in Org-mode."
476 :tag "Org Archive"
477 :group 'org-structure)
479 (defcustom org-archive-tag "ARCHIVE"
480 "The tag that marks a subtree as archived.
481 An archived subtree does not open during visibility cycling, and does
482 not contribute to the agenda listings."
483 :group 'org-archive
484 :group 'org-keywords
485 :type 'string)
487 (defcustom org-agenda-skip-archived-trees t
488 "Non-nil means, the agenda will skip any items located in archived trees.
489 An archived tree is a tree marked with the tag ARCHIVE."
490 :group 'org-archive
491 :group 'org-agenda-display
492 :type 'boolean)
494 (defcustom org-cycle-open-archived-trees nil
495 "Non-nil means, `org-cycle' will open archived trees.
496 An archived tree is a tree marked with the tag ARCHIVE.
497 When nil, archived trees will stay folded. You can still open them with
498 normal outline commands like `show-all', but not with the cycling commands."
499 :group 'org-archive
500 :group 'org-cycle
501 :type 'boolean)
503 (defcustom org-sparse-tree-open-archived-trees nil
504 "Non-nil means sparse tree construction shows matches in archived trees.
505 When nil, matches in these trees are highlighted, but the trees are kept in
506 collapsed state."
507 :group 'org-archive
508 :group 'org-sparse-trees
509 :type 'boolean)
511 (defcustom org-archive-location "%s_archive::"
512 "The location where subtrees should be archived.
513 This string consists of two parts, separated by a double-colon.
515 The first part is a file name - when omitted, archiving happens in the same
516 file. %s will be replaced by the current file name (without directory part).
517 Archiving to a different file is useful to keep archived entries from
518 contributing to the Org-mode Agenda.
520 The part after the double colon is a headline. The archived entries will be
521 filed under that headline. When omitted, the subtrees are simply filed away
522 at the end of the file, as top-level entries.
524 Here are a few examples:
525 \"%s_archive::\"
526 If the current file is Projects.org, archive in file
527 Projects.org_archive, as top-level trees. This is the default.
529 \"::* Archived Tasks\"
530 Archive in the current file, under the top-level headline
531 \"* Archived Tasks\".
533 \"~/org/archive.org::\"
534 Archive in file ~/org/archive.org (absolute path), as top-level trees.
536 \"basement::** Finished Tasks\"
537 Archive in file ./basement (relative path), as level 3 trees
538 below the level 2 heading \"** Finished Tasks\".
540 You may set this option on a per-file basis by adding to the buffer a
541 line like
543 #+ARCHIVE: basement::** Finished Tasks"
544 :group 'org-archive
545 :type 'string)
547 (defcustom org-archive-mark-done t
548 "Non-nil means, mark entries as DONE when they are moved to the archive file."
549 :group 'org-archive
550 :type 'boolean)
552 (defcustom org-archive-stamp-time t
553 "Non-nil means, add a time stamp to entries moved to an archive file.
554 The time stamp will be added directly after the TODO state keyword in the
555 first line, so it is probably best to use this in combinations with
556 `org-archive-mark-done'."
557 :group 'org-archive
558 :type 'boolean)
560 (defgroup org-table nil
561 "Options concerning tables in Org-mode."
562 :tag "Org Table"
563 :group 'org)
565 (defcustom org-enable-table-editor 'optimized
566 "Non-nil means, lines starting with \"|\" are handled by the table editor.
567 When nil, such lines will be treated like ordinary lines.
569 When equal to the symbol `optimized', the table editor will be optimized to
570 do the following:
571 - Use automatic overwrite mode in front of whitespace in table fields.
572 This make the structure of the table stay in tact as long as the edited
573 field does not exceed the column width.
574 - Minimize the number of realigns. Normally, the table is aligned each time
575 TAB or RET are pressed to move to another field. With optimization this
576 happens only if changes to a field might have changed the column width.
577 Optimization requires replacing the functions `self-insert-command',
578 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
579 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
580 very good at guessing when a re-align will be necessary, but you can always
581 force one with \\[org-ctrl-c-ctrl-c].
583 If you would like to use the optimized version in Org-mode, but the
584 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
586 This variable can be used to turn on and off the table editor during a session,
587 but in order to toggle optimization, a restart is required.
589 See also the variable `org-table-auto-blank-field'."
590 :group 'org-table
591 :type '(choice
592 (const :tag "off" nil)
593 (const :tag "on" t)
594 (const :tag "on, optimized" optimized)))
596 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
597 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
598 In the optimized version, the table editor takes over all simple keys that
599 normally just insert a character. In tables, the characters are inserted
600 in a way to minimize disturbing the table structure (i.e. in overwrite mode
601 for empty fields). Outside tables, the correct binding of the keys is
602 restored.
604 The default for this option is t if the optimized version is also used in
605 Org-mode. See the variable `org-enable-table-editor' for details. Changing
606 this variable requires a restart of Emacs to become effective."
607 :group 'org-table
608 :type 'boolean)
610 (defgroup org-table-settings nil
611 "Settings for tables in Org-mode."
612 :tag "Org Table Settings"
613 :group 'org-table)
615 (defcustom org-table-default-size "5x2"
616 "The default size for newly created tables, Columns x Rows."
617 :group 'org-table-settings
618 :type 'string)
620 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
621 "Regular expression for recognizing numbers in table columns.
622 If a table column contains mostly numbers, it will be aligned to the
623 right. If not, it will be aligned to the left.
625 The default value of this option is a regular expression which allows
626 anything which looks remotely like a number as used in scientific
627 context. For example, all of the following will be considered a
628 number:
629 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
631 Other options offered by the customize interface are more restrictive."
632 :group 'org-table-settings
633 :type '(choice
634 (const :tag "Positive Integers"
635 "^[0-9]+$")
636 (const :tag "Integers"
637 "^[-+]?[0-9]+$")
638 (const :tag "Floating Point Numbers"
639 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
640 (const :tag "Floating Point Number or Integer"
641 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
642 (const :tag "Exponential, Floating point, Integer"
643 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
644 (const :tag "Very General Number-Like"
645 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
646 (string :tag "Regexp:")))
648 (defcustom org-table-number-fraction 0.5
649 "Fraction of numbers in a column required to make the column align right.
650 In a column all non-white fields are considered. If at least this
651 fraction of fields is matched by `org-table-number-fraction',
652 alignment to the right border applies."
653 :group 'org-table-settings
654 :type 'number)
656 (defgroup org-table-editing nil
657 "Bahavior of tables during editing in Org-mode."
658 :tag "Org Table Editing"
659 :group 'org-table)
661 (defcustom org-table-automatic-realign t
662 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
663 When nil, aligning is only done with \\[org-table-align], or after column
664 removal/insertion."
665 :group 'org-table-editing
666 :type 'boolean)
668 (defcustom org-table-limit-column-width t ;kw
669 "Non-nil means, allow to limit the width of table columns with <N> fields."
670 :group 'org-table-editing
671 :type 'boolean)
673 (defcustom org-table-auto-blank-field t
674 "Non-nil means, automatically blank table field when starting to type into it.
675 This only happens when typing immediately after a field motion
676 command (TAB, S-TAB or RET).
677 Only relevant when `org-enable-table-editor' is equal to `optimized'."
678 :group 'org-table-editing
679 :type 'boolean)
681 (defcustom org-table-tab-jumps-over-hlines t
682 "Non-nil means, tab in the last column of a table with jump over a hline.
683 If a horizontal separator line is following the current line,
684 `org-table-next-field' can either create a new row before that line, or jump
685 over the line. When this option is nil, a new line will be created before
686 this line."
687 :group 'org-table-editing
688 :type 'boolean)
690 (defcustom org-table-tab-recognizes-table.el t
691 "Non-nil means, TAB will automatically notice a table.el table.
692 When it sees such a table, it moves point into it and - if necessary -
693 calls `table-recognize-table'."
694 :group 'org-table-editing
695 :type 'boolean)
697 (defgroup org-table-calculation nil
698 "Options concerning tables in Org-mode."
699 :tag "Org Table Calculation"
700 :group 'org-table)
702 (defcustom org-table-copy-increment t
703 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
704 :group 'org-table-calculation
705 :type 'boolean)
707 (defcustom org-calc-default-modes
708 '(calc-internal-prec 12
709 calc-float-format (float 5)
710 calc-angle-mode deg
711 calc-prefer-frac nil
712 calc-symbolic-mode nil
713 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
714 calc-display-working-message t
716 "List with Calc mode settings for use in calc-eval for table formulas.
717 The list must contain alternating symbols (Calc modes variables and values).
718 Don't remove any of the default settings, just change the values. Org-mode
719 relies on the variables to be present in the list."
720 :group 'org-table-calculation
721 :type 'plist)
723 (defcustom org-table-formula-evaluate-inline t
724 "Non-nil means, TAB and RET evaluate a formula in current table field.
725 If the current field starts with an equal sign, it is assumed to be a formula
726 which should be evaluated as described in the manual and in the documentation
727 string of the command `org-table-eval-formula'. This feature requires the
728 Emacs calc package.
729 When this variable is nil, formula calculation is only available through
730 the command \\[org-table-eval-formula]."
731 :group 'org-table-calculation
732 :type 'boolean)
735 (defcustom org-table-formula-use-constants t
736 "Non-nil means, interpret constants in formulas in tables.
737 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
738 by the value given in `org-table-formula-constants', or by a value obtained
739 from the `constants.el' package."
740 :group 'org-table-calculation
741 :type 'boolean)
743 (defcustom org-table-formula-constants nil
744 "Alist with constant names and values, for use in table formulas.
745 The car of each element is a name of a constant, without the `$' before it.
746 The cdr is the value as a string. For example, if you'd like to use the
747 speed of light in a formula, you would configure
749 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
751 and then use it in an equation like `$1*$c'."
752 :group 'org-table-calculation
753 :type '(repeat
754 (cons (string :tag "name")
755 (string :tag "value"))))
757 (defcustom org-table-formula-numbers-only nil
758 "Non-nil means, calculate only with numbers in table formulas.
759 Then all input fields will be converted to a number, and the result
760 must also be a number. When nil, calc's full potential is available
761 in table calculations, including symbolics etc."
762 :group 'org-table-calculation
763 :type 'boolean)
765 (defcustom org-table-allow-automatic-line-recalculation t
766 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
767 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
768 :group 'org-table-calculation
769 :type 'boolean)
771 (defgroup org-link nil
772 "Options concerning links in Org-mode."
773 :tag "Org Link"
774 :group 'org)
776 (defcustom org-descriptive-links t
777 "Non-nil means, hide link part and only show description of bracket links.
778 Bracket links are like [[link][descritpion]]. This variable sets the initial
779 state in new org-mode buffers. The setting can then be toggled on a
780 per-buffer basis from the Org->Hyperlinks menu."
781 :group 'org-link
782 :type 'boolean)
784 (defcustom org-link-style 'bracket
785 "The style of links to be inserted with \\[org-insert-link].
786 Possible values are:
787 bracket [[link][description]]. This is recommended
788 plain Description \\n link. The old way, no longer recommended."
789 :group 'org-link
790 :type '(choice
791 (const :tag "Bracket (recommended)" bracket)
792 (const :tag "Plain (no longer recommended)" plain)))
794 (defcustom org-link-format "%s"
795 "Default format for external, URL-like linkes in the buffer.
796 This is a format string for printf, %s will be replaced by the link text.
797 The recommended value is just \"%s\", since links will be protected by
798 enclosing them in double brackets. If you prefer plain links (see variable
799 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
800 additional URL: prefix, so the format would be \"<URL:%s>\"."
801 :group 'org-link
802 :type '(choice
803 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
804 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
805 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
806 (string :tag "Other" :value "<%s>")))
808 (defcustom org-link-file-path-type 'adaptive
809 "How the path name in file links should be stored.
810 Valid values are:
812 relative relative to the current directory, i.e. the directory of the file
813 into which the link is being inserted.
814 absolute absolute path, if possible with ~ for home directory.
815 noabbrev absolute path, no abbreviation of home directory.
816 adaptive Use relative path for files in the current directory and sub-
817 directories of it. For other files, use an absolute path."
818 :group 'org-link
819 :type '(choice
820 (const relative)
821 (const absolute)
822 (const noabbrev)
823 (const adaptive)))
825 (defcustom org-activate-links '(bracket angle plain radio tag date)
826 "Types of links that should be activated in Org-mode files.
827 This is a list of symbols, each leading to the activation of a certain link
828 type. In principle, it does not hurt to turn on most link types - there may
829 be a small gain when turning off unused link types. The types are:
831 bracket The recommended [[link][description]] or [[link]] links with hiding.
832 angular Links in angular brackes that may contain whitespace like
833 <bbdb:Carsten Dominik>.
834 plain Plain links in normal text, no whitespace, like http://google.com.
835 radio Text that is matched by a radio target, see manual for details.
836 tag Tag settings in a headline (link to tag search).
837 date Time stamps (link to calendar).
838 camel CamelCase words defining text searches.
840 Changing this variable requires a restart of Emacs to become effective."
841 :group 'org-link
842 :type '(set (const :tag "Double bracket links (new style)" bracket)
843 (const :tag "Angular bracket links (old style)" angular)
844 (const :tag "plain text links" plain)
845 (const :tag "Radio target matches" radio)
846 (const :tag "Tags" tag)
847 (const :tag "Timestamps" date)
848 (const :tag "CamelCase words" camel)))
850 (defgroup org-link-store nil
851 "Options concerning storing links in Org-mode"
852 :tag "Org Store Link"
853 :group 'org-link)
855 (defcustom org-context-in-file-links t
856 "Non-nil means, file links from `org-store-link' contain context.
857 A search string will be added to the file name with :: as separator and
858 used to find the context when the link is activated by the command
859 `org-open-at-point'.
860 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
861 negates this setting for the duration of the command."
862 :group 'org-link-store
863 :type 'boolean)
865 (defcustom org-file-link-context-use-camel-case nil
866 "Non-nil means, use CamelCase to store a search context in a file link.
867 When nil, the search string simply consists of the words of the string.
868 CamelCase is deprecated, and support for it may be dropped in the future."
869 :group 'org-link-store
870 :type 'boolean)
872 (defcustom org-keep-stored-link-after-insertion nil
873 "Non-nil means, keep link in list for entire session.
875 The command `org-store-link' adds a link pointing to the current
876 location to an internal list. These links accumulate during a session.
877 The command `org-insert-link' can be used to insert links into any
878 Org-mode file (offering completion for all stored links). When this
879 option is nil, every link which has been inserted once using \\[org-insert-link]
880 will be removed from the list, to make completing the unused links
881 more efficient."
882 :group 'org-link-store
883 :type 'boolean)
885 (defcustom org-usenet-links-prefer-google nil
886 "Non-nil means, `org-store-link' will create web links to Google groups.
887 When nil, Gnus will be used for such links.
888 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
889 negates this setting for the duration of the command."
890 :group 'org-link-store
891 :type 'boolean)
893 (defgroup org-link-follow nil
894 "Options concerning following links in Org-mode"
895 :tag "Org Follow Link"
896 :group 'org-link)
898 (defcustom org-tab-follows-link nil
899 "Non-nil means, on links TAB will follow the link.
900 Needs to be set before org.el is loaded."
901 :group 'org-link-follow
902 :type 'boolean)
904 (defcustom org-return-follows-link nil
905 "Non-nil means, on links RET will follow the link.
906 Needs to be set before org.el is loaded."
907 :group 'org-link-follow
908 :type 'boolean)
910 (defcustom org-mouse-1-follows-link t
911 "Non-nil means, mouse-1 on a link will follow the link.
912 A longer mouse click will still set point. Does not wortk on XEmacs.
913 Needs to be set before org.el is loaded."
914 :group 'org-link-follow
915 :type 'boolean)
917 (defcustom org-mark-ring-length 4
918 "Number of different positions to be recorded in the ring
919 Changing this requires a restart of Emacs to work correctly."
920 :group 'org-link-follow
921 :type 'interger)
923 (defcustom org-link-frame-setup
924 '((vm . vm-visit-folder-other-frame)
925 (gnus . gnus-other-frame)
926 (file . find-file-other-window))
927 "Setup the frame configuration for following links.
928 When following a link with Emacs, it may often be useful to display
929 this link in another window or frame. This variable can be used to
930 set this up for the different types of links.
931 For VM, use any of
932 `vm-visit-folder'
933 `vm-visit-folder-other-frame'
934 For Gnus, use any of
935 `gnus'
936 `gnus-other-frame'
937 For FILE, use any of
938 `find-file'
939 `find-file-other-window'
940 `find-file-other-frame'
941 For the calendar, use the variable `calendar-setup'.
942 For BBDB, it is currently only possible to display the matches in
943 another window."
944 :group 'org-link-follow
945 :type '(list
946 (cons (const vm)
947 (choice
948 (const vm-visit-folder)
949 (const vm-visit-folder-other-window)
950 (const vm-visit-folder-other-frame)))
951 (cons (const gnus)
952 (choice
953 (const gnus)
954 (const gnus-other-frame)))
955 (cons (const file)
956 (choice
957 (const find-file)
958 (const find-file-other-window)
959 (const find-file-other-frame)))))
961 (defcustom org-open-non-existing-files nil
962 "Non-nil means, `org-open-file' will open non-existing file.
963 When nil, an error will be generated."
964 :group 'org-link-follow
965 :type 'boolean)
967 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
968 "Function and arguments to call for following mailto links.
969 This is a list with the first element being a lisp function, and the
970 remaining elements being arguments to the function. In string arguments,
971 %a will be replaced by the address, and %s will be replaced by the subject
972 if one was given like in <mailto:arthur@galaxy.org::this subject>."
973 :group 'org-link-follow
974 :type '(choice
975 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
976 (const :tag "compose-mail" (compose-mail "%a" "%s"))
977 (const :tag "message-mail" (message-mail "%a" "%s"))
978 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
980 (defcustom org-confirm-shell-link-function 'yes-or-no-p
981 "Non-nil means, ask for confirmation before executing shell links.
982 Shell links can be dangerous, just thing about a link
984 [[shell:rm -rf ~/*][Google Search]]
986 This link would show up in your Org-mode document as \"Google Search\"
987 but really it would remove your entire home directory.
988 Therefore I *definitely* advise against setting this variable to nil.
989 Just change it to `y-or-n-p' of you want to confirm with a single key press
990 rather than having to type \"yes\"."
991 :group 'org-link-follow
992 :type '(choice
993 (const :tag "with yes-or-no (safer)" yes-or-no-p)
994 (const :tag "with y-or-n (faster)" y-or-n-p)
995 (const :tag "no confirmation (dangerous)" nil)))
997 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
998 "Non-nil means, ask for confirmation before executing elisp links.
999 Elisp links can be dangerous, just thing about a link
1001 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1003 This link would show up in your Org-mode document as \"Google Search\"
1004 but really it would remove your entire home directory.
1005 Therefore I *definitely* advise against setting this variable to nil.
1006 Just change it to `y-or-n-p' of you want to confirm with a single key press
1007 rather than having to type \"yes\"."
1008 :group 'org-link-follow
1009 :type '(choice
1010 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1011 (const :tag "with y-or-n (faster)" y-or-n-p)
1012 (const :tag "no confirmation (dangerous)" nil)))
1014 (defconst org-file-apps-defaults-gnu
1015 '((remote . emacs)
1016 (t . mailcap))
1017 "Default file applications on a UNIX or GNU/Linux system.
1018 See `org-file-apps'.")
1020 (defconst org-file-apps-defaults-macosx
1021 '((remote . emacs)
1022 (t . "open %s")
1023 ("ps" . "gv %s")
1024 ("ps.gz" . "gv %s")
1025 ("eps" . "gv %s")
1026 ("eps.gz" . "gv %s")
1027 ("dvi" . "xdvi %s")
1028 ("fig" . "xfig %s"))
1029 "Default file applications on a MacOS X system.
1030 The system \"open\" is known as a default, but we use X11 applications
1031 for some files for which the OS does not have a good default.
1032 See `org-file-apps'.")
1034 (defconst org-file-apps-defaults-windowsnt
1035 (list
1036 '(remote . emacs)
1037 (cons t
1038 (list (if (featurep 'xemacs)
1039 'mswindows-shell-execute
1040 'w32-shell-execute)
1041 "open" 'file)))
1042 "Default file applications on a Windows NT system.
1043 The system \"open\" is used for most files.
1044 See `org-file-apps'.")
1046 (defcustom org-file-apps
1048 ("txt" . emacs)
1049 ("tex" . emacs)
1050 ("ltx" . emacs)
1051 ("org" . emacs)
1052 ("el" . emacs)
1053 ("bib" . emacs)
1055 "External applications for opening `file:path' items in a document.
1056 Org-mode uses system defaults for different file types, but
1057 you can use this variable to set the application for a given file
1058 extension. The entries in this list are cons cells where the car identifies
1059 files and the cdr the corresponding command. Possible values for the
1060 file identifier are
1061 \"ext\" A string identifying an extension
1062 `directory' Matches a directory
1063 `remote' Matches a remote file, accessible through tramp or efs.
1064 Remote files most likely should be visited through emacs
1065 because external applications cannot handle such paths.
1066 t Default for all remaining files
1068 Possible values for the command are:
1069 `emacs' The file will be visited by the current Emacs process.
1070 `default' Use the default application for this file type.
1071 string A command to be executed by a shell; %s will be replaced
1072 by the path to the file.
1073 sexp A Lisp form which will be evaluated. The file path will
1074 be available in the Lisp variable `file'.
1075 For more examples, see the system specific constants
1076 `org-file-apps-defaults-macosx'
1077 `org-file-apps-defaults-windowsnt'
1078 `org-file-apps-defaults-gnu'."
1079 :group 'org-link-follow
1080 :type '(repeat
1081 (cons (choice :value ""
1082 (string :tag "Extension")
1083 (const :tag "Default for unrecognized files" t)
1084 (const :tag "Remote file" remote)
1085 (const :tag "Links to a directory" directory))
1086 (choice :value ""
1087 (const :tag "Visit with Emacs" emacs)
1088 (const :tag "Use system default" default)
1089 (string :tag "Command")
1090 (sexp :tag "Lisp form")))))
1092 (defcustom org-mhe-search-all-folders nil
1093 "Non-nil means, that the search for the mh-message will be extended to
1094 all folders if the message cannot be found in the folder given in the link.
1095 Searching all folders is very effective with one of the search engines
1096 supported by MH-E, but will be slow with pick."
1097 :group 'org-link-follow
1098 :type 'boolean)
1100 (defgroup org-remember nil
1101 "Options concerning interaction with remember.el."
1102 :tag "Org Remember"
1103 :group 'org)
1105 (defcustom org-directory "~/org"
1106 "Directory with org files.
1107 This directory will be used as default to prompt for org files.
1108 Used by the hooks for remember.el."
1109 :group 'org-remember
1110 :type 'directory)
1112 (defcustom org-default-notes-file "~/.notes"
1113 "Default target for storing notes.
1114 Used by the hooks for remember.el. This can be a string, or nil to mean
1115 the value of `remember-data-file'."
1116 :group 'org-remember
1117 :type '(choice
1118 (const :tag "Default from remember-data-file" nil)
1119 file))
1121 (defcustom org-remember-templates nil
1122 "Templates for the creation of remember buffers.
1123 When nil, just let remember make the buffer.
1124 When not nil, this is a list of 3-element lists. In each entry, the first
1125 element is a character, a unique key to select this template.
1126 The second element is the template. The third element is optional and can
1127 specify a destination file for remember items created with this template.
1128 The default file is given by `org-default-notes-file'.
1130 The template specifies the structure of the remember buffer. It should have
1131 a first line starting with a star, to act as the org-mode headline.
1132 Furthermore, the following %-escapes will be replaced with content:
1133 %t time stamp, date only
1134 %T time stamp with date and time
1135 %u inactive time stamp, date only
1136 %U inactive time stamp with date and time
1137 %n user name
1138 %a annotation, normally the link created with org-store-link
1139 %i initial content, the region when remember is called with C-u.
1140 If %i is indented, the entire inserted text will be indented as well.
1141 %? This will be removed, and the cursor placed at this position."
1142 :group 'org-remember
1143 :type '(repeat :tag "enabled"
1144 (list :value (?a "\n" nil)
1145 (character :tag "Selection Key")
1146 (string :tag "Template")
1147 (file :tag "Destination file (optional)"))))
1149 (defcustom org-reverse-note-order nil
1150 "Non-nil means, store new notes at the beginning of a file or entry.
1151 When nil, new notes will be filed to the end of a file or entry."
1152 :group 'org-remember
1153 :type '(choice
1154 (const :tag "Reverse always" t)
1155 (const :tag "Reverse never" nil)
1156 (repeat :tag "By file name regexp"
1157 (cons regexp boolean))))
1159 (defgroup org-todo nil
1160 "Options concerning TODO items in Org-mode."
1161 :tag "Org TODO"
1162 :group 'org)
1164 (defcustom org-todo-keywords '("TODO" "DONE")
1165 "List of TODO entry keywords.
1166 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1167 considered to mean that the entry is \"done\". All the other mean that
1168 action is required, and will make the entry show up in todo lists, diaries
1169 etc.
1170 The command \\[org-todo] cycles an entry through these states, and an
1171 additional state where no keyword is present. For details about this
1172 cycling, see also the variable `org-todo-interpretation'
1173 Changes become only effective after restarting Emacs."
1174 :group 'org-todo
1175 :group 'org-keywords
1176 :type '(repeat (string :tag "Keyword")))
1178 (defcustom org-todo-interpretation 'sequence
1179 "Controls how TODO keywords are interpreted.
1180 This variable is only relevant if `org-todo-keywords' contains more than two
1181 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1183 When `sequence', \\[org-todo] will always switch to the next state in the
1184 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1185 to state when executed several times in direct succession. Otherwise, it
1186 switches directly to DONE from any state.
1187 See the manual for more information."
1188 :group 'org-todo
1189 :group 'org-keywords
1190 :type '(choice (const sequence)
1191 (const type)))
1193 (defcustom org-after-todo-state-change-hook nil
1194 "Hook which is run after the state of a TODO item was changed.
1195 The new state (a string with a TODO keyword, or nil) is available in the
1196 Lisp variable `state'."
1197 :group 'org-todo
1198 :type 'hook)
1200 (defcustom org-log-done nil
1201 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1202 When the state of an entry is changed from nothing to TODO, remove a previous
1203 closing date.
1204 This can also be configured on a per-file basis by adding one of
1205 the following lines anywhere in the buffer:
1207 #+STARTUP: logging
1208 #+STARTUP: nologging"
1209 :group 'org-todo
1210 :type 'boolean)
1212 (defgroup org-priorities nil
1213 "Priorities in Org-mode."
1214 :tag "Org Priorities"
1215 :group 'org-todo)
1217 (defcustom org-default-priority ?B
1218 "The default priority of TODO items.
1219 This is the priority an item get if no explicit priority is given."
1220 :group 'org-priorities
1221 :type 'character)
1223 (defcustom org-lowest-priority ?C
1224 "The lowest priority of TODO items. A character like ?A, ?B etc."
1225 :group 'org-priorities
1226 :type 'character)
1228 (defgroup org-time nil
1229 "Options concerning time stamps and deadlines in Org-mode."
1230 :tag "Org Time"
1231 :group 'org)
1233 (defcustom org-insert-labeled-timestamps-at-point nil
1234 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1235 When nil, these labeled time stamps are forces into the second line of an
1236 entry, just after the headline. When scheduling from the global TODO list,
1237 the time stamp will always be forced into the second line."
1238 :group 'org-time
1239 :type 'boolean)
1241 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1242 "Formats for `format-time-string' which are used for time stamps.
1243 It is not recommended to change this constant.")
1245 (defcustom org-time-stamp-rounding-minutes 0
1246 "Number of minutes to round time stamps to upon insertion.
1247 When zero, insert the time unmodified. Useful rounding numbers
1248 should be factors of 60, so for example 5, 10, 15.
1249 When this is not zero, you can still force an exact time-stamp by using
1250 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1251 :group 'org-time
1252 :type 'integer)
1254 (defcustom org-deadline-warning-days 30
1255 "No. of days before expiration during which a deadline becomes active.
1256 This variable governs the display in the org file."
1257 :group 'org-time
1258 :type 'number)
1260 (defcustom org-popup-calendar-for-date-prompt t
1261 "Non-nil means, pop up a calendar when prompting for a date.
1262 In the calendar, the date can be selected with mouse-1. However, the
1263 minibuffer will also be active, and you can simply enter the date as well.
1264 When nil, only the minibuffer will be available."
1265 :group 'org-time
1266 :type 'boolean)
1268 (defcustom org-calendar-follow-timestamp-change t
1269 "Non-nil means, make the calendar window follow timestamp changes.
1270 When a timestamp is modified and the calendar window is visible, it will be
1271 moved to the new date."
1272 :group 'org-time
1273 :type 'boolean)
1275 (defgroup org-tags nil
1276 "Options concerning tags in Org-mode."
1277 :tag "Org Tags"
1278 :group 'org)
1280 (defcustom org-tag-alist nil
1281 "List of tags allowed in Org-mode files.
1282 When this list is nil, Org-mode will base TAG input on what is already in the
1283 buffer.
1284 The value of this variable is an alist, the car may be (and should) be a
1285 character that is used to select that tag through the fast-tag-selection
1286 interface. See the manual for details."
1287 :group 'org-tags
1288 :type '(repeat
1289 (choice
1290 (cons (string :tag "Tag name")
1291 (character :tag "Access char"))
1292 (const :tag "Start radio group" (:startgroup))
1293 (const :tag "End radio group" (:endgroup)))))
1295 (defcustom org-use-fast-tag-selection 'auto
1296 "Non-nil means, use fast tag selection scheme.
1297 This is a special interface to select and deselect tags with single keys.
1298 When nil, fast selection is never used.
1299 When the symbol `auto', fast selection is used if and only if selection
1300 characters for tags have been configured, either through the variable
1301 `org-tag-alist' or through a #+TAGS line in the buffer.
1302 When t, fast selection is always used and selection keys are assigned
1303 automatically if necessary."
1304 :group 'org-tags
1305 :type '(choice
1306 (const :tag "Always" t)
1307 (const :tag "Never" nil)
1308 (const :tag "When selection characters are configured" 'auto)))
1310 (defcustom org-tags-column 48
1311 "The column to which tags should be indented in a headline.
1312 If this number is positive, it specifies the column. If it is negative,
1313 it means that the tags should be flushright to that column. For example,
1314 -79 works well for a normal 80 character screen."
1315 :group 'org-tags
1316 :type 'integer)
1318 (defcustom org-auto-align-tags t
1319 "Non-nil means, realign tags after pro/demotion of TODO state change.
1320 These operations change the length of a headline and therefore shift
1321 the tags around. With this options turned on, after each such operation
1322 the tags are again aligned to `org-tags-column'."
1323 :group 'org-tags
1324 :type 'boolean)
1326 (defcustom org-use-tag-inheritance t
1327 "Non-nil means, tags in levels apply also for sublevels.
1328 When nil, only the tags directly given in a specific line apply there.
1329 If you turn off this option, you very likely want to turn on the
1330 companion option `org-tags-match-list-sublevels'."
1331 :group 'org-tags
1332 :type 'boolean)
1334 (defcustom org-tags-match-list-sublevels nil
1335 "Non-nil means list also sublevels of headlines matching tag search.
1336 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1337 the sublevels of a headline matching a tag search often also match
1338 the same search. Listing all of them can create very long lists.
1339 Setting this variable to nil causes subtrees of a match to be skipped.
1340 This option is off by default, because inheritance in on. If you turn
1341 inheritance off, you very likely want to turn this option on.
1343 As a special case, if the tag search is restricted to TODO items, the
1344 value of this variable is ignored and sublevels are always checked, to
1345 make sure all corresponding TODO items find their way into the list."
1346 :group 'org-tags
1347 :type 'boolean)
1349 (defvar org-tags-history nil
1350 "History of minibuffer reads for tags.")
1351 (defvar org-last-tags-completion-table nil
1352 "The last used completion table for tags.")
1354 (defgroup org-agenda nil
1355 "Options concerning agenda display Org-mode."
1356 :tag "Org Agenda"
1357 :group 'org)
1359 (defvar org-category nil
1360 "Variable used by org files to set a category for agenda display.
1361 Such files should use a file variable to set it, for example
1363 -*- mode: org; org-category: \"ELisp\"
1365 or contain a special line
1367 #+CATEGORY: ELisp
1369 If the file does not specify a category, then file's base name
1370 is used instead.")
1371 (make-variable-buffer-local 'org-category)
1373 (defcustom org-agenda-files nil
1374 "The files to be used for agenda display.
1375 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1376 \\[org-remove-file]. You can also use customize to edit the list.
1378 If the value of the variable is not a list but a single file name, then
1379 the list of agenda files is actually stored and maintained in that file, one
1380 agenda file per line."
1381 :group 'org-agenda
1382 :type '(choice
1383 (repeat :tag "List of files" file)
1384 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1386 (defcustom org-agenda-custom-commands ;'(("w" todo "WAITING"))
1387 '(("w" todo "WAITING" ((aaa 1) (bbb 2))))
1388 "Custom commands for the agenda.
1389 These commands will be offered on the splash screen displayed by the
1390 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1392 (key type match options)
1394 key The key (a single char as a string) to be associated with the command.
1395 type The command type, any of the following symbols:
1396 todo Entries with a specific TODO keyword, in all agenda files.
1397 tags Tags match in all agenda files.
1398 tags-todo Tags match in all agenda files, TODO entries only.
1399 todo-tree Sparse tree of specific TODO keyword in *current* file.
1400 tags-tree Sparse tree with all tags matches in *current* file.
1401 occur-tree Occur sparse tree for *current* file.
1402 match What to search for:
1403 - a single keyword for TODO keyword searches
1404 - a tags match expression for tags searches
1405 - a regular expression for occur searches
1406 options A list of option setttings, similar to that in a let form, so like
1407 this: ((opt1 val1) (opt2 val2) ...)
1409 You can also define a set of commands, to create a composite agenda buffer.
1410 In this case, an entry looks like this:
1412 (key desc (cmd1 cmd2 ...) general-options)
1414 where
1416 desc A description string to be displayed in the dispatcher menu.
1417 cmd An agenda command, similar to the above. However, tree commands
1418 are no allowed, but instead you can get agenda and global todo list.
1419 So valid commands for a set are:
1420 (agenda)
1421 (alltodo)
1422 (todo \"match\" options)
1423 (tags \"match\" options )
1424 (tags-todo \"match\" options)
1426 Each command can carry a list of options, and another set of options can be
1427 given for the whole set of commands. Individual command options take
1428 precedence over the general options."
1429 :group 'org-agenda
1430 :type '(repeat
1431 (choice
1432 (list :tag "Single command"
1433 (string :tag "Key")
1434 (choice
1435 (const :tag "Tags search (all agenda files)" tags)
1436 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1437 (const :tag "TODO keyword search (all agenda files)" todo)
1438 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1439 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1440 (const :tag "Occur tree (current buffer)" occur-tree))
1441 (string :tag "Match")
1442 (repeat :tag "Local options"
1443 (list (variable :tag "Option") (sexp :tag "Value"))))
1444 (list :tag "Command series, all agenda files"
1445 (string :tag "Key")
1446 (string :tag "Description")
1447 (repeat
1448 (choice
1449 (const :tag "Agenda" (agenda))
1450 (const :tag "TODO list" (alltodo))
1451 (list :tag "Tags search"
1452 (const :format "" tags)
1453 (string :tag "Match")
1454 (repeat :tag "Local options"
1455 (list (variable :tag "Option")
1456 (sexp :tag "Value"))))
1458 (list :tag "Tags search, TODO entries only"
1459 (const :format "" tags-todo)
1460 (string :tag "Match")
1461 (repeat :tag "Local options"
1462 (list (variable :tag "Option")
1463 (sexp :tag "Value"))))
1465 (list :tag "TODO keyword search"
1466 (const :format "" todo)
1467 (string :tag "Match")
1468 (repeat :tag "Local options"
1469 (list (variable :tag "Option")
1470 (sexp :tag "Value"))))))
1471 (repeat :tag "General options"
1472 (list (variable :tag "Option")
1473 (sexp :tag "Value")))))))
1475 (defcustom org-agenda-todo-list-sublevels t
1476 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1477 When nil, the sublevels of a TODO entry are not checked, resulting in
1478 potentially much shorter TODO lists."
1479 :group 'org-agenda
1480 :group 'org-todo
1481 :type 'boolean)
1483 (defcustom org-agenda-todo-ignore-scheduled nil
1484 "Non-nil means, don't show scheduled entries in the global todo list.
1485 The idea behind this is that by scheduling it, you have already taken care
1486 of this item."
1487 :group 'org-agenda
1488 :group 'org-todo
1489 :type 'boolean)
1491 (defcustom org-timeline-show-empty-dates 3
1492 "Non-nil means, `org-timeline' also shows dates without an entry.
1493 When nil, only the days which actually have entries are shown.
1494 When t, all days between the first and the last date are shown.
1495 When an integer, show also empty dates, but if there is a gap of more than
1496 N days, just insert a special line indicating the size of the gap."
1497 :group 'org-agenda
1498 :type '(choice
1499 (const :tag "None" nil)
1500 (const :tag "All" t)
1501 (number :tag "at most")))
1503 (defcustom org-agenda-include-all-todo nil
1504 "Set means weekly/daily agenda will always contain all TODO entries.
1505 The TODO entries will be listed at the top of the agenda, before
1506 the entries for specific days."
1507 :group 'org-agenda
1508 :type 'boolean)
1510 (defcustom org-agenda-include-diary nil
1511 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1512 :group 'org-agenda
1513 :type 'boolean)
1515 (defcustom org-calendar-to-agenda-key [?c]
1516 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1517 The command `org-calendar-goto-agenda' will be bound to this key. The
1518 default is the character `c' because then `c' can be used to switch back and
1519 forth between agenda and calendar."
1520 :group 'org-agenda
1521 :type 'sexp)
1523 (defgroup org-agenda-setup nil
1524 "Options concerning setting up the Agenda window in Org Mode."
1525 :tag "Org Agenda Window Setup"
1526 :group 'org-agenda)
1528 (defcustom org-agenda-mouse-1-follows-link nil
1529 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1530 A longer mouse click will still set point. Does not wortk on XEmacs.
1531 Needs to be set before org.el is loaded."
1532 :group 'org-agenda-setup
1533 :type 'boolean)
1535 (defcustom org-agenda-start-with-follow-mode nil
1536 "The initial value of follwo-mode in a newly created agenda window."
1537 :group 'org-agenda-setup
1538 :type 'boolean)
1540 (defcustom org-select-agenda-window t
1541 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1542 When nil, cursor will remain in the current window."
1543 :group 'org-agenda-setup
1544 :type 'boolean)
1546 (defcustom org-fit-agenda-window t
1547 "Non-nil means, change window size of agenda to fit content."
1548 :group 'org-agenda-setup
1549 :type 'boolean)
1551 (defgroup org-agenda-display nil
1552 "Options concerning what to display initially in Agenda."
1553 :tag "Org Agenda Display"
1554 :group 'org-agenda)
1556 (defcustom org-agenda-show-all-dates t
1557 "Non-nil means, `org-agenda' shows every day in the selected range.
1558 When nil, only the days which actually have entries are shown."
1559 :group 'org-agenda-display
1560 :type 'boolean)
1562 (defcustom org-agenda-start-on-weekday 1
1563 "Non-nil means, start the overview always on the specified weekday.
1564 0 denotes Sunday, 1 denotes Monday etc.
1565 When nil, always start on the current day."
1566 :group 'org-agenda-display
1567 :type '(choice (const :tag "Today" nil)
1568 (number :tag "Weekday No.")))
1570 (defcustom org-agenda-ndays 7
1571 "Number of days to include in overview display.
1572 Should be 1 or 7."
1573 :group 'org-agenda-display
1574 :type 'number)
1576 (defcustom org-agenda-use-time-grid t
1577 "Non-nil means, show a time grid in the agenda schedule.
1578 A time grid is a set of lines for specific times (like every two hours between
1579 8:00 and 20:00). The items scheduled for a day at specific times are
1580 sorted in between these lines.
1581 For details about when the grid will be shown, and what it will look like, see
1582 the variable `org-agenda-time-grid'."
1583 :group 'org-agenda-display
1584 :type 'boolean)
1586 (defcustom org-agenda-time-grid
1587 '((daily today require-timed)
1588 "----------------"
1589 (800 1000 1200 1400 1600 1800 2000))
1591 "The settings for time grid for agenda display.
1592 This is a list of three items. The first item is again a list. It contains
1593 symbols specifying conditions when the grid should be displayed:
1595 daily if the agenda shows a single day
1596 weekly if the agenda shows an entire week
1597 today show grid on current date, independent of daily/weekly display
1598 require-timed show grid only if at least one item has a time specification
1600 The second item is a string which will be places behing the grid time.
1602 The third item is a list of integers, indicating the times that should have
1603 a grid line."
1604 :group 'org-agenda-display
1605 :type
1606 '(list
1607 (set :greedy t :tag "Grid Display Options"
1608 (const :tag "Show grid in single day agenda display" daily)
1609 (const :tag "Show grid in weekly agenda display" weekly)
1610 (const :tag "Always show grid for today" today)
1611 (const :tag "Show grid only if any timed entries are present"
1612 require-timed)
1613 (const :tag "Skip grid times already present in an entry"
1614 remove-match))
1615 (string :tag "Grid String")
1616 (repeat :tag "Grid Times" (integer :tag "Time"))))
1618 (let ((sorting-choice
1619 '(choice
1620 (const time-up) (const time-down)
1621 (const category-keep) (const category-up) (const category-down)
1622 (const tag-down) (const tag-up)
1623 (const priority-up) (const priority-down))))
1625 (defcustom org-agenda-sorting-strategy
1626 '((agenda time-up category-keep priority-down)
1627 (todo category-keep priority-down)
1628 (tags category-keep))
1629 "Sorting structure for the agenda items of a single day.
1630 This is a list of symbols which will be used in sequence to determine
1631 if an entry should be listed before another entry. The following
1632 symbols are recognized:
1634 time-up Put entries with time-of-day indications first, early first
1635 time-down Put entries with time-of-day indications first, late first
1636 category-keep Keep the default order of categories, corresponding to the
1637 sequence in `org-agenda-files'.
1638 category-up Sort alphabetically by category, A-Z.
1639 category-down Sort alphabetically by category, Z-A.
1640 tag-up Sort alphabetically by last tag, A-Z.
1641 tag-down Sort alphabetically by last tag, Z-A.
1642 priority-up Sort numerically by priority, high priority last.
1643 priority-down Sort numerically by priority, high priority first.
1645 The different possibilities will be tried in sequence, and testing stops
1646 if one comparison returns a \"not-equal\". For example, the default
1647 '(time-up category-keep priority-down)
1648 means: Pull out all entries having a specified time of day and sort them,
1649 in order to make a time schedule for the current day the first thing in the
1650 agenda listing for the day. Of the entries without a time indication, keep
1651 the grouped in categories, don't sort the categories, but keep them in
1652 the sequence given in `org-agenda-files'. Within each category sort by
1653 priority.
1655 Leaving out `category-keep' would mean that items will be sorted across
1656 categories by priority."
1657 :group 'org-agenda-display
1658 :type `(choice
1659 (repeat :tag "General" ,sorting-choice)
1660 (list :tag "Individually"
1661 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1662 (repeat ,sorting-choice))
1663 (cons (const :tag "Strategy for TODO lists" todo)
1664 (repeat ,sorting-choice))
1665 (cons (const :tag "Strategy for Tags matches" tags)
1666 (repeat ,sorting-choice))))))
1668 (defcustom org-sort-agenda-notime-is-late t
1669 "Non-nil means, items without time are considered late.
1670 This is only relevant for sorting. When t, items which have no explicit
1671 time like 15:30 will be considered as 99:01, i.e. later than any items which
1672 do have a time. When nil, the default time is before 0:00. You can use this
1673 option to decide if the schedule for today should come before or after timeless
1674 agenda entries."
1675 :group 'org-agenda-display
1676 :type 'boolean)
1679 (defgroup org-agenda-prefix nil
1680 "Options concerning the entry prefix in the Org-mode agenda display."
1681 :tag "Org Agenda Prefix"
1682 :group 'org-agenda)
1684 (defcustom org-agenda-prefix-format
1685 '((agenda . " %-12:c%?-12t% s")
1686 (timeline . " % s")
1687 (todo . " %-12:c")
1688 (tags . " %-12:c"))
1689 "Format specifications for the prefix of items in the agenda views.
1690 An alist with four entries, for the different agenda types. The keys to the
1691 sublists are `agenda', `timeline', `todo', and `tags'. The values
1692 are format strings.
1693 This format works similar to a printf format, with the following meaning:
1695 %c the category of the item, \"Diary\" for entries from the diary, or
1696 as given by the CATEGORY keyword or derived from the file name.
1697 %T the *last* tag of the item. Last because inherited tags come
1698 first in the list.
1699 %t the time-of-day specification if one applies to the entry, in the
1700 format HH:MM
1701 %s Scheduling/Deadline information, a short string
1703 All specifiers work basically like the standard `%s' of printf, but may
1704 contain two additional characters: A question mark just after the `%' and
1705 a whitespace/punctuation character just before the final letter.
1707 If the first character after `%' is a question mark, the entire field
1708 will only be included if the corresponding value applies to the
1709 current entry. This is useful for fields which should have fixed
1710 width when present, but zero width when absent. For example,
1711 \"%?-12t\" will result in a 12 character time field if a time of the
1712 day is specified, but will completely disappear in entries which do
1713 not contain a time.
1715 If there is punctuation or whitespace character just before the final
1716 format letter, this character will be appended to the field value if
1717 the value is not empty. For example, the format \"%-12:c\" leads to
1718 \"Diary: \" if the category is \"Diary\". If the category were be
1719 empty, no additional colon would be interted.
1721 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1722 - Indent the line with two space characters
1723 - Give the category in a 12 chars wide field, padded with whitespace on
1724 the right (because of `-'). Append a colon if there is a category
1725 (because of `:').
1726 - If there is a time-of-day, put it into a 12 chars wide field. If no
1727 time, don't put in an empty field, just skip it (because of '?').
1728 - Finally, put the scheduling information and append a whitespace.
1730 As another example, if you don't want the time-of-day of entries in
1731 the prefix, you could use:
1733 (setq org-agenda-prefix-format \" %-11:c% s\")
1735 See also the variables `org-agenda-remove-times-when-in-prefix' and
1736 `org-agenda-remove-tags-when-in-prefix'."
1737 :type '(choice
1738 (string :tag "General format")
1739 (list :greedy t :tag "View dependent"
1740 (cons (const agenda) (string :tag "Format"))
1741 (cons (const timeline) (string :tag "Format"))
1742 (cons (const todo) (string :tag "Format"))
1743 (cons (const tags) (string :tag "Format"))))
1744 :group 'org-agenda-prefix)
1746 (defvar org-prefix-format-compiled nil
1747 "The compiled version of the most recently used prefix format.
1748 See the variable `org-agenda-prefix-format'.")
1750 (defcustom org-agenda-remove-times-when-in-prefix t
1751 "Non-nil means, remove duplicate time specifications in agenda items.
1752 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1753 time-of-day specification in a headline or diary entry is extracted and
1754 placed into the prefix. If this option is non-nil, the original specification
1755 \(a timestamp or -range, or just a plain time(range) specification like
1756 11:30-4pm) will be removed for agenda display. This makes the agenda less
1757 cluttered.
1758 The option can be t or nil. It may also be the symbol `beg', indicating
1759 that the time should only be removed what it is located at the beginning of
1760 the headline/diary entry."
1761 :group 'org-agenda-prefix
1762 :type '(choice
1763 (const :tag "Always" t)
1764 (const :tag "Never" nil)
1765 (const :tag "When at beginning of entry" beg)))
1767 (defcustom org-agenda-remove-tags-when-in-prefix nil
1768 "Non-nil means, remove the tags from the headline copy in the agenda.
1769 When this is the symbol `prefix', only remove tags when
1770 `org-agenda-prefix-format' contains a `%T' specifier."
1771 :group 'org-agenda-prefix
1772 :type '(choice
1773 (const :tag "Always" t)
1774 (const :tag "Never" nil)
1775 (const :tag "When prefix format contains %T" prefix)))
1777 (defcustom org-agenda-align-tags-to-column 65
1778 "Shift tags in agenda items to this column."
1779 :group 'org-agenda-prefix ;; FIXME
1780 :type 'integer)
1782 (defgroup org-latex nil
1783 "Options for embedding LaTeX code into Org-mode"
1784 :tag "Org LaTeX"
1785 :group 'org)
1787 (defcustom org-format-latex-options
1788 '(:foreground "Black" :background "Transparent" :scale 1.0
1789 :matchers ("begin" "$" "$$" "\\(" "\\["))
1790 "Options for creating images from LaTeX fragments.
1791 This is a property list with the following properties:
1792 :foreground the foreground color, for example \"Black\".
1793 :background the background color, or \"Transparent\".
1794 :scale a scaling factor for the size of the images
1795 :matchers a list indicating which matchers should be used to
1796 find LaTeX fragments. Valid members of this list are:
1797 \"begin\" find environments
1798 \"$\" find math expressions surrounded by $...$
1799 \"$$\" find math expressions surrounded by $$....$$
1800 \"\\(\" find math expressions surrounded by \\(...\\)
1801 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1802 :group 'org-latex
1803 :type 'plist)
1805 (defgroup org-export nil
1806 "Options for exporting org-listings."
1807 :tag "Org Export"
1808 :group 'org)
1810 (defgroup org-export-general nil
1811 "General options for exporting Org-mode files."
1812 :tag "Org Export General"
1813 :group 'org-export)
1815 (defcustom org-export-publishing-directory "."
1816 "Path to the location where exported files should be located.
1817 This path may be relative to the directory where the Org-mode file lives.
1818 The default is to put them into the same directory as the Org-mode file.
1819 The variable may also be an alist with export types `:html', `:ascii',
1820 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1821 is relative, it is interpreted relative to the directory where the exported
1822 Org-mode files lives."
1823 :group 'org-export-general
1824 :type '(choice
1825 (directory)
1826 (repeat
1827 (cons
1828 (choice :tag "Type"
1829 (const :html) (const :ascii) (const :ical) (const :xoxo))
1830 (directory)))))
1832 (defcustom org-export-language-setup
1833 '(("en" "Author" "Date" "Table of Contents")
1834 ("cs" "Autor" "Datum" "Obsah")
1835 ("da" "Ophavsmand" "Dato" "Indhold")
1836 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1837 ("es" "Autor" "Fecha" "\xccndice")
1838 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1839 ("it" "Autore" "Data" "Indice")
1840 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1841 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1842 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1843 "Terms used in export text, translated to different languages.
1844 Use the variable `org-export-default-language' to set the language,
1845 or use the +OPTION lines for a per-file setting."
1846 :group 'org-export-general
1847 :type '(repeat
1848 (list
1849 (string :tag "HTML language tag")
1850 (string :tag "Author")
1851 (string :tag "Date")
1852 (string :tag "Table of Contents"))))
1854 (defcustom org-export-default-language "en"
1855 "The default language of HTML export, as a string.
1856 This should have an association in `org-export-language-setup'."
1857 :group 'org-export-general
1858 :type 'string)
1860 (defcustom org-export-headline-levels 3
1861 "The last level which is still exported as a headline.
1862 Inferior levels will produce itemize lists when exported.
1863 Note that a numeric prefix argument to an exporter function overrides
1864 this setting.
1866 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1867 :group 'org-export-general
1868 :type 'number)
1870 (defcustom org-export-with-section-numbers t
1871 "Non-nil means, add section numbers to headlines when exporting.
1873 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1874 :group 'org-export-general
1875 :type 'boolean)
1877 (defcustom org-export-with-toc t
1878 "Non-nil means, create a table of contents in exported files.
1879 The TOC contains headlines with levels up to`org-export-headline-levels'.
1881 Headlines which contain any TODO items will be marked with \"(*)\" in
1882 ASCII export, and with red color in HTML output.
1884 In HTML output, the TOC will be clickable.
1886 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1887 :group 'org-export-general
1888 :type 'boolean)
1890 (defcustom org-export-mark-todo-in-toc nil
1891 "Non-nil means, mark TOC lines that contain any open TODO items."
1892 :group 'org-export-general
1893 :type 'boolean)
1895 (defcustom org-export-preserve-breaks nil
1896 "Non-nil means, preserve all line breaks when exporting.
1897 Normally, in HTML output paragraphs will be reformatted. In ASCII
1898 export, line breaks will always be preserved, regardless of this variable.
1900 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1901 :group 'org-export-general
1902 :type 'boolean)
1904 (defcustom org-export-with-archived-trees 'headline
1905 "Whether subtrees with the ARCHIVE tag should be exported.
1906 This can have three different values
1907 nil Do not export, pretend this tree is not present
1908 t Do export the entire tree
1909 headline Only export the headline, but skip the tree below it."
1910 :group 'org-export-general
1911 :group 'org-archive
1912 :type '(choice
1913 (const :tag "not at all" nil)
1914 (const :tag "headline only" 'headline)
1915 (const :tag "entirely" t)))
1917 (defcustom org-export-with-timestamps t
1918 "Nil means, do not export time stamps and associated keywords."
1919 :group 'org-export-general
1920 :type 'boolean)
1922 (defcustom org-export-remove-timestamps-from-toc t
1923 "Nil means, remove timestamps from the table of contents entries."
1924 :group 'org-export-general
1925 :type 'boolean)
1927 (defcustom org-export-with-tags 'not-in-toc
1928 "Nil means, do not export tags, just remove them from headlines.
1929 If this is the sysmbol `not-in-toc', tags will be removed from table of
1930 contents entries, but still be shown in the headlines of the document."
1931 :group 'org-export-general
1932 :type '(choice
1933 (const :tag "Off" nil)
1934 (const :tag "Not in TOC" not-in-toc)
1935 (const :tag "On" t)))
1937 (defgroup org-export-translation nil
1938 "Options for translating special ascii sequences for the export backends."
1939 :tag "Org Export Translation"
1940 :group 'org-export)
1942 (defcustom org-export-with-emphasize t
1943 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1944 If the export target supports emphasizing text, the word will be
1945 typeset in bold, italic, or underlined, respectively. Works only for
1946 single words, but you can say: I *really* *mean* *this*.
1947 Not all export backends support this.
1949 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1950 :group 'org-export-translation
1951 :type 'boolean)
1953 (defcustom org-export-with-sub-superscripts t
1954 "Non-nil means, interpret \"_\" and \"^\" for export.
1955 When this option is turned on, you can use TeX-like syntax for sub- and
1956 superscripts. Several characters after \"_\" or \"^\" will be
1957 considered as a single item - so grouping with {} is normally not
1958 needed. For example, the following things will be parsed as single
1959 sub- or superscripts.
1961 10^24 or 10^tau several digits will be considered 1 item.
1962 10^-12 or 10^-tau a leading sign with digits or a word
1963 x^2-y^3 will be read as x^2 - y^3, because items are
1964 terminated by almost any nonword/nondigit char.
1965 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1967 Still, ambiguity is possible - so when in doubt use {} to enclose the
1968 sub/superscript.
1969 Not all export backends support this, but HTML does.
1971 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1972 :group 'org-export-translation
1973 :type 'boolean)
1975 (defcustom org-export-with-TeX-macros t
1976 "Non-nil means, interpret simple TeX-like macros when exporting.
1977 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1978 No only real TeX macros will work here, but the standard HTML entities
1979 for math can be used as macro names as well. For a list of supported
1980 names in HTML export, see the constant `org-html-entities'.
1981 Not all export backends support this.
1983 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1984 :group 'org-export-translation
1985 :group 'org-latex
1986 :type 'boolean)
1988 (defcustom org-export-with-LaTeX-fragments nil
1989 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1990 When set, the exporter will find LaTeX environments if the \\begin line is
1991 the first non-white thing on a line. It will also find the math delimiters
1992 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1993 display math.
1995 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1996 :group 'org-export-translation
1997 :group 'org-latex
1998 :type 'boolean)
2000 (defcustom org-export-with-fixed-width t
2001 "Non-nil means, lines starting with \":\" will be in fixed width font.
2002 This can be used to have pre-formatted text, fragments of code etc. For
2003 example:
2004 : ;; Some Lisp examples
2005 : (while (defc cnt)
2006 : (ding))
2007 will be looking just like this in also HTML. See also the QUOTE keyword.
2008 Not all export backends support this.
2010 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2011 :group 'org-export-translation
2012 :type 'boolean)
2014 (defcustom org-match-sexp-depth 3
2015 "Number of stacked braces for sub/superscript matching.
2016 This has to be set before loading org.el to be effective."
2017 :group 'org-export-translation
2018 :type 'integer)
2020 (defgroup org-export-tables nil
2021 "Options for exporting tables in Org-mode."
2022 :tag "Org Export Tables"
2023 :group 'org-export)
2025 (defcustom org-export-with-tables t
2026 "If non-nil, lines starting with \"|\" define a table.
2027 For example:
2029 | Name | Address | Birthday |
2030 |-------------+----------+-----------|
2031 | Arthur Dent | England | 29.2.2100 |
2033 Not all export backends support this.
2035 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2036 :group 'org-export-tables
2037 :type 'boolean)
2039 (defcustom org-export-highlight-first-table-line t
2040 "Non-nil means, highlight the first table line.
2041 In HTML export, this means use <th> instead of <td>.
2042 In tables created with table.el, this applies to the first table line.
2043 In Org-mode tables, all lines before the first horizontal separator
2044 line will be formatted with <th> tags."
2045 :group 'org-export-tables
2046 :type 'boolean)
2048 (defcustom org-export-table-remove-special-lines t
2049 "Remove special lines and marking characters in calculating tables.
2050 This removes the special marking character column from tables that are set
2051 up for spreadsheet calculations. It also removes the entire lines
2052 marked with `!', `_', or `^'. The lines with `$' are kept, because
2053 the values of constants may be useful to have."
2054 :group 'org-export-tables
2055 :type 'boolean)
2057 (defcustom org-export-prefer-native-exporter-for-tables nil
2058 "Non-nil means, always export tables created with table.el natively.
2059 Natively means, use the HTML code generator in table.el.
2060 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2061 the table does not use row- or column-spanning). This has the
2062 advantage, that the automatic HTML conversions for math symbols and
2063 sub/superscripts can be applied. Org-mode's HTML generator is also
2064 much faster."
2065 :group 'org-export-tables
2066 :type 'boolean)
2068 (defgroup org-export-ascii nil
2069 "Options specific for ASCII export of Org-mode files."
2070 :tag "Org Export ASCII"
2071 :group 'org-export)
2073 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2074 "Characters for underlining headings in ASCII export.
2075 In the given sequence, these characters will be used for level 1, 2, ..."
2076 :group 'org-export-ascii
2077 :type '(repeat character))
2079 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2080 "Bullet characters for headlines converted to lists in ASCII export.
2081 The first character is is used for the first lest level generated in this
2082 way, and so on. If there are more levels than characters given here,
2083 the list will be repeated.
2084 Note that plain lists will keep the same bullets as the have in the
2085 Org-mode file."
2086 :group 'org-export-ascii
2087 :type '(repeat character))
2089 (defcustom org-export-ascii-show-new-buffer t
2090 "Non-nil means, popup buffer containing the exported ASCII text.
2091 Otherwise the buffer will just be saved to a file and stay hidden."
2092 :group 'org-export-ascii
2093 :type 'boolean)
2095 (defgroup org-export-xml nil
2096 "Options specific for XML export of Org-mode files."
2097 :tag "Org Export XML"
2098 :group 'org-export)
2100 (defgroup org-export-html nil
2101 "Options specific for HTML export of Org-mode files."
2102 :tag "Org Export HTML"
2103 :group 'org-export)
2105 (defcustom org-export-html-style
2106 "<style type=\"text/css\">
2107 html {
2108 font-family: Times, serif;
2109 font-size: 12pt;
2111 .title { text-align: center; }
2112 .todo { color: red; }
2113 .done { color: green; }
2114 .timestamp { color: grey }
2115 .timestamp-kwd { color: CadetBlue }
2116 .tag { background-color:lightblue; font-weight:normal }
2117 .target { background-color: lavender; }
2118 pre {
2119 border: 1pt solid #AEBDCC;
2120 background-color: #F3F5F7;
2121 padding: 5pt;
2122 font-family: courier, monospace;
2124 table { border-collapse: collapse; }
2125 td, th {
2126 vertical-align: top;
2127 border: 1pt solid #ADB9CC;
2129 </style>"
2130 "The default style specification for exported HTML files.
2131 Since there are different ways of setting style information, this variable
2132 needs to contain the full HTML structure to provide a style, including the
2133 surrounding HTML tags. The style specifications should include definitions
2134 for new classes todo, done, title, and deadline. For example, legal values
2135 would be:
2137 <style type=\"text/css\">
2138 p { font-weight: normal; color: gray; }
2139 h1 { color: black; }
2140 .title { text-align: center; }
2141 .todo, .deadline { color: red; }
2142 .done { color: green; }
2143 </style>
2145 or, if you want to keep the style in a file,
2147 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2149 As the value of this option simply gets inserted into the HTML <head> header,
2150 you can \"misuse\" it to add arbitrary text to the header."
2151 :group 'org-export-html
2152 :type 'string)
2154 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2155 "Format for typesetting the document title in HTML export."
2156 :group 'org-export-html
2157 :type 'string)
2159 (defcustom org-export-html-toplevel-hlevel 2
2160 "The <H> level for level 1 headings in HTML export."
2161 :group 'org-export-html
2162 :type 'string)
2164 (defcustom org-export-html-link-org-files-as-html t
2165 "Non-nil means, make file links to `file.org' point to `file.html'.
2166 When org-mode is exporting an org-mode file to HTML, links to
2167 non-html files are directly put into a href tag in HTML.
2168 However, links to other Org-mode files (recognized by the
2169 extension `.org.) should become links to the corresponding html
2170 file, assuming that the linked org-mode file will also be
2171 converted to HTML.
2172 When nil, the links still point to the plain `.org' file."
2173 :group 'org-export-html
2174 :type 'boolean)
2176 (defcustom org-export-html-inline-images 'maybe
2177 "Non-nil means, inline images into exported HTML pages.
2178 This is done using an <img> tag. When nil, an anchor with href is used to
2179 link to the image. If this option is `maybe', then images in links with
2180 an empty description will be inlined, while images with a description will
2181 be linked only."
2182 :group 'org-export-html
2183 :type '(choice (const :tag "Never" nil)
2184 (const :tag "Always" t)
2185 (const :tag "When there is no description" maybe)))
2187 (defcustom org-export-html-expand t
2188 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2189 When nil, these tags will be exported as plain text and therefore
2190 not be interpreted by a browser.
2192 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2193 :group 'org-export-html
2194 :type 'boolean)
2196 (defcustom org-export-html-table-tag
2197 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2198 "The HTML tag used to start a table.
2199 This must be a <table> tag, but you may change the options like
2200 borders and spacing."
2201 :group 'org-export-html
2202 :type 'string)
2204 (defcustom org-export-html-with-timestamp nil
2205 "If non-nil, write `org-export-html-html-helper-timestamp'
2206 into the exported HTML text. Otherwise, the buffer will just be saved
2207 to a file."
2208 :group 'org-export-html
2209 :type 'boolean)
2211 (defcustom org-export-html-html-helper-timestamp
2212 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2213 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2214 :group 'org-export-html
2215 :type 'string)
2217 (defcustom org-export-html-show-new-buffer nil
2218 "Non-nil means, popup buffer containing the exported html text.
2219 Otherwise, the buffer will just be saved to a file and stay hidden."
2220 :group 'org-export-html
2221 :type 'boolean)
2223 (defgroup org-export-icalendar nil
2224 "Options specific for iCalendar export of Org-mode files."
2225 :tag "Org Export iCalendar"
2226 :group 'org-export)
2228 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2229 "The file name for the iCalendar file covering all agenda files.
2230 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2231 The file name should be absolute."
2232 :group 'org-export-icalendar
2233 :type 'file)
2235 (defcustom org-icalendar-include-todo nil
2236 "Non-nil means, export to iCalendar files should also cover TODO items."
2237 :group 'org-export-icalendar
2238 :type 'boolean)
2240 (defcustom org-icalendar-combined-name "OrgMode"
2241 "Calendar name for the combined iCalendar representing all agenda files."
2242 :group 'org-export-icalendar
2243 :type 'string)
2245 (defgroup org-font-lock nil
2246 "Font-lock settings for highlighting in Org-mode."
2247 :tag "Org Font Lock"
2248 :group 'org)
2250 (defcustom org-level-color-stars-only nil
2251 "Non-nil means fontify only the stars in each headline.
2252 When nil, the entire headline is fontified.
2253 Changing it requires restart of `font-lock-mode' to become effective
2254 also in regions already fontified."
2255 :group 'org-font-lock
2256 :type 'boolean)
2258 (defcustom org-hide-leading-stars nil
2259 "Non-nil means, hide the first N-1 stars in a headline.
2260 This works by using the face `org-hide' for these stars. This
2261 face is white for a light background, and black for a dark
2262 background. You may have to customize the face `org-hide' to
2263 make this work.
2264 Changing it requires restart of `font-lock-mode' to become effective
2265 also in regions already fontified.
2266 You may also set this on a per-file basis by adding one of the following
2267 lines to the buffer:
2269 #+STARTUP: hidestars
2270 #+STARTUP: showstars"
2271 :group 'org-font-lock
2272 :type 'boolean)
2274 (defcustom org-fontify-done-headline nil
2275 "Non-nil means, change the face of a headline if it is marked DONE.
2276 Normally, only the TODO/DONE keyword indicates the state of a headline.
2277 When this is non-nil, the headline after the keyword is set to the
2278 `org-headline-done' as an additional indication."
2279 :group 'org-font-lock
2280 :type 'boolean)
2282 (defcustom org-fontify-emphasized-text t
2283 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2284 Changing this variable requires a restart of Emacs to take effect."
2285 :group 'org-font-lock
2286 :type 'boolean)
2288 (defvar org-emph-re nil
2289 "Regular expression for matching emphasis.")
2290 (defvar org-emphasis-regexp-components) ; defined just below
2291 (defvar org-emphasis-alist) ; defined just below
2292 (defun org-set-emph-re (var val)
2293 "Set variable and compute the emphasis regular expression."
2294 (set var val)
2295 (when (and (boundp 'org-emphasis-alist)
2296 (boundp 'org-emphasis-regexp-components)
2297 org-emphasis-alist org-emphasis-regexp-components)
2298 (let* ((e org-emphasis-regexp-components)
2299 (pre (car e))
2300 (post (nth 1 e))
2301 (border (nth 2 e))
2302 (body (nth 3 e))
2303 (nl (nth 4 e))
2304 (stacked (nth 5 e))
2305 (body1 (concat body "*?"))
2306 (markers (mapconcat 'car org-emphasis-alist "")))
2307 ;; make sure special characters appear at the right position in the class
2308 (if (string-match "\\^" markers)
2309 (setq markers (concat (replace-match "" t t markers) "^")))
2310 (if (string-match "-" markers)
2311 (setq markers (concat (replace-match "" t t markers) "-")))
2312 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2313 ;; Make the regexp
2314 (setq org-emph-re
2315 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2316 "\\("
2317 "\\([" markers "]\\)"
2318 "\\("
2319 (if stacked (concat "[^" border markers "]")) ; FIXME: correct?
2320 body1
2321 (if stacked (concat "[^" border markers "]")) ; FIXME: correct?
2322 "\\)"
2323 "\\3\\)"
2324 "\\([" post (if stacked markers) "]\\|$\\)")))))
2326 (defcustom org-emphasis-regexp-components
2327 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2328 "Components used to build the reqular expression for emphasis.
2329 This is a list with 6 entries. Terminology: In an emphasis string
2330 like \" *strong word* \", we call the initial space PREMATCH, the final
2331 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2332 and \"trong wor\" is the body. The different components in this variable
2333 specify what is allowed/forbidden in each part:
2335 pre Chars allowed as prematch. Beginning of line will be allowed too.
2336 post Chars allowed as postmatch. End of line will be allowed too.
2337 border The chars *forbidden* as border characters. In addition to the
2338 characters given here, all marker characters are forbidden too.
2339 body-regexp A regexp like \".\" to match a body character. Don't use
2340 non-shy groups here, and don't allow newline here.
2341 newline The maximum number of newlines allowed in an emphasis exp.
2342 stacked Non-nil means, allow stacked styles. This works only in HTML
2343 export. When this is set, all marker characters (as given in
2344 `org-emphasis-alist') will be allowed as pre/post, aiding
2345 inside-out matching.
2346 Use customize to modify this, or restart emacs after changing it."
2347 :group 'org-font-lock
2348 :set 'org-set-emph-re
2349 :type '(list
2350 (sexp :tag "Allowed chars in pre ")
2351 (sexp :tag "Allowed chars in post ")
2352 (sexp :tag "Forbidden chars in border ")
2353 (sexp :tag "Regexp for body ")
2354 (integer :tag "number of newlines allowed")
2355 (boolean :tag "Stacking allowed ")))
2357 (defcustom org-emphasis-alist
2358 '(("*" bold "<b>" "</b>")
2359 ("/" italic "<i>" "</i>")
2360 ("_" underline "<u>" "</u>")
2361 ("=" shadow "<code>" "</code>")
2362 ("+" (:strike-through t) "<del>" "</del>")
2364 "Special syntax for emphasised text.
2365 Text starting and ending with a special character will be emphasized, for
2366 example *bold*, _underlined_ and /italic/. This variable sets the marker
2367 characters, the face to bbe used by font-lock for highlighting in Org-mode
2368 emacs buffers, and the HTML tags to be used for this.
2369 Use customize to modify this, or restart emacs after changing it."
2370 :group 'org-font-lock
2371 :set 'org-set-emph-re
2372 :type '(repeat
2373 (list
2374 (string :tag "Marker character")
2375 (choice
2376 (face :tag "Font-lock-face")
2377 (plist :tag "Face property list"))
2378 (string :tag "HTML start tag")
2379 (string :tag "HTML end tag"))))
2381 (defgroup org-faces nil
2382 "Faces in Org-mode."
2383 :tag "Org Faces"
2384 :group 'org-font-lock)
2386 (defun org-compatible-face (specs)
2387 "Make a compatible face specification.
2388 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2389 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2390 to the top of the list. The `min-colors' attribute will be removed from
2391 any other entries, and any resulting duplicates will be removed entirely."
2392 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2393 (let (r e a)
2394 (while (setq e (pop specs))
2395 (cond
2396 ((memq (car e) '(t default)) (push e r))
2397 ((setq a (member '(min-colors 8) (car e)))
2398 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2399 (cdr e)))))
2400 ((setq a (assq 'min-colors (car e)))
2401 (setq e (cons (delq a (car e)) (cdr e)))
2402 (or (assoc (car e) r) (push e r)))
2403 (t (or (assoc (car e) r) (push e r)))))
2404 (nreverse r))
2405 specs))
2407 (defface org-hide
2408 '((((background light)) (:foreground "white"))
2409 (((background dark)) (:foreground "black")))
2410 "Face used to hide leading stars in headlines.
2411 The forground color of this face should be equal to the background
2412 color of the frame."
2413 :group 'org-faces)
2415 (defface org-level-1 ;; font-lock-function-name-face
2416 (org-compatible-face
2417 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2418 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2419 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2420 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2421 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2422 (t (:bold t))))
2423 "Face used for level 1 headlines."
2424 :group 'org-faces)
2426 (defface org-level-2 ;; font-lock-variable-name-face
2427 (org-compatible-face
2428 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2429 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2430 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2431 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2432 (t (:bold t))))
2433 "Face used for level 2 headlines."
2434 :group 'org-faces)
2436 (defface org-level-3 ;; font-lock-keyword-face
2437 (org-compatible-face
2438 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2439 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2440 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2441 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2442 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2443 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2444 (t (:bold t))))
2445 "Face used for level 3 headlines."
2446 :group 'org-faces)
2448 (defface org-level-4 ;; font-lock-comment-face
2449 (org-compatible-face
2450 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2451 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2452 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2453 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2454 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2455 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2456 (t (:bold t))))
2457 "Face used for level 4 headlines."
2458 :group 'org-faces)
2460 (defface org-level-5 ;; font-lock-type-face
2461 (org-compatible-face
2462 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2463 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2464 (((class color) (min-colors 8)) (:foreground "green"))))
2465 "Face used for level 5 headlines."
2466 :group 'org-faces)
2468 (defface org-level-6 ;; font-lock-constant-face
2469 (org-compatible-face
2470 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2471 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2472 (((class color) (min-colors 8)) (:foreground "magenta"))))
2473 "Face used for level 6 headlines."
2474 :group 'org-faces)
2476 (defface org-level-7 ;; font-lock-builtin-face
2477 (org-compatible-face
2478 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2479 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2480 (((class color) (min-colors 8)) (:foreground "blue"))))
2481 "Face used for level 7 headlines."
2482 :group 'org-faces)
2484 (defface org-level-8 ;; font-lock-string-face
2485 (org-compatible-face
2486 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2487 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2488 (((class color) (min-colors 8)) (:foreground "green"))))
2489 "Face used for level 8 headlines."
2490 :group 'org-faces)
2492 (defface org-special-keyword ;; font-lock-string-face
2493 (org-compatible-face
2494 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2495 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2496 (t (:italic t))))
2497 "Face used for special keywords."
2498 :group 'org-faces)
2500 (defface org-warning ;; font-lock-warning-face
2501 (org-compatible-face
2502 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2503 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2504 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2505 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2506 (t (:bold t))))
2507 "Face for deadlines and TODO keywords."
2508 :group 'org-faces)
2510 (defface org-headline-done ;; font-lock-string-face
2511 (org-compatible-face
2512 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2513 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2514 (((class color) (min-colors 8) (background light)) (:bold nil))))
2515 "Face used to indicate that a headline is DONE.
2516 This face is only used if `org-fontify-done-headline' is set."
2517 :group 'org-faces)
2519 (defface org-archived ; similar to shadow
2520 (org-compatible-face
2521 '((((class color grayscale) (min-colors 88) (background light))
2522 (:foreground "grey50"))
2523 (((class color grayscale) (min-colors 88) (background dark))
2524 (:foreground "grey70"))
2525 (((class color) (min-colors 8) (background light))
2526 (:foreground "green"))
2527 (((class color) (min-colors 8) (background dark))
2528 (:foreground "yellow"))))
2529 "Face for headline with the ARCHIVE tag."
2530 :group 'org-faces)
2532 (defface org-link
2533 '((((class color) (background light)) (:foreground "Purple" :underline t))
2534 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2535 (t (:underline t)))
2536 "Face for links."
2537 :group 'org-faces)
2539 (defface org-date
2540 '((((class color) (background light)) (:foreground "Purple" :underline t))
2541 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2542 (t (:underline t)))
2543 "Face for links."
2544 :group 'org-faces)
2546 (defface org-tag
2547 '((t (:bold t)))
2548 "Face for tags."
2549 :group 'org-faces)
2551 (defface org-todo ;; font-lock-warning-face
2552 (org-compatible-face
2553 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2554 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2555 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2556 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2557 (t (:inverse-video t :bold t))))
2558 "Face for TODO keywords."
2559 :group 'org-faces)
2561 (defface org-done ;; font-lock-type-face
2562 (org-compatible-face
2563 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2564 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2565 (((class color) (min-colors 8)) (:foreground "green"))
2566 (t (:bold t))))
2567 "Face used for DONE."
2568 :group 'org-faces)
2570 (defface org-table ;; font-lock-function-name-face
2571 (org-compatible-face
2572 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2573 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2574 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2575 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2576 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2577 (((class color) (min-colors 8) (background dark)))))
2578 "Face used for tables."
2579 :group 'org-faces)
2581 (defface org-formula
2582 (org-compatible-face
2583 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2584 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2585 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2586 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2587 (t (:bold t :italic t))))
2588 "Face for formulas."
2589 :group 'org-faces)
2591 (defface org-scheduled-today
2592 (org-compatible-face
2593 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2594 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2595 (((class color) (min-colors 8)) (:foreground "green"))
2596 (t (:bold t :italic t))))
2597 "Face for items scheduled for a certain day."
2598 :group 'org-faces)
2600 (defface org-scheduled-previously
2601 (org-compatible-face
2602 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2603 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2604 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2605 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2606 (t (:bold t))))
2607 "Face for items scheduled previously, and not yet done."
2608 :group 'org-faces)
2610 (defface org-upcoming-deadline
2611 (org-compatible-face
2612 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2613 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2614 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2615 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2616 (t (:bold t))))
2617 "Face for items scheduled previously, and not yet done."
2618 :group 'org-faces)
2620 (defface org-time-grid ;; font-lock-variable-name-face
2621 (org-compatible-face
2622 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2623 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2624 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2625 "Face used for time grids."
2626 :group 'org-faces)
2628 (defconst org-level-faces
2629 '(org-level-1 org-level-2 org-level-3 org-level-4
2630 org-level-5 org-level-6 org-level-7 org-level-8
2632 (defconst org-n-levels (length org-level-faces))
2635 ;; Variables for pre-computed regular expressions, all buffer local
2636 (defvar org-done-string nil
2637 "The last string in `org-todo-keywords', indicating an item is DONE.")
2638 (make-variable-buffer-local 'org-done-string)
2639 (defvar org-todo-regexp nil
2640 "Matches any of the TODO state keywords.")
2641 (make-variable-buffer-local 'org-todo-regexp)
2642 (defvar org-not-done-regexp nil
2643 "Matches any of the TODO state keywords except the last one.")
2644 (make-variable-buffer-local 'org-not-done-regexp)
2645 (defvar org-todo-line-regexp nil
2646 "Matches a headline and puts TODO state into group 2 if present.")
2647 (make-variable-buffer-local 'org-todo-line-regexp)
2648 (defvar org-todo-line-tags-regexp nil
2649 "Matches a headline and puts TODO state into group 2 if present.
2650 Also put tags into group 4 if tags are present.")
2651 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2652 (defvar org-nl-done-regexp nil
2653 "Matches newline followed by a headline with the DONE keyword.")
2654 (make-variable-buffer-local 'org-nl-done-regexp)
2655 (defvar org-looking-at-done-regexp nil
2656 "Matches the DONE keyword a point.")
2657 (make-variable-buffer-local 'org-looking-at-done-regexp)
2658 (defvar org-todo-kwd-priority-p nil
2659 "Do TODO items have priorities?")
2660 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2661 (defvar org-todo-kwd-max-priority nil
2662 "Maximum priority of TODO items.")
2663 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2664 (defvar org-ds-keyword-length 12
2665 "Maximum length of the Deadline and SCHEDULED keywords.")
2666 (make-variable-buffer-local 'org-ds-keyword-length)
2667 (defvar org-deadline-regexp nil
2668 "Matches the DEADLINE keyword.")
2669 (make-variable-buffer-local 'org-deadline-regexp)
2670 (defvar org-deadline-time-regexp nil
2671 "Matches the DEADLINE keyword together with a time stamp.")
2672 (make-variable-buffer-local 'org-deadline-time-regexp)
2673 (defvar org-deadline-line-regexp nil
2674 "Matches the DEADLINE keyword and the rest of the line.")
2675 (make-variable-buffer-local 'org-deadline-line-regexp)
2676 (defvar org-scheduled-regexp nil
2677 "Matches the SCHEDULED keyword.")
2678 (make-variable-buffer-local 'org-scheduled-regexp)
2679 (defvar org-scheduled-time-regexp nil
2680 "Matches the SCHEDULED keyword together with a time stamp.")
2681 (make-variable-buffer-local 'org-scheduled-time-regexp)
2682 (defvar org-closed-time-regexp nil
2683 "Matches the CLOSED keyword together with a time stamp.")
2684 (make-variable-buffer-local 'org-closed-time-regexp)
2686 (defvar org-keyword-time-regexp nil
2687 "Matches any of the 3 keywords, together with the time stamp.")
2688 (make-variable-buffer-local 'org-keyword-time-regexp)
2689 (defvar org-maybe-keyword-time-regexp nil
2690 "Matches a timestamp, possibly preceeded by a keyword.")
2691 (make-variable-buffer-local 'org-keyword-time-regexp)
2693 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2694 mouse-map t)
2695 "Properties to remove when a string without properties is wanted.")
2697 (defsubst org-match-string-no-properties (num &optional string)
2698 (if (featurep 'xemacs)
2699 (let ((s (match-string num string)))
2700 (remove-text-properties 0 (length s) org-rm-props s)
2702 (match-string-no-properties num string)))
2704 (defsubst org-no-properties (s)
2705 (remove-text-properties 0 (length s) org-rm-props s)
2708 (defsubst org-set-local (var value)
2709 "Make VAR local in current buffer and set it to VALUE."
2710 (set (make-variable-buffer-local var) value))
2712 (defsubst org-mode-p ()
2713 "Check if the current buffer is in Org-mode."
2714 (eq major-mode 'org-mode))
2716 (defsubst org-last (list)
2717 "Return the last element of LIST."
2718 (car (last list)))
2720 (defun org-let (list &rest body)
2721 (eval (cons 'let (cons list body))))
2722 (put 'org-let 'lisp-indent-function 1)
2724 (defun org-let2 (list1 list2 &rest body)
2725 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
2726 (put 'org-let2 'lisp-indent-function 2)
2728 (defconst org-startup-options
2729 '(("fold" org-startup-folded t)
2730 ("overview" org-startup-folded t)
2731 ("nofold" org-startup-folded nil)
2732 ("showall" org-startup-folded nil)
2733 ("content" org-startup-folded content)
2734 ("hidestars" org-hide-leading-stars t)
2735 ("showstars" org-hide-leading-stars nil)
2736 ("odd" org-odd-levels-only t)
2737 ("oddeven" org-odd-levels-only nil)
2738 ("align" org-startup-align-all-tables t)
2739 ("noalign" org-startup-align-all-tables nil)
2740 ("logging" org-log-done t)
2741 ("nologging" org-log-done nil)
2742 ("dlcheck" org-startup-with-deadline-check t)
2743 ("nodlcheck" org-startup-with-deadline-check nil)))
2745 (defun org-set-regexps-and-options ()
2746 "Precompute regular expressions for current buffer."
2747 (when (org-mode-p)
2748 (let ((re (org-make-options-regexp
2749 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2750 "STARTUP" "ARCHIVE" "TAGS" "CALC")))
2751 (splitre "[ \t]+")
2752 kwds int key value cat arch tags)
2753 (save-excursion
2754 (save-restriction
2755 (widen)
2756 (goto-char (point-min))
2757 (while (re-search-forward re nil t)
2758 (setq key (match-string 1) value (org-match-string-no-properties 2))
2759 (cond
2760 ((equal key "CATEGORY")
2761 (if (string-match "[ \t]+$" value)
2762 (setq value (replace-match "" t t value)))
2763 (setq cat (intern value)))
2764 ((equal key "SEQ_TODO")
2765 (setq int 'sequence
2766 kwds (append kwds (org-split-string value splitre))))
2767 ((equal key "PRI_TODO")
2768 (setq int 'priority
2769 kwds (append kwds (org-split-string value splitre))))
2770 ((equal key "TYP_TODO")
2771 (setq int 'type
2772 kwds (append kwds (org-split-string value splitre))))
2773 ((equal key "TAGS")
2774 (setq tags (append tags (org-split-string value splitre))))
2775 ((equal key "STARTUP")
2776 (let ((opts (org-split-string value splitre))
2777 l var val)
2778 (while (setq l (assoc (pop opts) org-startup-options))
2779 (setq var (nth 1 l) val (nth 2 l))
2780 (set (make-local-variable var) val))))
2781 ((equal key "ARCHIVE")
2782 (string-match " *$" value)
2783 (setq arch (replace-match "" t t value))
2784 (remove-text-properties 0 (length arch)
2785 '(face t fontified t) arch)))
2787 (and cat (org-set-local 'org-category cat))
2788 (and kwds (org-set-local 'org-todo-keywords kwds))
2789 (and arch (org-set-local 'org-archive-location arch))
2790 (and int (org-set-local 'org-todo-interpretation int))
2791 (when tags
2792 (let (e tgs)
2793 (while (setq e (pop tags))
2794 (cond
2795 ((equal e "{") (push '(:startgroup) tgs))
2796 ((equal e "}") (push '(:endgroup) tgs))
2797 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2798 (push (cons (match-string 1 e)
2799 (string-to-char (match-string 2 e)))
2800 tgs))
2801 (t (push (list e) tgs))))
2802 (org-set-local 'org-tag-alist nil)
2803 (while (setq e (pop tgs))
2804 (or (and (stringp (car e))
2805 (assoc (car e) org-tag-alist))
2806 (push e org-tag-alist))))))
2808 ;; Compute the regular expressions and other local variables
2809 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2810 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2811 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2812 (length org-scheduled-string)))
2813 org-done-string
2814 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2815 org-todo-regexp
2816 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2817 "\\|") "\\)\\>")
2818 org-not-done-regexp
2819 (concat "\\<\\("
2820 (mapconcat 'regexp-quote
2821 (nreverse (cdr (reverse org-todo-keywords)))
2822 "\\|")
2823 "\\)\\>")
2824 org-todo-line-regexp
2825 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
2826 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2827 "\\)\\>\\)? *\\(.*\\)")
2828 org-nl-done-regexp
2829 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2830 org-todo-line-tags-regexp
2831 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
2832 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2833 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2834 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2835 org-deadline-regexp (concat "\\<" org-deadline-string)
2836 org-deadline-time-regexp
2837 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2838 org-deadline-line-regexp
2839 (concat "\\<\\(" org-deadline-string "\\).*")
2840 org-scheduled-regexp
2841 (concat "\\<" org-scheduled-string)
2842 org-scheduled-time-regexp
2843 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2844 org-closed-time-regexp
2845 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2846 org-keyword-time-regexp
2847 (concat "\\<\\(" org-scheduled-string
2848 "\\|" org-deadline-string
2849 "\\|" org-closed-string
2850 "\\|" org-clock-string "\\)"
2851 " *[[<]\\([^]>]+\\)[]>]")
2852 org-maybe-keyword-time-regexp
2853 (concat "\\(\\<\\(" org-scheduled-string
2854 "\\|" org-deadline-string
2855 "\\|" org-closed-string
2856 "\\|" org-clock-string "\\)\\)?"
2857 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2859 (org-set-font-lock-defaults)))
2861 ;; Tell the compiler about dynamically scoped variables,
2862 ;; and variables from other packages
2863 (defvar calc-embedded-close-formula) ; defined by the calc package
2864 (defvar calc-embedded-open-formula) ; defined by the calc package
2865 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2866 (defvar zmacs-regions) ; XEmacs regions
2867 (defvar original-date) ; dynamically scoped in calendar
2868 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2869 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2870 (defvar org-html-entities) ; defined later in this file
2871 (defvar org-goto-start-pos) ; dynamically scoped parameter
2872 (defvar org-time-was-given) ; dynamically scoped parameter
2873 (defvar org-ts-what) ; dynamically scoped parameter
2874 (defvar org-current-export-file) ; dynamically scoped parameter
2875 (defvar org-current-export-dir) ; dynamically scoped parameter
2876 (defvar mark-active) ; Emacs only, not available in XEmacs.
2877 (defvar timecnt) ; dynamically scoped parameter
2878 (defvar levels-open) ; dynamically scoped parameter
2879 (defvar entry) ; dynamically scoped parameter
2880 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2881 (defvar date) ; dynamically scoped parameter
2882 (defvar description) ; dynamically scoped parameter
2883 (defvar ans1) ; dynamically scoped parameter
2884 (defvar ans2) ; dynamically scoped parameter
2885 (defvar starting-day) ; local variable
2886 (defvar include-all-loc) ; local variable
2887 (defvar vm-message-pointer) ; from vm
2888 (defvar vm-folder-directory) ; from vm
2889 (defvar gnus-other-frame-object) ; from gnus
2890 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2891 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2892 (defvar gnus-group-name) ; from gnus
2893 (defvar gnus-article-current) ; from gnus
2894 (defvar w3m-current-url) ; from w3m
2895 (defvar w3m-current-title) ; from w3m
2896 (defvar mh-progs) ; from MH-E
2897 (defvar mh-current-folder) ; from MH-E
2898 (defvar mh-show-folder-buffer) ; from MH-E
2899 (defvar mh-index-folder) ; from MH-E
2900 (defvar mh-searcher) ; from MH-E
2901 (defvar org-selected-point) ; dynamically scoped parameter
2902 (defvar calendar-mode-map) ; from calendar.el
2903 (defvar last-arg) ; local variable
2904 (defvar remember-save-after-remembering) ; from remember.el
2905 (defvar remember-data-file) ; from remember.el
2906 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2907 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2908 (defvar orgtbl-mode) ; defined later in this file
2909 (defvar Info-current-file) ; from info.el
2910 (defvar Info-current-node) ; from info.el
2911 (defvar texmathp-why) ; from texmathp.el
2912 (defvar org-latex-regexps)
2914 ;;; Define the mode
2916 (defvar org-mode-map
2917 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2918 (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.")
2919 (copy-keymap outline-mode-map))
2920 "Keymap for Org-mode.")
2922 (defvar org-struct-menu) ; defined later in this file
2923 (defvar org-org-menu) ; defined later in this file
2924 (defvar org-tbl-menu) ; defined later in this file
2926 ;; We use a before-change function to check if a table might need
2927 ;; an update.
2928 (defvar org-table-may-need-update t
2929 "Indicates that a table might need an update.
2930 This variable is set by `org-before-change-function'.
2931 `org-table-align' sets it back to nil.")
2932 (defvar org-mode-hook nil)
2933 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2934 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2937 ;;;###autoload
2938 (define-derived-mode org-mode outline-mode "Org"
2939 "Outline-based notes management and organizer, alias
2940 \"Carsten's outline-mode for keeping track of everything.\"
2942 Org-mode develops organizational tasks around a NOTES file which
2943 contains information about projects as plain text. Org-mode is
2944 implemented on top of outline-mode, which is ideal to keep the content
2945 of large files well structured. It supports ToDo items, deadlines and
2946 time stamps, which magically appear in the diary listing of the Emacs
2947 calendar. Tables are easily created with a built-in table editor.
2948 Plain text URL-like links connect to websites, emails (VM), Usenet
2949 messages (Gnus), BBDB entries, and any files related to the project.
2950 For printing and sharing of notes, an Org-mode file (or a part of it)
2951 can be exported as a structured ASCII or HTML file.
2953 The following commands are available:
2955 \\{org-mode-map}"
2957 ;; Get rid of Outline menus, they are not needed
2958 ;; Need to do this here because define-derived-mode sets up
2959 ;; the keymap so late.
2960 (if (featurep 'xemacs)
2961 (progn
2962 ;; Assume this is Greg's port, it used easymenu
2963 (easy-menu-remove outline-mode-menu-heading)
2964 (easy-menu-remove outline-mode-menu-show)
2965 (easy-menu-remove outline-mode-menu-hide))
2966 (define-key org-mode-map [menu-bar headings] 'undefined)
2967 (define-key org-mode-map [menu-bar hide] 'undefined)
2968 (define-key org-mode-map [menu-bar show] 'undefined))
2970 (easy-menu-add org-org-menu)
2971 (easy-menu-add org-tbl-menu)
2972 (org-install-agenda-files-menu)
2973 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2974 (org-add-to-invisibility-spec '(org-cwidth))
2975 (when (featurep 'xemacs)
2976 (org-set-local 'line-move-ignore-invisible t))
2977 (setq outline-regexp "\\*+")
2978 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2979 (setq outline-level 'org-outline-level)
2980 (when (and org-ellipsis (stringp org-ellipsis))
2981 (unless org-display-table
2982 (setq org-display-table (make-display-table)))
2983 (set-display-table-slot org-display-table
2984 4 (string-to-vector org-ellipsis))
2985 (setq buffer-display-table org-display-table))
2986 (org-set-regexps-and-options)
2987 ;; Calc embedded
2988 (org-set-local 'calc-embedded-open-mode "# ")
2989 (modify-syntax-entry ?# "<")
2990 (if org-startup-truncated (setq truncate-lines t))
2991 (org-set-local 'font-lock-unfontify-region-function
2992 'org-unfontify-region)
2993 ;; Activate before-change-function
2994 (org-set-local 'org-table-may-need-update t)
2995 (org-add-hook 'before-change-functions 'org-before-change-function nil
2996 'local)
2997 ;; Check for running clock before killing a buffer
2998 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2999 ;; Paragraphs and auto-filling
3000 (org-set-autofill-regexps)
3001 (org-update-radio-target-regexp)
3003 (if (and org-insert-mode-line-in-empty-file
3004 (interactive-p)
3005 (= (point-min) (point-max)))
3006 (insert " -*- mode: org -*-\n\n"))
3008 (unless org-inhibit-startup
3009 (when org-startup-align-all-tables
3010 (let ((bmp (buffer-modified-p)))
3011 (org-table-map-tables 'org-table-align)
3012 (set-buffer-modified-p bmp)))
3013 (if org-startup-with-deadline-check
3014 (call-interactively 'org-check-deadlines)
3015 (cond
3016 ((eq org-startup-folded t)
3017 (org-cycle '(4)))
3018 ((eq org-startup-folded 'content)
3019 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3020 (org-cycle '(4)) (org-cycle '(4))))))))
3022 (defsubst org-call-with-arg (command arg)
3023 "Call COMMAND interactively, but pretend prefix are was ARG."
3024 (let ((current-prefix-arg arg)) (call-interactively command)))
3026 (defsubst org-current-line (&optional pos)
3027 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
3029 (defun org-current-time ()
3030 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3031 (if (> org-time-stamp-rounding-minutes 0)
3032 (let ((r org-time-stamp-rounding-minutes)
3033 (time (decode-time)))
3034 (apply 'encode-time
3035 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3036 (nthcdr 2 time))))
3037 (current-time)))
3039 (defun org-add-props (string plist &rest props)
3040 "Add text properties to entire string, from beginning to end.
3041 PLIST may be a list of properties, PROPS are individual properties and values
3042 that will be added to PLIST. Returns the string that was modified."
3043 (add-text-properties
3044 0 (length string) (if props (append plist props) plist) string)
3045 string)
3046 (put 'org-add-props 'lisp-indent-function 2)
3049 ;;; Font-Lock stuff
3051 (defvar org-mouse-map (make-sparse-keymap))
3052 (define-key org-mouse-map
3053 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3054 (define-key org-mouse-map
3055 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3056 (when org-mouse-1-follows-link
3057 (define-key org-mouse-map [follow-link] 'mouse-face))
3058 (when org-tab-follows-link
3059 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3060 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3061 (when org-return-follows-link
3062 (define-key org-mouse-map [(return)] 'org-open-at-point)
3063 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3065 (require 'font-lock)
3067 (defconst org-non-link-chars "]\t\n\r<>")
3068 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3069 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3070 (defconst org-link-re-with-space
3071 (concat
3072 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3073 "\\([^" org-non-link-chars " ]"
3074 "[^" org-non-link-chars "]*"
3075 "[^" org-non-link-chars " ]\\)>?")
3076 "Matches a link with spaces, optional angular brackets around it.")
3078 (defconst org-link-re-with-space2
3079 (concat
3080 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3081 "\\([^" org-non-link-chars " ]"
3082 "[^]\t\n\r]*"
3083 "[^" org-non-link-chars " ]\\)>?")
3084 "Matches a link with spaces, optional angular brackets around it.")
3086 (defconst org-angle-link-re
3087 (concat
3088 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3089 "\\([^" org-non-link-chars " ]"
3090 "[^" org-non-link-chars "]*"
3091 "\\)>")
3092 "Matches link with angular brackets, spaces are allowed.")
3093 (defconst org-plain-link-re
3094 (concat
3095 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3096 "\\([^]\t\n\r<>,;() ]+\\)")
3097 "Matches plain link, without spaces.")
3099 (defconst org-bracket-link-regexp
3100 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3101 "Matches a link in double brackets.")
3103 (defconst org-bracket-link-analytic-regexp
3104 (concat
3105 "\\[\\["
3106 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3107 "\\([^]]+\\)"
3108 "\\]"
3109 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3110 "\\]"))
3111 ; 1: http:
3112 ; 2: http
3113 ; 3: path
3114 ; 4: [desc]
3115 ; 5: desc
3118 (defconst org-ts-lengths
3119 (cons (length (format-time-string (car org-time-stamp-formats)))
3120 (length (format-time-string (cdr org-time-stamp-formats))))
3121 "This holds the lengths of the two different time formats.")
3122 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3123 "Regular expression for fast time stamp matching.")
3124 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3125 "Regular expression for fast time stamp matching.")
3126 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3127 "Regular expression matching time strings for analysis.")
3128 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3129 "Regular expression matching time stamps, with groups.")
3130 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3131 "Regular expression matching time stamps (also [..]), with groups.")
3132 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3133 "Regular expression matching a time stamp range.")
3134 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3135 org-ts-regexp "\\)?")
3136 "Regular expression matching a time stamp or time stamp range.")
3138 (defvar org-�§emph-face nil)
3140 (defun org-do-emphasis-faces (limit)
3141 "Run through the buffer and add overlays to links."
3142 (if (re-search-forward org-emph-re limit t)
3143 (progn
3144 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3145 'face
3146 (nth 1 (assoc (match-string 3)
3147 org-emphasis-alist)))
3148 (add-text-properties (match-beginning 2) (match-end 2)
3149 '(font-lock-multiline t))
3150 (backward-char 1)
3151 t)))
3153 (defun org-activate-plain-links (limit)
3154 "Run through the buffer and add overlays to links."
3155 (if (re-search-forward org-plain-link-re limit t)
3156 (progn
3157 (add-text-properties (match-beginning 0) (match-end 0)
3158 (list 'mouse-face 'highlight
3159 'keymap org-mouse-map
3161 t)))
3163 (defun org-activate-angle-links (limit)
3164 "Run through the buffer and add overlays to links."
3165 (if (re-search-forward org-angle-link-re limit t)
3166 (progn
3167 (add-text-properties (match-beginning 0) (match-end 0)
3168 (list 'mouse-face 'highlight
3169 'keymap org-mouse-map
3171 t)))
3173 (defun org-activate-bracket-links (limit)
3174 "Run through the buffer and add overlays to bracketed links."
3175 (if (re-search-forward org-bracket-link-regexp limit t)
3176 (let* ((help (concat "LINK: "
3177 (org-match-string-no-properties 1)))
3178 ;; FIXME: above we should remove the escapes.
3179 ;; but that requires another match, protecting match data,
3180 ;; a lot of overhead for font-lock.
3181 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3182 'keymap org-mouse-map 'mouse-face 'highlight
3183 'help-echo help))
3184 (vp (list 'rear-nonsticky t
3185 'keymap org-mouse-map 'mouse-face 'highlight
3186 'help-echo help)))
3187 ;; We need to remove the invisible property here. Table narrowing
3188 ;; may have made some of this invisible.
3189 (remove-text-properties (match-beginning 0) (match-end 0)
3190 '(invisible nil))
3191 (if (match-end 3)
3192 (progn
3193 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3194 (add-text-properties (match-beginning 3) (match-end 3) vp)
3195 (add-text-properties (match-end 3) (match-end 0) ip))
3196 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3197 (add-text-properties (match-beginning 1) (match-end 1) vp)
3198 (add-text-properties (match-end 1) (match-end 0) ip))
3199 t)))
3201 (defun org-activate-dates (limit)
3202 "Run through the buffer and add overlays to dates."
3203 (if (re-search-forward org-tsr-regexp limit t)
3204 (progn
3205 (add-text-properties (match-beginning 0) (match-end 0)
3206 (list 'mouse-face 'highlight
3207 'keymap org-mouse-map))
3208 t)))
3210 (defvar org-target-link-regexp nil
3211 "Regular expression matching radio targets in plain text.")
3212 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3213 "Regular expression matching a link target.")
3214 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3215 "Regular expression matching a link target.")
3217 (defun org-activate-target-links (limit)
3218 "Run through the buffer and add overlays to target matches."
3219 (when org-target-link-regexp
3220 (let ((case-fold-search t))
3221 (if (re-search-forward org-target-link-regexp limit t)
3222 (progn
3223 (add-text-properties (match-beginning 0) (match-end 0)
3224 (list 'mouse-face 'highlight
3225 'keymap org-mouse-map
3226 'help-echo "Radio target link"
3227 'org-linked-text t))
3228 t)))))
3230 (defun org-update-radio-target-regexp ()
3231 "Find all radio targets in this file and update the regular expression."
3232 (interactive)
3233 (when (memq 'radio org-activate-links)
3234 (setq org-target-link-regexp
3235 (org-make-target-link-regexp (org-all-targets 'radio)))
3236 (org-restart-font-lock)))
3238 (defun org-hide-wide-columns (limit)
3239 (let (s e)
3240 (setq s (text-property-any (point) (or limit (point-max))
3241 'org-cwidth t))
3242 (when s
3243 (setq e (next-single-property-change s 'org-cwidth))
3244 (add-text-properties s e '(invisible org-cwidth intangible t))
3245 (goto-char e)
3246 t)))
3248 (defun org-restart-font-lock ()
3249 "Restart font-lock-mode, to force refontification."
3250 (when (and (boundp 'font-lock-mode) font-lock-mode)
3251 (font-lock-mode -1)
3252 (font-lock-mode 1)))
3254 (defun org-all-targets (&optional radio)
3255 "Return a list of all targets in this file.
3256 With optional argument RADIO, only find radio targets."
3257 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3258 rtn)
3259 (save-excursion
3260 (goto-char (point-min))
3261 (while (re-search-forward re nil t)
3262 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3263 rtn)))
3265 (defun org-make-target-link-regexp (targets)
3266 "Make regular expression matching all strings in TARGETS.
3267 The regular expression finds the targets also if there is a line break
3268 between words."
3269 (and targets
3270 (concat
3271 "\\<\\("
3272 (mapconcat
3273 (lambda (x)
3274 (while (string-match " +" x)
3275 (setq x (replace-match "\\s-+" t t x)))
3277 targets
3278 "\\|")
3279 "\\)\\>")))
3281 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3282 "Matches CamelCase words, possibly with a star before it.")
3284 (defun org-activate-camels (limit)
3285 "Run through the buffer and add overlays to dates."
3286 (if (re-search-forward org-camel-regexp limit t)
3287 (progn
3288 (add-text-properties (match-beginning 0) (match-end 0)
3289 (list 'mouse-face 'highlight
3290 'keymap org-mouse-map))
3291 t)))
3293 (defun org-activate-tags (limit)
3294 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3295 (progn
3296 (add-text-properties (match-beginning 1) (match-end 1)
3297 (list 'mouse-face 'highlight
3298 'keymap org-mouse-map))
3299 t)))
3301 (defun org-font-lock-level ()
3302 (save-excursion
3303 (org-back-to-heading t)
3304 (- (match-end 0) (match-beginning 0))))
3306 (defun org-outline-level ()
3307 (save-excursion
3308 (looking-at outline-regexp)
3309 (if (match-beginning 1)
3310 (+ (org-get-string-indentation (match-string 1)) 1000)
3311 (- (match-end 0) (match-beginning 0)))))
3313 (defvar org-font-lock-keywords nil)
3315 (defun org-set-font-lock-defaults ()
3316 (let* ((em org-fontify-emphasized-text)
3317 (lk org-activate-links)
3318 (org-font-lock-extra-keywords
3319 ;; Headlines
3320 (list
3321 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3322 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3323 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3324 (1 'org-table))
3325 ;; Links
3326 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3327 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3328 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3329 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3330 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3331 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3332 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3333 (if org-table-limit-column-width
3334 '(org-hide-wide-columns (0 nil append)))
3335 ;; TODO lines
3336 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3337 '(1 'org-todo t))
3338 ;; Priorities
3339 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3340 ;; Special keywords
3341 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3342 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3343 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3344 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3345 ;; Emphasis
3346 (if em '(org-do-emphasis-faces))
3347 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3348 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3349 2 'bold prepend)
3350 (if org-provide-checkbox-statistics
3351 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3352 (0 (org-get-checkbox-statistics-face) t)))
3353 ;; COMMENT
3354 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3355 "\\|" org-quote-string "\\)\\>")
3356 '(1 'org-special-keyword t))
3357 '("^#.*" (0 'font-lock-comment-face t))
3358 ;; DONE
3359 (if org-fontify-done-headline
3360 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3361 '(1 'org-done t) '(2 'org-headline-done t))
3362 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3363 '(1 'org-done t)))
3364 ;; Table stuff
3365 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3366 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3367 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3368 (if org-format-transports-properties-p
3369 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3370 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3372 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3373 ;; Now set the full font-lock-keywords
3374 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3375 (org-set-local 'font-lock-defaults
3376 '(org-font-lock-keywords t nil nil backward-paragraph))
3377 (kill-local-variable 'font-lock-keywords) nil))
3379 (defvar org-m nil)
3380 (defvar org-l nil)
3381 (defvar org-f nil)
3382 (defun org-get-level-face (n)
3383 "Get the right face for match N in font-lock matching of healdines."
3384 (setq org-l (- (match-end 2) (match-beginning 1)))
3385 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3386 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3387 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3388 (cond
3389 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3390 ((eq n 2) org-f)
3391 (t (if org-level-color-stars-only nil org-f))))
3393 (defun org-unfontify-region (beg end &optional maybe_loudly)
3394 "Remove fontification and activation overlays from links."
3395 (font-lock-default-unfontify-region beg end)
3396 (let* ((buffer-undo-list t)
3397 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3398 (inhibit-modification-hooks t)
3399 deactivate-mark buffer-file-name buffer-file-truename)
3400 (remove-text-properties beg end
3401 '(mouse-face nil keymap nil org-linked-text nil
3402 invisible nil intangible nil))))
3403 ;;; Visibility cycling
3405 (defvar org-cycle-global-status nil)
3406 (make-variable-buffer-local 'org-cycle-global-status)
3407 (defvar org-cycle-subtree-status nil)
3408 (make-variable-buffer-local 'org-cycle-subtree-status)
3410 ;;;###autoload
3411 (defun org-cycle (&optional arg)
3412 "Visibility cycling for Org-mode.
3414 - When this function is called with a prefix argument, rotate the entire
3415 buffer through 3 states (global cycling)
3416 1. OVERVIEW: Show only top-level headlines.
3417 2. CONTENTS: Show all headlines of all levels, but no body text.
3418 3. SHOW ALL: Show everything.
3420 - When point is at the beginning of a headline, rotate the subtree started
3421 by this line through 3 different states (local cycling)
3422 1. FOLDED: Only the main headline is shown.
3423 2. CHILDREN: The main headline and the direct children are shown.
3424 From this state, you can move to one of the children
3425 and zoom in further.
3426 3. SUBTREE: Show the entire subtree, including body text.
3428 - When there is a numeric prefix, go up to a heading with level ARG, do
3429 a `show-subtree' and return to the previous cursor position. If ARG
3430 is negative, go up that many levels.
3432 - When point is not at the beginning of a headline, execute
3433 `indent-relative', like TAB normally does. See the option
3434 `org-cycle-emulate-tab' for details.
3436 - Special case: if point is the the beginning of the buffer and there is
3437 no headline in line 1, this function will act as if called with prefix arg."
3438 (interactive "P")
3439 (let* ((outline-regexp
3440 (if org-cycle-include-plain-lists
3441 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3442 outline-regexp))
3443 (bob-special (and org-cycle-global-at-bob (bobp)
3444 (not (looking-at outline-regexp))))
3445 (org-cycle-hook
3446 (if bob-special
3447 (delq 'org-optimize-window-after-visibility-change
3448 (copy-sequence org-cycle-hook))
3449 org-cycle-hook))
3450 (pos (point)))
3452 (if (or bob-special (equal arg '(4)))
3453 ;; special case: use global cycling
3454 (setq arg t))
3456 (cond
3458 ((org-at-table-p 'any)
3459 ;; Enter the table or move to the next field in the table
3460 (or (org-table-recognize-table.el)
3461 (progn
3462 (if arg (org-table-edit-field t)
3463 (org-table-justify-field-maybe)
3464 (call-interactively 'org-table-next-field)))))
3466 ((eq arg t) ;; Global cycling
3468 (cond
3469 ((and (eq last-command this-command)
3470 (eq org-cycle-global-status 'overview))
3471 ;; We just created the overview - now do table of contents
3472 ;; This can be slow in very large buffers, so indicate action
3473 (message "CONTENTS...")
3474 (org-content)
3475 (message "CONTENTS...done")
3476 (setq org-cycle-global-status 'contents)
3477 (run-hook-with-args 'org-cycle-hook 'contents))
3479 ((and (eq last-command this-command)
3480 (eq org-cycle-global-status 'contents))
3481 ;; We just showed the table of contents - now show everything
3482 (show-all)
3483 (message "SHOW ALL")
3484 (setq org-cycle-global-status 'all)
3485 (run-hook-with-args 'org-cycle-hook 'all))
3488 ;; Default action: go to overview
3489 (org-overview)
3490 (message "OVERVIEW")
3491 (setq org-cycle-global-status 'overview)
3492 (run-hook-with-args 'org-cycle-hook 'overview))))
3494 ((integerp arg)
3495 ;; Show-subtree, ARG levels up from here.
3496 (save-excursion
3497 (org-back-to-heading)
3498 (outline-up-heading (if (< arg 0) (- arg)
3499 (- (funcall outline-level) arg)))
3500 (org-show-subtree)))
3502 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3503 ;; At a heading: rotate between three different views
3504 (org-back-to-heading)
3505 (let ((goal-column 0) eoh eol eos)
3506 ;; First, some boundaries
3507 (save-excursion
3508 (org-back-to-heading)
3509 (save-excursion
3510 (beginning-of-line 2)
3511 (while (and (not (eobp)) ;; this is like `next-line'
3512 (get-char-property (1- (point)) 'invisible))
3513 (beginning-of-line 2)) (setq eol (point)))
3514 (outline-end-of-heading) (setq eoh (point))
3515 (org-end-of-subtree t) (setq eos (point))
3516 (outline-next-heading))
3517 ;; Find out what to do next and set `this-command'
3518 (cond
3519 ((and (= eos eoh)
3520 ;; Nothing is hidden behind this heading
3521 (message "EMPTY ENTRY")
3522 (setq org-cycle-subtree-status nil)))
3523 ((>= eol eos)
3524 ;; Entire subtree is hidden in one line: open it
3525 (org-show-entry)
3526 (show-children)
3527 (message "CHILDREN")
3528 (setq org-cycle-subtree-status 'children)
3529 (run-hook-with-args 'org-cycle-hook 'children))
3530 ((and (eq last-command this-command)
3531 (eq org-cycle-subtree-status 'children))
3532 ;; We just showed the children, now show everything.
3533 (org-show-subtree)
3534 (message "SUBTREE")
3535 (setq org-cycle-subtree-status 'subtree)
3536 (run-hook-with-args 'org-cycle-hook 'subtree))
3538 ;; Default action: hide the subtree.
3539 (hide-subtree)
3540 (message "FOLDED")
3541 (setq org-cycle-subtree-status 'folded)
3542 (run-hook-with-args 'org-cycle-hook 'folded)))))
3544 ;; TAB emulation
3545 (buffer-read-only (org-back-to-heading))
3547 ((org-try-cdlatex-tab))
3549 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3550 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3551 (or (and (eq org-cycle-emulate-tab 'white)
3552 (= (match-end 0) (point-at-eol)))
3553 (and (eq org-cycle-emulate-tab 'whitestart)
3554 (>= (match-end 0) pos))))
3556 (eq org-cycle-emulate-tab t))
3557 (if (and (looking-at "[ \n\r\t]")
3558 (string-match "^[ \t]*$" (buffer-substring
3559 (point-at-bol) (point))))
3560 (progn
3561 (beginning-of-line 1)
3562 (and (looking-at "[ \t]+") (replace-match ""))))
3563 (indent-relative))
3565 (t (save-excursion
3566 (org-back-to-heading)
3567 (org-cycle))))))
3569 ;;;###autoload
3570 (defun org-global-cycle (&optional arg)
3571 "Cycle the global visibility. For details see `org-cycle'."
3572 (interactive "P")
3573 (if (integerp arg)
3574 (progn
3575 (show-all)
3576 (hide-sublevels arg)
3577 (setq org-cycle-global-status 'contents))
3578 (org-cycle '(4))))
3580 (defun org-overview ()
3581 "Switch to overview mode, shoing only top-level headlines.
3582 Really, this shows all headlines with level equal or greater than the level
3583 of the first headline in the buffer. This is important, because if the
3584 first headline is not level one, then (hide-sublevels 1) gives confusing
3585 results."
3586 (interactive)
3587 (hide-sublevels (save-excursion
3588 (goto-char (point-min))
3589 (if (re-search-forward (concat "^" outline-regexp) nil t)
3590 (progn
3591 (goto-char (match-beginning 0))
3592 (funcall outline-level))
3593 1))))
3595 ;; FIXME: allow an argument to give a limiting level for this.
3596 (defun org-content ()
3597 "Show all headlines in the buffer, like a table of contents"
3598 (interactive)
3599 (save-excursion
3600 ;; Visit all headings and show their offspring
3601 (goto-char (point-max))
3602 (catch 'exit
3603 (while (and (progn (condition-case nil
3604 (outline-previous-visible-heading 1)
3605 (error (goto-char (point-min))))
3607 (looking-at outline-regexp))
3608 (show-branches)
3609 (if (bobp) (throw 'exit nil))))))
3612 (defun org-optimize-window-after-visibility-change (state)
3613 "Adjust the window after a change in outline visibility.
3614 This function is the default value of the hook `org-cycle-hook'."
3615 (when (get-buffer-window (current-buffer))
3616 (cond
3617 ((eq state 'overview) (org-first-headline-recenter 1))
3618 ((eq state 'content) nil)
3619 ((eq state 'all) nil)
3620 ((eq state 'folded) nil)
3621 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3622 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3624 (defun org-subtree-end-visible-p ()
3625 "Is the end of the current subtree visible?"
3626 (pos-visible-in-window-p
3627 (save-excursion (org-end-of-subtree t) (point))))
3629 (defun org-first-headline-recenter (&optional N)
3630 "Move cursor to the first headline and recenter the headline.
3631 Optional argument N means, put the headline into the Nth line of the window."
3632 (goto-char (point-min))
3633 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3634 (beginning-of-line)
3635 (recenter (prefix-numeric-value N))))
3637 (defvar org-goto-window-configuration nil)
3638 (defvar org-goto-marker nil)
3639 (defvar org-goto-map (make-sparse-keymap))
3640 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3641 (while (setq cmd (pop cmds))
3642 (substitute-key-definition cmd cmd org-goto-map global-map)))
3643 (define-key org-goto-map "\C-m" 'org-goto-ret)
3644 (define-key org-goto-map [(left)] 'org-goto-left)
3645 (define-key org-goto-map [(right)] 'org-goto-right)
3646 (define-key org-goto-map [(?q)] 'org-goto-quit)
3647 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3648 (define-key org-goto-map "\C-i" 'org-cycle)
3649 (define-key org-goto-map [(tab)] 'org-cycle)
3650 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3651 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3652 (define-key org-goto-map "n" 'outline-next-visible-heading)
3653 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3654 (define-key org-goto-map "f" 'outline-forward-same-level)
3655 (define-key org-goto-map "b" 'outline-backward-same-level)
3656 (define-key org-goto-map "u" 'outline-up-heading)
3657 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3658 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3659 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3660 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3661 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3662 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3663 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3665 (defconst org-goto-help
3666 "Select a location to jump to, press RET
3667 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3669 (defun org-goto ()
3670 "Go to a different location of the document, keeping current visibility.
3672 When you want to go to a different location in a document, the fastest way
3673 is often to fold the entire buffer and then dive into the tree. This
3674 method has the disadvantage, that the previous location will be folded,
3675 which may not be what you want.
3677 This command works around this by showing a copy of the current buffer in
3678 overview mode. You can dive into the tree in that copy, to find the
3679 location you want to reach. When pressing RET, the command returns to the
3680 original buffer in which the visibility is still unchanged. It then jumps
3681 to the new location, making it and the headline hierarchy above it visible."
3682 (interactive)
3683 (let* ((org-goto-start-pos (point))
3684 (selected-point
3685 (org-get-location (current-buffer) org-goto-help)))
3686 (if selected-point
3687 (progn
3688 (org-mark-ring-push org-goto-start-pos)
3689 (goto-char selected-point)
3690 (if (or (org-invisible-p) (org-invisible-p2))
3691 (org-show-hierarchy-above)))
3692 (error "Quit"))))
3694 (defun org-get-location (buf help)
3695 "Let the user select a location in the Org-mode buffer BUF.
3696 This function uses a recursive edit. It returns the selected position
3697 or nil."
3698 (let (org-selected-point)
3699 (save-excursion
3700 (save-window-excursion
3701 (delete-other-windows)
3702 (switch-to-buffer (get-buffer-create "*org-goto*"))
3703 (with-output-to-temp-buffer "*Help*"
3704 (princ help))
3705 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3706 (setq buffer-read-only nil)
3707 (erase-buffer)
3708 (insert-buffer-substring buf)
3709 (let ((org-startup-truncated t)
3710 (org-startup-folded t)
3711 (org-startup-align-all-tables nil)
3712 (org-startup-with-deadline-check nil))
3713 (org-mode))
3714 (setq buffer-read-only t)
3715 (if (boundp 'org-goto-start-pos)
3716 (goto-char org-goto-start-pos)
3717 (goto-char (point-min)))
3718 (org-beginning-of-line)
3719 (message "Select location and press RET")
3720 ;; now we make sure that during selection, ony very few keys work
3721 ;; and that it is impossible to switch to another window.
3722 (let ((gm (current-global-map))
3723 (overriding-local-map org-goto-map))
3724 (unwind-protect
3725 (progn
3726 (use-global-map org-goto-map)
3727 (recursive-edit))
3728 (use-global-map gm)))))
3729 (kill-buffer "*org-goto*")
3730 org-selected-point))
3732 (defun org-goto-ret (&optional arg)
3733 "Finish `org-goto' by going to the new location."
3734 (interactive "P")
3735 (setq org-selected-point (point)
3736 current-prefix-arg arg)
3737 (throw 'exit nil))
3739 (defun org-goto-left ()
3740 "Finish `org-goto' by going to the new location."
3741 (interactive)
3742 (if (org-on-heading-p)
3743 (progn
3744 (beginning-of-line 1)
3745 (setq org-selected-point (point)
3746 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3747 (throw 'exit nil))
3748 (error "Not on a heading")))
3750 (defun org-goto-right ()
3751 "Finish `org-goto' by going to the new location."
3752 (interactive)
3753 (if (org-on-heading-p)
3754 (progn
3755 (outline-end-of-subtree)
3756 (or (eobp) (forward-char 1))
3757 (setq org-selected-point (point)
3758 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3759 (throw 'exit nil))
3760 (error "Not on a heading")))
3762 (defun org-goto-quit ()
3763 "Finish `org-goto' without cursor motion."
3764 (interactive)
3765 (setq org-selected-point nil)
3766 (throw 'exit nil))
3768 ;;; Promotion, Demotion, Inserting new headlines
3770 (defvar org-ignore-region nil
3771 "To temporarily disable the active region.")
3773 (defun org-insert-heading (&optional force-heading)
3774 "Insert a new heading or item with same depth at point.
3775 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3776 If point is at the beginning of a headline, insert a sibling before the
3777 current headline. If point is in the middle of a headline, split the headline
3778 at that position and make the rest of the headline part of the sibling below
3779 the current headline."
3780 (interactive "P")
3781 (if (= (buffer-size) 0)
3782 (insert "\n* ")
3783 (when (or force-heading (not (org-insert-item)))
3784 (let* ((head (save-excursion
3785 (condition-case nil
3786 (progn
3787 (org-back-to-heading)
3788 (match-string 0))
3789 (error "*"))))
3790 pos)
3791 (cond
3792 ((and (org-on-heading-p) (bolp)
3793 (save-excursion (backward-char 1) (not (org-invisible-p))))
3794 (open-line 1))
3795 ((and (bolp) (save-excursion
3796 (backward-char 1) (not (org-invisible-p))))
3797 nil)
3798 (t (newline)))
3799 (insert head) (just-one-space)
3800 (setq pos (point))
3801 (end-of-line 1)
3802 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3803 (run-hooks 'org-insert-heading-hook)))))
3805 (defun org-in-item-p ()
3806 "It the cursor inside a plain list item.
3807 Does not have to be the first line."
3808 (save-excursion
3809 (condition-case nil
3810 (progn
3811 (org-beginning-of-item)
3812 (org-at-item-p)
3814 (error nil))))
3816 (defun org-insert-item (&optional checkbox)
3817 "Insert a new item at the current level.
3818 Return t when things worked, nil when we are not in an item."
3819 (when (save-excursion
3820 (condition-case nil
3821 (progn
3822 (org-beginning-of-item)
3823 (org-at-item-p)
3825 (error nil)))
3826 (let* ((bul (match-string 0))
3827 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3828 (match-end 0)))
3829 pos)
3830 (cond
3831 ((and (org-at-item-p) (<= (point) eow))
3832 ;; before the bullet
3833 (beginning-of-line 1)
3834 (open-line 1))
3835 ((<= (point) eow)
3836 (beginning-of-line 1))
3837 (t (newline)))
3838 (insert bul (if checkbox "[ ]" ""))
3839 (just-one-space)
3840 (setq pos (point))
3841 (end-of-line 1)
3842 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3843 (org-maybe-renumber-ordered-list)
3844 (and checkbox (org-update-checkbox-count-maybe))
3847 (defun org-insert-todo-heading (arg)
3848 "Insert a new heading with the same level and TODO state as current heading.
3849 If the heading has no TODO state, or if the state is DONE, use the first
3850 state (TODO by default). Also with prefix arg, force first state."
3851 (interactive "P")
3852 (when (not (org-insert-item 'checkbox))
3853 (org-insert-heading)
3854 (save-excursion
3855 (org-back-to-heading)
3856 (outline-previous-heading)
3857 (looking-at org-todo-line-regexp))
3858 (if (or arg
3859 (not (match-beginning 2))
3860 (equal (match-string 2) org-done-string))
3861 (insert (car org-todo-keywords) " ")
3862 (insert (match-string 2) " "))))
3864 (defun org-promote-subtree ()
3865 "Promote the entire subtree.
3866 See also `org-promote'."
3867 (interactive)
3868 (save-excursion
3869 (org-map-tree 'org-promote))
3870 (org-fix-position-after-promote))
3872 (defun org-demote-subtree ()
3873 "Demote the entire subtree. See `org-demote'.
3874 See also `org-promote'."
3875 (interactive)
3876 (save-excursion
3877 (org-map-tree 'org-demote))
3878 (org-fix-position-after-promote))
3881 (defun org-do-promote ()
3882 "Promote the current heading higher up the tree.
3883 If the region is active in `transient-mark-mode', promote all headings
3884 in the region."
3885 (interactive)
3886 (save-excursion
3887 (if (org-region-active-p)
3888 (org-map-region 'org-promote (region-beginning) (region-end))
3889 (org-promote)))
3890 (org-fix-position-after-promote))
3892 (defun org-do-demote ()
3893 "Demote the current heading lower down the tree.
3894 If the region is active in `transient-mark-mode', demote all headings
3895 in the region."
3896 (interactive)
3897 (save-excursion
3898 (if (org-region-active-p)
3899 (org-map-region 'org-demote (region-beginning) (region-end))
3900 (org-demote)))
3901 (org-fix-position-after-promote))
3903 (defun org-fix-position-after-promote ()
3904 "Make sure that after pro/demotion cursor position is right."
3905 (if (and (equal (char-after) ?\n)
3906 (save-excursion
3907 (skip-chars-backward "a-zA-Z0-9_@")
3908 (looking-at org-todo-regexp)))
3909 (insert " "))
3910 (and (equal (char-after) ?\ )
3911 (equal (char-before) ?*)
3912 (forward-char 1)))
3914 (defun org-get-legal-level (level change)
3915 "Rectify a level change under the influence of `org-odd-levels-only'
3916 LEVEL is a current level, CHANGE is by how much the level should be
3917 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3918 even level numbers will become the next higher odd number."
3919 (if org-odd-levels-only
3920 (cond ((not change) (1+ (* 2 (/ level 2))))
3921 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3922 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3923 (max 1 (+ level change))))
3925 (defun org-promote ()
3926 "Promote the current heading higher up the tree.
3927 If the region is active in `transient-mark-mode', promote all headings
3928 in the region."
3929 (org-back-to-heading t)
3930 (let* ((level (save-match-data (funcall outline-level)))
3931 (up-head (make-string (org-get-legal-level level -1) ?*))
3932 (diff (abs (- level (length up-head)))))
3933 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3934 (replace-match up-head nil t)
3935 ;; Fixup tag positioning
3936 (and org-auto-align-tags (org-set-tags nil t))
3937 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3939 (defun org-demote ()
3940 "Demote the current heading lower down the tree.
3941 If the region is active in `transient-mark-mode', demote all headings
3942 in the region."
3943 (org-back-to-heading t)
3944 (let* ((level (save-match-data (funcall outline-level)))
3945 (down-head (make-string (org-get-legal-level level 1) ?*))
3946 (diff (abs (- level (length down-head)))))
3947 (replace-match down-head nil t)
3948 ;; Fixup tag positioning
3949 (and org-auto-align-tags (org-set-tags nil t))
3950 (if org-adapt-indentation (org-fixup-indentation diff))))
3952 (defun org-map-tree (fun)
3953 "Call FUN for every heading underneath the current one."
3954 (org-back-to-heading)
3955 (let ((level (funcall outline-level)))
3956 (save-excursion
3957 (funcall fun)
3958 (while (and (progn
3959 (outline-next-heading)
3960 (> (funcall outline-level) level))
3961 (not (eobp)))
3962 (funcall fun)))))
3964 (defun org-map-region (fun beg end)
3965 "Call FUN for every heading between BEG and END."
3966 (let ((org-ignore-region t))
3967 (save-excursion
3968 (setq end (copy-marker end))
3969 (goto-char beg)
3970 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3971 (< (point) end))
3972 (funcall fun))
3973 (while (and (progn
3974 (outline-next-heading)
3975 (< (point) end))
3976 (not (eobp)))
3977 (funcall fun)))))
3979 (defun org-fixup-indentation (diff)
3980 "Change the indentation in the current entry by DIFF
3981 However, if any line in the current entry has no indentation, or if it
3982 would end up with no indentation after the change, nothing at all is done."
3983 (save-excursion
3984 (let ((end (save-excursion (outline-next-heading)
3985 (point-marker)))
3986 (prohibit (if (> diff 0)
3987 "^\\S-"
3988 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3989 col)
3990 (unless (save-excursion (re-search-forward prohibit end t))
3991 (while (re-search-forward "^[ \t]+" end t)
3992 (goto-char (match-end 0))
3993 (setq col (current-column))
3994 (if (< diff 0) (replace-match ""))
3995 (indent-to (+ diff col))))
3996 (move-marker end nil))))
3998 ;;; Vertical tree motion, cutting and pasting of subtrees
4000 (defun org-move-subtree-up (&optional arg)
4001 "Move the current subtree up past ARG headlines of the same level."
4002 (interactive "p")
4003 (org-move-subtree-down (- (prefix-numeric-value arg))))
4005 (defun org-move-subtree-down (&optional arg)
4006 "Move the current subtree down past ARG headlines of the same level."
4007 (interactive "p")
4008 (setq arg (prefix-numeric-value arg))
4009 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4010 'outline-get-last-sibling))
4011 (ins-point (make-marker))
4012 (cnt (abs arg))
4013 beg end txt folded)
4014 ;; Select the tree
4015 (org-back-to-heading)
4016 (setq beg (point))
4017 (save-match-data
4018 (save-excursion (outline-end-of-heading)
4019 (setq folded (org-invisible-p)))
4020 (outline-end-of-subtree))
4021 (outline-next-heading)
4022 (setq end (point))
4023 ;; Find insertion point, with error handling
4024 (goto-char beg)
4025 (while (> cnt 0)
4026 (or (and (funcall movfunc) (looking-at outline-regexp))
4027 (progn (goto-char beg)
4028 (error "Cannot move past superior level or buffer limit")))
4029 (setq cnt (1- cnt)))
4030 (if (> arg 0)
4031 ;; Moving forward - still need to move over subtree
4032 (progn (outline-end-of-subtree)
4033 (outline-next-heading)
4034 (if (not (or (looking-at (concat "^" outline-regexp))
4035 (bolp)))
4036 (newline))))
4037 (move-marker ins-point (point))
4038 (setq txt (buffer-substring beg end))
4039 (delete-region beg end)
4040 (insert txt)
4041 (goto-char ins-point)
4042 (if folded (hide-subtree))
4043 (move-marker ins-point nil)))
4045 (defvar org-subtree-clip ""
4046 "Clipboard for cut and paste of subtrees.
4047 This is actually only a copy of the kill, because we use the normal kill
4048 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4050 (defvar org-subtree-clip-folded nil
4051 "Was the last copied subtree folded?
4052 This is used to fold the tree back after pasting.")
4054 (defun org-cut-subtree ()
4055 "Cut the current subtree into the clipboard.
4056 This is a short-hand for marking the subtree and then cutting it."
4057 (interactive)
4058 (org-copy-subtree 'cut))
4060 (defun org-copy-subtree (&optional cut)
4061 "Cut the current subtree into the clipboard.
4062 This is a short-hand for marking the subtree and then copying it.
4063 If CUT is non nil, actually cut the subtree."
4064 (interactive)
4065 (let (beg end folded)
4066 (org-back-to-heading)
4067 (setq beg (point))
4068 (save-match-data
4069 (save-excursion (outline-end-of-heading)
4070 (setq folded (org-invisible-p)))
4071 (outline-end-of-subtree))
4072 (if (equal (char-after) ?\n) (forward-char 1))
4073 (setq end (point))
4074 (goto-char beg)
4075 (when (> end beg)
4076 (setq org-subtree-clip-folded folded)
4077 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4078 (setq org-subtree-clip (current-kill 0))
4079 (message "%s: Subtree with %d characters"
4080 (if cut "Cut" "Copied")
4081 (length org-subtree-clip)))))
4083 (defun org-paste-subtree (&optional level tree)
4084 "Paste the clipboard as a subtree, with modification of headline level.
4085 The entire subtree is promoted or demoted in order to match a new headline
4086 level. By default, the new level is derived from the visible headings
4087 before and after the insertion point, and taken to be the inferior headline
4088 level of the two. So if the previous visible heading is level 3 and the
4089 next is level 4 (or vice versa), level 4 will be used for insertion.
4090 This makes sure that the subtree remains an independent subtree and does
4091 not swallow low level entries.
4093 You can also force a different level, either by using a numeric prefix
4094 argument, or by inserting the heading marker by hand. For example, if the
4095 cursor is after \"*****\", then the tree will be shifted to level 5.
4097 If you want to insert the tree as is, just use \\[yank].
4099 If optional TREE is given, use this text instead of the kill ring."
4100 (interactive "P")
4101 (unless (org-kill-is-subtree-p tree)
4102 (error
4103 (substitute-command-keys
4104 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4105 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4106 (^re (concat "^\\(" outline-regexp "\\)"))
4107 (re (concat "\\(" outline-regexp "\\)"))
4108 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4110 (old-level (if (string-match ^re txt)
4111 (- (match-end 0) (match-beginning 0))
4112 -1))
4113 (force-level (cond (level (prefix-numeric-value level))
4114 ((string-match
4115 ^re_ (buffer-substring (point-at-bol) (point)))
4116 (- (match-end 0) (match-beginning 0)))
4117 (t nil)))
4118 (previous-level (save-excursion
4119 (condition-case nil
4120 (progn
4121 (outline-previous-visible-heading 1)
4122 (if (looking-at re)
4123 (- (match-end 0) (match-beginning 0))
4125 (error 1))))
4126 (next-level (save-excursion
4127 (condition-case nil
4128 (progn
4129 (outline-next-visible-heading 1)
4130 (if (looking-at re)
4131 (- (match-end 0) (match-beginning 0))
4133 (error 1))))
4134 (new-level (or force-level (max previous-level next-level)))
4135 (shift (if (or (= old-level -1)
4136 (= new-level -1)
4137 (= old-level new-level))
4139 (- new-level old-level)))
4140 (shift1 shift)
4141 (delta (if (> shift 0) -1 1))
4142 (func (if (> shift 0) 'org-demote 'org-promote))
4143 (org-odd-levels-only nil)
4144 beg end)
4145 ;; Remove the forces level indicator
4146 (if force-level
4147 (delete-region (point-at-bol) (point)))
4148 ;; Make sure we start at the beginning of an empty line
4149 (if (not (bolp)) (insert "\n"))
4150 (if (not (looking-at "[ \t]*$"))
4151 (progn (insert "\n") (backward-char 1)))
4152 ;; Paste
4153 (setq beg (point))
4154 (if (string-match "[ \t\r\n]+\\'" txt)
4155 (setq txt (replace-match "\n" t t txt)))
4156 (insert txt)
4157 (setq end (point))
4158 (if (looking-at "[ \t\r\n]+")
4159 (replace-match "\n"))
4160 (goto-char beg)
4161 ;; Shift if necessary
4162 (if (= shift 0)
4163 (message "Pasted at level %d, without shift" new-level)
4164 (save-restriction
4165 (narrow-to-region beg end)
4166 (while (not (= shift 0))
4167 (org-map-region func (point-min) (point-max))
4168 (setq shift (+ delta shift)))
4169 (goto-char (point-min))
4170 (message "Pasted at level %d, with shift by %d levels"
4171 new-level shift1)))
4172 (if (and kill-ring
4173 (eq org-subtree-clip (current-kill 0))
4174 org-subtree-clip-folded)
4175 ;; The tree was folded before it was killed/copied
4176 (hide-subtree))))
4178 (defun org-kill-is-subtree-p (&optional txt)
4179 "Check if the current kill is an outline subtree, or a set of trees.
4180 Returns nil if kill does not start with a headline, or if the first
4181 headline level is not the largest headline level in the tree.
4182 So this will actually accept several entries of equal levels as well,
4183 which is OK for `org-paste-subtree'.
4184 If optional TXT is given, check this string instead of the current kill."
4185 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4186 (start-level (and kill
4187 (string-match (concat "\\`" outline-regexp) kill)
4188 (- (match-end 0) (match-beginning 0))))
4189 (re (concat "^" outline-regexp))
4190 (start 1))
4191 (if (not start-level)
4192 nil ;; does not even start with a heading
4193 (catch 'exit
4194 (while (setq start (string-match re kill (1+ start)))
4195 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4196 (throw 'exit nil)))
4197 t))))
4199 (defun org-narrow-to-subtree ()
4200 "Narrow buffer to the current subtree."
4201 (interactive)
4202 (save-excursion
4203 (narrow-to-region
4204 (progn (org-back-to-heading) (point))
4205 (progn (org-end-of-subtree t) (point)))))
4207 ;;; Plain list items
4209 (defun org-at-item-p ()
4210 "Is point in a line starting a hand-formatted item?"
4211 (let ((llt org-plain-list-ordered-item-terminator))
4212 (save-excursion
4213 (goto-char (point-at-bol))
4214 (looking-at
4215 (cond
4216 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4217 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4218 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4219 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4221 (defun org-at-item-checkbox-p ()
4222 "Is point at a line starting a plain-list item with a checklet?"
4223 (and (org-at-item-p)
4224 (save-excursion
4225 (goto-char (match-end 0))
4226 (skip-chars-forward " \t")
4227 (looking-at "\\[[ X]\\]"))))
4229 (defun org-toggle-checkbox (&optional arg)
4230 "Toggle the checkbox in the current line."
4231 (interactive "P")
4232 (catch 'exit
4233 (let (beg end status (firstnew 'unknown))
4234 (cond
4235 ((org-region-active-p)
4236 (setq beg (region-beginning) end (region-end)))
4237 ((org-on-heading-p)
4238 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4239 ((org-at-item-checkbox-p)
4240 (save-excursion
4241 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4242 (throw 'exit t))
4243 (t (error "Not at a checkbox or heading, and no active region")))
4244 (save-excursion
4245 (goto-char beg)
4246 (while (< (point) end)
4247 (when (org-at-item-checkbox-p)
4248 (setq status (equal (match-string 0) "[X]"))
4249 (when (eq firstnew 'unknown)
4250 (setq firstnew (not status)))
4251 (replace-match
4252 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4253 (beginning-of-line 2)))))
4254 (org-update-checkbox-count-maybe))
4256 (defun org-update-checkbox-count-maybe ()
4257 "Update checkbox statistics unless turned off by user."
4258 (when org-provide-checkbox-statistics
4259 (org-update-checkbox-count)))
4261 (defun org-update-checkbox-count (&optional all)
4262 "Update the checkbox statistics in the current section.
4263 This will find all statistic cookies like [57%] and [6/12] and update them
4264 with the current numbers. With optional prefix argument ALL, do this for
4265 the whole buffer."
4266 (interactive "P")
4267 (save-excursion
4268 (let* ((buffer-invisibility-spec nil)
4269 (beg (progn (outline-back-to-heading) (point)))
4270 (end (move-marker (make-marker)
4271 (progn (outline-next-heading) (point))))
4272 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
4273 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
4274 b1 e1 f1 c-on c-off lim (cstat 0))
4275 (when all
4276 (goto-char (point-min))
4277 (outline-next-heading)
4278 (setq beg (point) end (point-max)))
4279 (goto-char beg)
4280 (while (re-search-forward re end t)
4281 (setq cstat (1+ cstat)
4282 b1 (match-beginning 0)
4283 e1 (match-end 0)
4284 f1 (match-beginning 1)
4285 lim (cond
4286 ((org-on-heading-p) (outline-next-heading) (point))
4287 ((org-at-item-p) (org-end-of-item) (point))
4288 (t nil))
4289 c-on 0 c-off 0)
4290 (goto-char e1)
4291 (when lim
4292 (while (re-search-forward re-box lim t)
4293 (if (equal (match-string 2) "[ ]")
4294 (setq c-off (1+ c-off))
4295 (setq c-on (1+ c-on))))
4296 (delete-region b1 e1)
4297 (goto-char b1)
4298 (insert (if f1
4299 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
4300 (format "[%d/%d]" c-on (+ c-on c-off))))))
4301 (when (interactive-p)
4302 (message "Checkbox satistics updated %s (%d places)"
4303 (if all "in entire file" "in current outline entry") cstat)))))
4305 (defun org-get-checkbox-statistics-face ()
4306 "Select the face for checkbox statistics.
4307 The face will be `org-done' when all relevant boxes are checked. Otherwise
4308 it will be `org-todo'."
4309 (if (match-end 1)
4310 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
4311 (if (and (> (match-end 2) (match-beginning 2))
4312 (equal (match-string 2) (match-string 3)))
4313 'org-done
4314 'org-todo)))
4316 (defun org-get-indentation (&optional line)
4317 "Get the indentation of the current line, interpreting tabs.
4318 When LINE is given, assume it represents a line and compute its indentation."
4319 (if line
4320 (if (string-match "^ *" (org-remove-tabs line))
4321 (match-end 0))
4322 (save-excursion
4323 (beginning-of-line 1)
4324 (skip-chars-forward " \t")
4325 (current-column))))
4327 (defun org-remove-tabs (s &optional width)
4328 "Replace tabulators in S with spaces.
4329 Assumes that s is a single line, starting in column 0."
4330 (setq width (or width tab-width))
4331 (while (string-match "\t" s)
4332 (setq s (replace-match
4333 (make-string
4334 (- (* width (/ (+ (match-beginning 0) width) width))
4335 (match-beginning 0)) ?\ )
4336 t t s)))
4339 ;; FIXME: document properly.
4340 (defun org-fix-indentation (line ind)
4341 "If the current indenation is smaller than ind1, leave it alone.
4342 If it is larger than ind, reduce it by ind."
4343 (let* ((l (org-remove-tabs line))
4344 (i (org-get-indentation l))
4345 (i1 (car ind)) (i2 (cdr ind)))
4346 (if (>= i i2) (setq l (substring line i2)))
4347 (if (> i1 0)
4348 (concat (make-string i1 ?\ ) l)
4349 l)))
4351 (defun org-beginning-of-item ()
4352 "Go to the beginning of the current hand-formatted item.
4353 If the cursor is not in an item, throw an error."
4354 (interactive)
4355 (let ((pos (point))
4356 (limit (save-excursion (org-back-to-heading)
4357 (beginning-of-line 2) (point)))
4358 ind ind1)
4359 (if (org-at-item-p)
4360 (beginning-of-line 1)
4361 (beginning-of-line 1)
4362 (skip-chars-forward " \t")
4363 (setq ind (current-column))
4364 (if (catch 'exit
4365 (while t
4366 (beginning-of-line 0)
4367 (if (< (point) limit) (throw 'exit nil))
4368 (unless (looking-at "[ \t]*$")
4369 (skip-chars-forward " \t")
4370 (setq ind1 (current-column))
4371 (if (< ind1 ind)
4372 (throw 'exit (org-at-item-p))))))
4374 (goto-char pos)
4375 (error "Not in an item")))))
4377 (defun org-end-of-item ()
4378 "Go to the end of the current hand-formatted item.
4379 If the cursor is not in an item, throw an error."
4380 (interactive)
4381 (let ((pos (point))
4382 (limit (save-excursion (outline-next-heading) (point)))
4383 (ind (save-excursion
4384 (org-beginning-of-item)
4385 (skip-chars-forward " \t")
4386 (current-column)))
4387 ind1)
4388 (if (catch 'exit
4389 (while t
4390 (beginning-of-line 2)
4391 (if (>= (point) limit) (throw 'exit t))
4392 (unless (looking-at "[ \t]*$")
4393 (skip-chars-forward " \t")
4394 (setq ind1 (current-column))
4395 (if (<= ind1 ind) (throw 'exit t)))))
4396 (beginning-of-line 1)
4397 (goto-char pos)
4398 (error "Not in an item"))))
4400 (defun org-next-item ()
4401 "Move to the beginning of the next item in the current plain list.
4402 Error if not at a plain list, or if this is the last item in the list."
4403 (interactive)
4404 (let (ind ind1 (pos (point)))
4405 (org-beginning-of-item)
4406 (setq ind (org-get-indentation))
4407 (org-end-of-item)
4408 (setq ind1 (org-get-indentation))
4409 (unless (and (org-at-item-p) (= ind ind1))
4410 (goto-char pos)
4411 (error "On last item"))))
4413 (defun org-previous-item ()
4414 "Move to the beginning of the previous item in the current plain list.
4415 Error if not at a plain list, or if this is the last item in the list."
4416 (interactive)
4417 (let (beg ind (pos (point)))
4418 (org-beginning-of-item)
4419 (setq beg (point))
4420 (setq ind (org-get-indentation))
4421 (goto-char beg)
4422 (catch 'exit
4423 (while t
4424 (beginning-of-line 0)
4425 (if (looking-at "[ \t]*$")
4427 (if (<= (org-get-indentation) ind)
4428 (throw 'exit t)))))
4429 (condition-case nil
4430 (org-beginning-of-item)
4431 (error (goto-char pos)
4432 (error "On first item")))))
4434 (defun org-move-item-down ()
4435 "Move the plain list item at point down, i.e. swap with following item.
4436 Subitems (items with larger indentation) are considered part of the item,
4437 so this really moves item trees."
4438 (interactive)
4439 (let (beg end ind ind1 (pos (point)) txt)
4440 (org-beginning-of-item)
4441 (setq beg (point))
4442 (setq ind (org-get-indentation))
4443 (org-end-of-item)
4444 (setq end (point))
4445 (setq ind1 (org-get-indentation))
4446 (if (and (org-at-item-p) (= ind ind1))
4447 (progn
4448 (org-end-of-item)
4449 (setq txt (buffer-substring beg end))
4450 (save-excursion
4451 (delete-region beg end))
4452 (setq pos (point))
4453 (insert txt)
4454 (goto-char pos)
4455 (org-maybe-renumber-ordered-list))
4456 (goto-char pos)
4457 (error "Cannot move this item further down"))))
4459 (defun org-move-item-up (arg)
4460 "Move the plain list item at point up, i.e. swap with previous item.
4461 Subitems (items with larger indentation) are considered part of the item,
4462 so this really moves item trees."
4463 (interactive "p")
4464 (let (beg end ind ind1 (pos (point)) txt)
4465 (org-beginning-of-item)
4466 (setq beg (point))
4467 (setq ind (org-get-indentation))
4468 (org-end-of-item)
4469 (setq end (point))
4470 (goto-char beg)
4471 (catch 'exit
4472 (while t
4473 (beginning-of-line 0)
4474 (if (looking-at "[ \t]*$")
4476 (if (<= (setq ind1 (org-get-indentation)) ind)
4477 (throw 'exit t)))))
4478 (condition-case nil
4479 (org-beginning-of-item)
4480 (error (goto-char beg)
4481 (error "Cannot move this item further up")))
4482 (setq ind1 (org-get-indentation))
4483 (if (and (org-at-item-p) (= ind ind1))
4484 (progn
4485 (setq txt (buffer-substring beg end))
4486 (save-excursion
4487 (delete-region beg end))
4488 (setq pos (point))
4489 (insert txt)
4490 (goto-char pos)
4491 (org-maybe-renumber-ordered-list))
4492 (goto-char pos)
4493 (error "Cannot move this item further up"))))
4495 (defun org-maybe-renumber-ordered-list ()
4496 "Renumber the ordered list at point if setup allows it.
4497 This tests the user option `org-auto-renumber-ordered-lists' before
4498 doing the renumbering."
4499 (and org-auto-renumber-ordered-lists
4500 (org-at-item-p)
4501 (match-beginning 3)
4502 (org-renumber-ordered-list 1)))
4504 (defun org-get-string-indentation (s)
4505 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4506 (let ((n -1) (i 0) (w tab-width) c)
4507 (catch 'exit
4508 (while (< (setq n (1+ n)) (length s))
4509 (setq c (aref s n))
4510 (cond ((= c ?\ ) (setq i (1+ i)))
4511 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4512 (t (throw 'exit t)))))
4515 (defun org-renumber-ordered-list (arg)
4516 "Renumber an ordered plain list.
4517 Cursor needs to be in the first line of an item, the line that starts
4518 with something like \"1.\" or \"2)\"."
4519 (interactive "p")
4520 (unless (and (org-at-item-p)
4521 (match-beginning 3))
4522 (error "This is not an ordered list"))
4523 (let ((line (org-current-line))
4524 (col (current-column))
4525 (ind (org-get-string-indentation
4526 (buffer-substring (point-at-bol) (match-beginning 3))))
4527 ;; (term (substring (match-string 3) -1))
4528 ind1 (n (1- arg)))
4529 ;; find where this list begins
4530 (catch 'exit
4531 (while t
4532 (catch 'next
4533 (beginning-of-line 0)
4534 (if (looking-at "[ \t]*$") (throw 'next t))
4535 (skip-chars-forward " \t") (setq ind1 (current-column))
4536 (if (or (< ind1 ind)
4537 (and (= ind1 ind)
4538 (not (org-at-item-p))))
4539 (throw 'exit t)))))
4540 ;; Walk forward and replace these numbers
4541 (catch 'exit
4542 (while t
4543 (catch 'next
4544 (beginning-of-line 2)
4545 (if (eobp) (throw 'exit nil))
4546 (if (looking-at "[ \t]*$") (throw 'next nil))
4547 (skip-chars-forward " \t") (setq ind1 (current-column))
4548 (if (> ind1 ind) (throw 'next t))
4549 (if (< ind1 ind) (throw 'exit t))
4550 (if (not (org-at-item-p)) (throw 'exit nil))
4551 (if (not (match-beginning 3))
4552 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4553 (delete-region (match-beginning 3) (1- (match-end 3)))
4554 (goto-char (match-beginning 3))
4555 (insert (format "%d" (setq n (1+ n)))))))
4556 (goto-line line)
4557 (move-to-column col)))
4559 (defvar org-last-indent-begin-marker (make-marker))
4560 (defvar org-last-indent-end-marker (make-marker))
4562 (defun org-outdent-item (arg)
4563 "Outdent a local list item."
4564 (interactive "p")
4565 (org-indent-item (- arg)))
4567 (defun org-indent-item (arg)
4568 "Indent a local list item."
4569 (interactive "p")
4570 (unless (org-at-item-p)
4571 (error "Not on an item"))
4572 (save-excursion
4573 (let (beg end ind ind1)
4574 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4575 (setq beg org-last-indent-begin-marker
4576 end org-last-indent-end-marker)
4577 (org-beginning-of-item)
4578 (setq beg (move-marker org-last-indent-begin-marker (point)))
4579 (org-end-of-item)
4580 (setq end (move-marker org-last-indent-end-marker (point))))
4581 (goto-char beg)
4582 (skip-chars-forward " \t") (setq ind (current-column))
4583 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4584 (while (< (point) end)
4585 (beginning-of-line 1)
4586 (skip-chars-forward " \t") (setq ind1 (current-column))
4587 (delete-region (point-at-bol) (point))
4588 (indent-to-column (+ ind1 arg))
4589 (beginning-of-line 2)))))
4591 ;;; Archiving
4593 (defun org-archive-subtree (&optional find-done)
4594 "Move the current subtree to the archive.
4595 The archive can be a certain top-level heading in the current file, or in
4596 a different file. The tree will be moved to that location, the subtree
4597 heading be marked DONE, and the current time will be added.
4599 When called with prefix argument FIND-DONE, find whole trees without any
4600 open TODO items and archive them (after getting confirmation from the user).
4601 If the cursor is not at a headline when this comand is called, try all level
4602 1 trees. If the cursor is on a headline, only try the direct children of
4603 this heading. "
4604 (interactive "P")
4605 (if find-done
4606 (org-archive-all-done)
4607 ;; Save all relevant TODO keyword-relatex variables
4609 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4610 (tr-org-todo-keywords org-todo-keywords)
4611 (tr-org-todo-interpretation org-todo-interpretation)
4612 (tr-org-done-string org-done-string)
4613 (tr-org-todo-regexp org-todo-regexp)
4614 (tr-org-todo-line-regexp org-todo-line-regexp)
4615 (this-buffer (current-buffer))
4616 file heading buffer level newfile-p)
4617 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4618 (progn
4619 (setq file (format (match-string 1 org-archive-location)
4620 (file-name-nondirectory buffer-file-name))
4621 heading (match-string 2 org-archive-location)))
4622 (error "Invalid `org-archive-location'"))
4623 (if (> (length file) 0)
4624 (setq newfile-p (not (file-exists-p file))
4625 buffer (find-file-noselect file))
4626 (setq buffer (current-buffer)))
4627 (unless buffer
4628 (error "Cannot access file \"%s\"" file))
4629 (if (and (> (length heading) 0)
4630 (string-match "^\\*+" heading))
4631 (setq level (match-end 0))
4632 (setq heading nil level 0))
4633 (save-excursion
4634 ;; We first only copy, in case something goes wrong
4635 ;; we need to protect this-command, to avoid kill-region sets it,
4636 ;; which would lead to duplication of subtrees
4637 (let (this-command) (org-copy-subtree))
4638 (set-buffer buffer)
4639 ;; Enforce org-mode for the archive buffer
4640 (if (not (org-mode-p))
4641 ;; Force the mode for future visits.
4642 (let ((org-insert-mode-line-in-empty-file t))
4643 (call-interactively 'org-mode)))
4644 (when newfile-p
4645 (goto-char (point-max))
4646 (insert (format "\nArchived entries from file %s\n\n"
4647 (buffer-file-name this-buffer))))
4648 ;; Force the TODO keywords of the original buffer
4649 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4650 (org-todo-keywords tr-org-todo-keywords)
4651 (org-todo-interpretation tr-org-todo-interpretation)
4652 (org-done-string tr-org-done-string)
4653 (org-todo-regexp tr-org-todo-regexp)
4654 (org-todo-line-regexp tr-org-todo-line-regexp))
4655 (goto-char (point-min))
4656 (if heading
4657 (progn
4658 (if (re-search-forward
4659 (concat "\\(^\\|\r\\)"
4660 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4661 nil t)
4662 (goto-char (match-end 0))
4663 ;; Heading not found, just insert it at the end
4664 (goto-char (point-max))
4665 (or (bolp) (insert "\n"))
4666 (insert "\n" heading "\n")
4667 (end-of-line 0))
4668 ;; Make the subtree visible
4669 (show-subtree)
4670 (org-end-of-subtree t)
4671 (skip-chars-backward " \t\r\n]")
4672 (and (looking-at "[ \t\r\n]*")
4673 (replace-match "\n\n")))
4674 ;; No specific heading, just go to end of file.
4675 (goto-char (point-max)) (insert "\n"))
4676 ;; Paste
4677 (org-paste-subtree (1+ level))
4678 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4679 (if org-archive-mark-done
4680 (org-todo (length org-todo-keywords)))
4681 ;; Move cursor to right after the TODO keyword
4682 (when org-archive-stamp-time
4683 (beginning-of-line 1)
4684 (looking-at org-todo-line-regexp)
4685 (goto-char (or (match-end 2) (match-beginning 3)))
4686 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4687 (org-current-time))
4688 ")"))
4689 ;; Save the buffer, if it is not the same buffer.
4690 (if (not (eq this-buffer buffer)) (save-buffer))))
4691 ;; Here we are back in the original buffer. Everything seems to have
4692 ;; worked. So now cut the tree and finish up.
4693 (let (this-command) (org-cut-subtree))
4694 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4695 (message "Subtree archived %s"
4696 (if (eq this-buffer buffer)
4697 (concat "under heading: " heading)
4698 (concat "in file: " (abbreviate-file-name file)))))))
4700 (defun org-archive-all-done (&optional tag)
4701 "Archive sublevels of the current tree without open TODO items.
4702 If the cursor is not on a headline, try all level 1 trees. If
4703 it is on a headline, try all direct children.
4704 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4705 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4706 (rea (concat ".*:" org-archive-tag ":"))
4707 (begm (make-marker))
4708 (endm (make-marker))
4709 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4710 "Move subtree to archive (no open TODO items)? "))
4711 beg end (cntarch 0))
4712 (if (org-on-heading-p)
4713 (progn
4714 (setq re1 (concat "^" (regexp-quote
4715 (make-string
4716 (1+ (- (match-end 0) (match-beginning 0)))
4717 ?*))
4718 " "))
4719 (move-marker begm (point))
4720 (move-marker endm (org-end-of-subtree)))
4721 (setq re1 "^* ")
4722 (move-marker begm (point-min))
4723 (move-marker endm (point-max)))
4724 (save-excursion
4725 (goto-char begm)
4726 (while (re-search-forward re1 endm t)
4727 (setq beg (match-beginning 0)
4728 end (save-excursion (org-end-of-subtree t) (point)))
4729 (goto-char beg)
4730 (if (re-search-forward re end t)
4731 (goto-char end)
4732 (goto-char beg)
4733 (if (and (or (not tag) (not (looking-at rea)))
4734 (y-or-n-p question))
4735 (progn
4736 (if tag
4737 (org-toggle-tag org-archive-tag 'on)
4738 (org-archive-subtree))
4739 (setq cntarch (1+ cntarch)))
4740 (goto-char end)))))
4741 (message "%d trees archived" cntarch)))
4743 (defun org-cycle-hide-archived-subtrees (state)
4744 "Re-hide all archived subtrees after a visibility state change."
4745 (when (and (not org-cycle-open-archived-trees)
4746 (not (memq state '(overview folded))))
4747 (save-excursion
4748 (let* ((globalp (memq state '(contents all)))
4749 (beg (if globalp (point-min) (point)))
4750 (end (if globalp (point-max) (org-end-of-subtree))))
4751 (org-hide-archived-subtrees beg end)
4752 (goto-char beg)
4753 (if (looking-at (concat ".*:" org-archive-tag ":"))
4754 (message (substitute-command-keys
4755 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4757 (defun org-force-cycle-archived ()
4758 "Cycle subtree even if it is archived."
4759 (interactive)
4760 (setq this-command 'org-cycle)
4761 (let ((org-cycle-open-archived-trees t))
4762 (call-interactively 'org-cycle)))
4764 (defun org-hide-archived-subtrees (beg end)
4765 "Re-hide all archived subtrees after a visibility state change."
4766 (save-excursion
4767 (let* ((re (concat ":" org-archive-tag ":")))
4768 (goto-char beg)
4769 (while (re-search-forward re end t)
4770 (and (org-on-heading-p) (hide-subtree))
4771 (org-end-of-subtree)))))
4773 (defun org-toggle-tag (tag &optional onoff)
4774 "Toggle the tag TAG for the current line.
4775 If ONOFF is `on' or `off', don't toggle but set to this state."
4776 (unless (org-on-heading-p) (error "Not on headling"))
4777 (let (res current)
4778 (save-excursion
4779 (beginning-of-line)
4780 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4781 (point-at-eol) t)
4782 (progn
4783 (setq current (match-string 1))
4784 (replace-match ""))
4785 (setq current ""))
4786 (setq current (nreverse (org-split-string current ":")))
4787 (cond
4788 ((eq onoff 'on)
4789 (setq res t)
4790 (or (member tag current) (push tag current)))
4791 ((eq onoff 'off)
4792 (or (not (member tag current)) (setq current (delete tag current))))
4793 (t (if (member tag current)
4794 (setq current (delete tag current))
4795 (setq res t)
4796 (push tag current))))
4797 (end-of-line 1)
4798 (when current
4799 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4800 (org-set-tags nil t))
4801 res))
4803 (defun org-toggle-archive-tag (&optional arg)
4804 "Toggle the archive tag for the current headline.
4805 With prefix ARG, check all children of current headline and offer tagging
4806 the children that do not contain any open TODO items."
4807 (interactive "P")
4808 (if arg
4809 (org-archive-all-done 'tag)
4810 (let (set)
4811 (save-excursion
4812 (org-back-to-heading t)
4813 (setq set (org-toggle-tag org-archive-tag))
4814 (when set (hide-subtree)))
4815 (and set (beginning-of-line 1))
4816 (message "Subtree %s" (if set "archived" "unarchived")))))
4818 (defvar org-agenda-multi nil) ; dynammically scoped
4819 (defvar org-agenda-buffer-name "*Org Agenda*")
4820 (defun org-prepare-agenda ()
4821 (if org-agenda-multi
4822 (progn
4823 (setq buffer-read-only nil)
4824 (goto-char (point-max))
4825 (unless (= (point) 1)
4826 (insert "\n" (make-string (window-width) ?=) "\n"))
4827 (narrow-to-region (point) (point-max)))
4828 (org-agenda-maybe-reset-markers 'force)
4829 (org-prepare-agenda-buffers (org-agenda-files))
4830 (unless (equal (current-buffer) (get-buffer org-agenda-buffer-name))
4831 (delete-other-windows)
4832 (switch-to-buffer-other-window
4833 (get-buffer-create org-agenda-buffer-name)))
4834 (setq buffer-read-only nil)
4835 (erase-buffer)
4836 (org-agenda-mode))
4837 (setq buffer-read-only nil)) ;;; FIXME: do we need all these occasions????
4839 (defun org-prepare-agenda-buffers (files)
4840 "Create buffers for all agenda files, protect archived trees and comments."
4841 (interactive)
4842 (let ((pa '(:org-archived t))
4843 (pc '(:org-comment t))
4844 (pall '(:org-archived t :org-comment t))
4845 (rea (concat ":" org-archive-tag ":"))
4846 bmp file re)
4847 (save-excursion
4848 (while (setq file (pop files))
4849 (org-check-agenda-file file)
4850 (set-buffer (org-get-agenda-file-buffer file))
4851 (widen)
4852 (setq bmp (buffer-modified-p))
4853 (save-excursion
4854 (remove-text-properties (point-min) (point-max) pall)
4855 (when org-agenda-skip-archived-trees
4856 (goto-char (point-min))
4857 (while (re-search-forward rea nil t)
4858 (if (org-on-heading-p)
4859 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4860 (goto-char (point-min))
4861 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4862 (while (re-search-forward re nil t)
4863 (add-text-properties
4864 (match-beginning 0) (org-end-of-subtree t) pc)))
4865 (set-buffer-modified-p bmp)))))
4867 (defun org-agenda-skip ()
4868 "Throw to `:skip' in places that should be skipped."
4869 (let ((p (point-at-bol)))
4870 (and org-agenda-skip-archived-trees
4871 (get-text-property p :org-archived)
4872 (org-end-of-subtree)
4873 (throw :skip t))
4874 (and (get-text-property p :org-comment)
4875 (org-end-of-subtree)
4876 (throw :skip t))
4877 (if (equal (char-after p) ?#) (throw :skip t))))
4879 (defun org-agenda-toggle-archive-tag ()
4880 "Toggle the archive tag for the current entry."
4881 (interactive)
4882 (org-agenda-check-no-diary)
4883 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4884 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4885 (org-agenda-error)))
4886 (buffer (marker-buffer hdmarker))
4887 (pos (marker-position hdmarker))
4888 (buffer-read-only nil)
4889 newhead)
4890 (with-current-buffer buffer
4891 (widen)
4892 (goto-char pos)
4893 (org-show-hidden-entry)
4894 (save-excursion
4895 (and (outline-next-heading)
4896 (org-flag-heading nil))) ; show the next heading
4897 (call-interactively 'org-toggle-archive-tag)
4898 (end-of-line 1)
4899 (setq newhead (org-get-heading)))
4900 (org-agenda-change-all-lines newhead hdmarker)
4901 (beginning-of-line 1)))
4903 ;;; Dynamic blocks
4905 (defun org-find-dblock (name)
4906 "Find the first dynamic block with name NAME in the buffer.
4907 If not found, stay at current position and return nil."
4908 (let (pos)
4909 (save-excursion
4910 (goto-char (point-min))
4911 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4912 nil t)
4913 (match-beginning 0))))
4914 (if pos (goto-char pos))
4915 pos))
4917 (defconst org-dblock-start-re
4918 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
4919 "Matches the startline of a dynamic block, with parameters.")
4921 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4922 "Matches the end of a dyhamic block.")
4924 (defun org-create-dblock (plist)
4925 "Create a dynamic block section, with parameters taken from PLIST.
4926 PLIST must containe a :name entry which is used as name of the block."
4927 (unless (bolp) (newline))
4928 (let ((name (plist-get plist :name)))
4929 (insert "#+BEGIN: " name)
4930 (while plist
4931 (if (eq (car plist) :name)
4932 (setq plist (cddr plist))
4933 (insert " " (prin1-to-string (pop plist)))))
4934 (insert "\n\n#+END:\n")
4935 (beginning-of-line -2)))
4937 (defun org-prepare-dblock ()
4938 "Prepare dynamic block for refresh.
4939 This empties the block, puts the cursor at the insert position and returns
4940 the property list including an extra property :name with the block name."
4941 (unless (looking-at org-dblock-start-re)
4942 (error "Not at a dynamic block"))
4943 (let* ((begdel (1+ (match-end 0)))
4944 (name (match-string 1))
4945 (params (append (list :name name)
4946 (read (concat "(" (match-string 3) ")")))))
4947 (unless (re-search-forward org-dblock-end-re nil t)
4948 (error "Dynamic block not terminated"))
4949 (delete-region begdel (match-beginning 0))
4950 (goto-char begdel)
4951 (open-line 1)
4952 params))
4954 (defun org-map-dblocks (&optional command)
4955 "Apply COMMAND to all dynamic blocks in the current buffer.
4956 If COMMAND is not given, use `org-update-dblock'."
4957 (let ((cmd (or command 'org-update-dblock))
4958 pos)
4959 (save-excursion
4960 (goto-char (point-min))
4961 (while (re-search-forward org-dblock-start-re nil t)
4962 (goto-char (setq pos (match-beginning 0)))
4963 (condition-case nil
4964 (funcall cmd)
4965 (error (message "Error during update of dynamic block")))
4966 (goto-char pos)
4967 (unless (re-search-forward org-dblock-end-re nil t)
4968 (error "Dynamic block not terminated"))))))
4970 (defun org-dblock-update (&optional arg)
4971 "User command for updating dynamic blocks.
4972 Update the dynamic block at point. With prefix ARG, update all dynamic
4973 blocks in the buffer."
4974 (interactive "P")
4975 (if arg
4976 (org-update-all-dblocks)
4977 (or (looking-at org-dblock-start-re)
4978 (org-beginning-of-dblock))
4979 (org-update-dblock)))
4981 (defun org-update-dblock ()
4982 "Update the dynamic block at point
4983 This means to empty the block, parse for parameters and then call
4984 the correct writing function."
4985 (let* ((pos (point))
4986 (params (org-prepare-dblock))
4987 (name (plist-get params :name))
4988 (cmd (intern (concat "org-dblock-write:" name))))
4989 (funcall cmd params)
4990 (goto-char pos)))
4992 (defun org-beginning-of-dblock ()
4993 "Find the beginning of the dynamic block at point.
4994 Error if there is no scuh block at point."
4995 (let ((pos (point))
4996 beg)
4997 (end-of-line 1)
4998 (if (and (re-search-backward org-dblock-start-re nil t)
4999 (setq beg (match-beginning 0))
5000 (re-search-forward org-dblock-end-re nil t)
5001 (> (match-end 0) pos))
5002 (goto-char beg)
5003 (goto-char pos)
5004 (error "Not in a dynamic block"))))
5006 (defun org-update-all-dblocks ()
5007 "Update all dynamic blocks in the buffer.
5008 This function can be used in a hook."
5009 (when (org-mode-p)
5010 (org-map-dblocks 'org-update-dblock)))
5013 ;;; Completion
5015 (defun org-complete (&optional arg)
5016 "Perform completion on word at point.
5017 At the beginning of a headline, this completes TODO keywords as given in
5018 `org-todo-keywords'.
5019 If the current word is preceded by a backslash, completes the TeX symbols
5020 that are supported for HTML support.
5021 If the current word is preceded by \"#+\", completes special words for
5022 setting file options.
5023 In the line after \"#+STARTUP:, complete valid keywords.\"
5024 At all other locations, this simply calls `ispell-complete-word'."
5025 (interactive "P")
5026 (catch 'exit
5027 (let* ((end (point))
5028 (beg1 (save-excursion
5029 ;FIXME??? (if (equal (char-before (point)) ?\ ) (backward-char 1))
5030 (skip-chars-backward "a-zA-Z_@0-9")
5031 (point)))
5032 (beg (save-excursion
5033 ;FIXME??? (if (equal (char-before (point)) ?\ ) (backward-char 1))
5034 (skip-chars-backward "a-zA-Z0-9_:$")
5035 (point)))
5036 (confirm (lambda (x) (stringp (car x))))
5037 (camel (equal (char-before beg) ?*))
5038 (tag (equal (char-before beg1) ?:))
5039 (texp (equal (char-before beg) ?\\))
5040 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
5041 beg)
5042 "#+"))
5043 (startup (string-match "^#\\+STARTUP:.*"
5044 (buffer-substring (point-at-bol) (point))))
5045 (completion-ignore-case opt)
5046 (type nil)
5047 (tbl nil)
5048 (table (cond
5049 (opt
5050 (setq type :opt)
5051 (mapcar (lambda (x)
5052 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
5053 (cons (match-string 2 x) (match-string 1 x)))
5054 (org-split-string (org-get-current-options) "\n")))
5055 (startup
5056 (setq type :startup)
5057 org-startup-options)
5058 (texp
5059 (setq type :tex)
5060 org-html-entities)
5061 ((string-match "\\`\\*+[ \t]*\\'"
5062 (buffer-substring (point-at-bol) beg))
5063 (setq type :todo)
5064 (mapcar 'list org-todo-keywords))
5065 (camel
5066 (setq type :camel)
5067 (save-excursion
5068 (goto-char (point-min))
5069 (while (re-search-forward org-todo-line-regexp nil t)
5070 (push (list
5071 (if org-file-link-context-use-camel-case
5072 (org-make-org-heading-camel (match-string 3) t)
5073 (org-make-org-heading-search-string
5074 (match-string 3) t)))
5075 tbl)))
5076 tbl)
5077 (tag (setq type :tag beg beg1)
5078 (or org-tag-alist (org-get-buffer-tags)))
5079 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
5080 (pattern (buffer-substring-no-properties beg end))
5081 (completion (try-completion pattern table confirm)))
5082 (cond ((eq completion t)
5083 (if (equal type :opt)
5084 (insert (substring (cdr (assoc (upcase pattern) table))
5085 (length pattern)))))
5086 ((null completion)
5087 (message "Can't find completion for \"%s\"" pattern)
5088 (ding))
5089 ((not (string= pattern completion))
5090 (delete-region beg end)
5091 (if (string-match " +$" completion)
5092 (setq completion (replace-match "" t t completion)))
5093 (insert completion)
5094 (if (get-buffer-window "*Completions*")
5095 (delete-window (get-buffer-window "*Completions*")))
5096 (if (assoc completion table)
5097 (if (eq type :todo) (insert " ")
5098 (if (eq type :tag) (insert ":"))))
5099 (if (and (equal type :opt) (assoc completion table))
5100 (message "%s" (substitute-command-keys
5101 "Press \\[org-complete] again to insert example settings"))))
5103 (message "Making completion list...")
5104 (let ((list (sort (all-completions pattern table confirm)
5105 'string<)))
5106 (with-output-to-temp-buffer "*Completions*"
5107 (condition-case nil
5108 ;; Protection needed for XEmacs and emacs 21
5109 (display-completion-list list pattern)
5110 (error (display-completion-list list)))))
5111 (message "Making completion list...%s" "done"))))))
5113 ;;; Comments, TODO and DEADLINE
5115 (defun org-toggle-comment ()
5116 "Change the COMMENT state of an entry."
5117 (interactive)
5118 (save-excursion
5119 (org-back-to-heading)
5120 (if (looking-at (concat outline-regexp
5121 "\\( +\\<" org-comment-string "\\>\\)"))
5122 (replace-match "" t t nil 1)
5123 (if (looking-at outline-regexp)
5124 (progn
5125 (goto-char (match-end 0))
5126 (insert " " org-comment-string))))))
5128 (defvar org-last-todo-state-is-todo nil
5129 "This is non-nil when the last TODO state change led to a TODO state.
5130 If the last change removed the TODO tag or switched to DONE, then
5131 this is nil.")
5133 (defun org-todo (&optional arg)
5134 "Change the TODO state of an item.
5135 The state of an item is given by a keyword at the start of the heading,
5136 like
5137 *** TODO Write paper
5138 *** DONE Call mom
5140 The different keywords are specified in the variable `org-todo-keywords'.
5141 By default the available states are \"TODO\" and \"DONE\".
5142 So for this example: when the item starts with TODO, it is changed to DONE.
5143 When it starts with DONE, the DONE is removed. And when neither TODO nor
5144 DONE are present, add TODO at the beginning of the heading.
5146 With prefix arg, use completion to determine the new state. With numeric
5147 prefix arg, switch to that state."
5148 (interactive "P")
5149 (save-excursion
5150 (org-back-to-heading)
5151 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5152 (or (looking-at (concat " +" org-todo-regexp " *"))
5153 (looking-at " *"))
5154 (let* ((this (match-string 1))
5155 (completion-ignore-case t)
5156 (member (member this org-todo-keywords))
5157 (tail (cdr member))
5158 (state (cond
5159 ((equal arg '(4))
5160 ;; Read a state with completion
5161 (completing-read "State: " (mapcar (lambda(x) (list x))
5162 org-todo-keywords)
5163 nil t))
5164 ((eq arg 'right)
5165 (if this
5166 (if tail (car tail) nil)
5167 (car org-todo-keywords)))
5168 ((eq arg 'left)
5169 (if (equal member org-todo-keywords)
5171 (if this
5172 (nth (- (length org-todo-keywords) (length tail) 2)
5173 org-todo-keywords)
5174 org-done-string)))
5175 (arg
5176 ;; user requests a specific state
5177 (nth (1- (prefix-numeric-value arg))
5178 org-todo-keywords))
5179 ((null member) (car org-todo-keywords))
5180 ((null tail) nil) ;; -> first entry
5181 ((eq org-todo-interpretation 'sequence)
5182 (car tail))
5183 ((memq org-todo-interpretation '(type priority))
5184 (if (eq this-command last-command)
5185 (car tail)
5186 (if (> (length tail) 0) org-done-string nil)))
5187 (t nil)))
5188 (next (if state (concat " " state " ") " ")))
5189 (replace-match next t t)
5190 (setq org-last-todo-state-is-todo
5191 (not (equal state org-done-string)))
5192 (when org-log-done
5193 (if (equal state org-done-string)
5194 (org-add-planning-info 'closed (current-time) 'scheduled)
5195 (if (not this)
5196 (org-add-planning-info nil nil 'closed))))
5197 ;; Fixup tag positioning
5198 (and org-auto-align-tags (org-set-tags nil t))
5199 (run-hooks 'org-after-todo-state-change-hook)))
5200 ;; Fixup cursor location if close to the keyword
5201 (if (and (outline-on-heading-p)
5202 (not (bolp))
5203 (save-excursion (beginning-of-line 1)
5204 (looking-at org-todo-line-regexp))
5205 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5206 (progn
5207 (goto-char (or (match-end 2) (match-end 1)))
5208 (just-one-space))))
5210 (defun org-log-done (&optional undone)
5211 "Add a time stamp logging that a TODO entry has been closed.
5212 When UNDONE is non-nil, remove such a time stamp again."
5213 (interactive)
5214 (let (beg end col)
5215 (save-excursion
5216 (org-back-to-heading t)
5217 (setq beg (point))
5218 (looking-at (concat outline-regexp " *"))
5219 (goto-char (match-end 0))
5220 (setq col (current-column))
5221 (outline-next-heading)
5222 (setq end (point))
5223 (goto-char beg)
5224 (when (re-search-forward (concat
5225 "[\r\n]\\([ \t]*"
5226 (regexp-quote org-closed-string)
5227 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5228 (delete-region (match-beginning 1) (match-end 1)))
5229 (unless undone
5230 (org-back-to-heading t)
5231 (skip-chars-forward "^\n\r")
5232 (goto-char (min (1+ (point)) (point-max)))
5233 (when (not (member (char-before) '(?\r ?\n)))
5234 (insert "\n"))
5235 (indent-to col)
5236 (insert org-closed-string " "
5237 (format-time-string
5238 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5239 (org-current-time))
5240 "\n")))))
5242 (defun org-show-todo-tree (arg)
5243 "Make a compact tree which shows all headlines marked with TODO.
5244 The tree will show the lines where the regexp matches, and all higher
5245 headlines above the match.
5246 With \\[universal-argument] prefix, also show the DONE entries.
5247 With a numeric prefix N, construct a sparse tree for the Nth element
5248 of `org-todo-keywords'."
5249 (interactive "P")
5250 (let ((case-fold-search nil)
5251 (kwd-re
5252 (cond ((null arg) org-not-done-regexp)
5253 ((equal arg '(4)) org-todo-regexp)
5254 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5255 (regexp-quote (nth (1- (prefix-numeric-value arg))
5256 org-todo-keywords)))
5257 (t (error "Invalid prefix argument: %s" arg)))))
5258 (message "%d TODO entries found"
5259 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5261 (defun org-deadline ()
5262 "Insert the DEADLINE: string to make a deadline.
5263 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5264 to modify it to the correct date."
5265 (interactive)
5266 (org-add-planning-info 'deadline nil 'closed))
5268 (defun org-schedule ()
5269 "Insert the SCHEDULED: string to schedule a TODO item.
5270 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5271 to modify it to the correct date."
5272 (interactive)
5273 (org-add-planning-info 'scheduled nil 'closed))
5275 (defun org-add-planning-info (what &optional time &rest remove)
5276 "Insert new timestamp with keyword in the line directly after the headline.
5277 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5278 If non is given, the user is prompted for a date.
5279 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5280 be removed."
5281 (interactive)
5282 (when what (setq time (or time (org-read-date nil 'to-time))))
5283 (when (and org-insert-labeled-timestamps-at-point
5284 (member what '(scheduled deadline)))
5285 (insert
5286 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5288 (format-time-string (car org-time-stamp-formats) time))
5289 (setq what nil))
5290 (save-excursion
5291 (let (col list elt (buffer-invisibility-spec nil) ts)
5292 (org-back-to-heading t)
5293 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5294 (goto-char (match-end 1))
5295 (setq col (current-column))
5296 (goto-char (1+ (match-end 0)))
5297 (if (and (not (looking-at outline-regexp))
5298 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5299 "[^\r\n]*"))
5300 (not (equal (match-string 1) org-clock-string)))
5301 (narrow-to-region (match-beginning 0) (match-end 0))
5302 (insert "\n")
5303 (backward-char 1)
5304 (narrow-to-region (point) (point))
5305 (indent-to-column col))
5306 ;; Check if we have to remove something.
5307 (setq list (cons what remove))
5308 (while list
5309 (setq elt (pop list))
5310 (goto-char (point-min))
5311 (when (or (and (eq elt 'scheduled)
5312 (re-search-forward org-scheduled-time-regexp nil t))
5313 (and (eq elt 'deadline)
5314 (re-search-forward org-deadline-time-regexp nil t))
5315 (and (eq elt 'closed)
5316 (re-search-forward org-closed-time-regexp nil t)))
5317 (replace-match "")
5318 (if (looking-at " +") (replace-match ""))))
5319 (goto-char (point-max))
5320 (when what
5321 (insert
5322 (if (not (equal (char-before) ?\ )) " " "")
5323 (cond ((eq what 'scheduled) org-scheduled-string)
5324 ((eq what 'deadline) org-deadline-string)
5325 ((eq what 'closed) org-closed-string))
5326 " ")
5327 (insert
5328 (setq ts
5329 (format-time-string
5330 (if (eq what 'closed)
5331 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5332 (car org-time-stamp-formats))
5333 time))))
5334 (goto-char (point-min))
5335 (widen)
5336 (if (looking-at "[ \t]+\r?\n")
5337 (replace-match ""))
5338 ts)))
5340 (defun org-occur (regexp &optional callback)
5341 "Make a compact tree which shows all matches of REGEXP.
5342 The tree will show the lines where the regexp matches, and all higher
5343 headlines above the match. It will also show the heading after the match,
5344 to make sure editing the matching entry is easy.
5345 If CALLBACK is non-nil, it is a function which is called to confirm
5346 that the match should indeed be shown."
5347 (interactive "sRegexp: ")
5348 (org-remove-occur-highlights nil nil t)
5349 (let ((cnt 0))
5350 (save-excursion
5351 (goto-char (point-min))
5352 (org-overview)
5353 (while (re-search-forward regexp nil t)
5354 (when (or (not callback)
5355 (save-match-data (funcall callback)))
5356 (setq cnt (1+ cnt))
5357 (org-highlight-new-match (match-beginning 0) (match-end 0))
5358 (org-show-hierarchy-above))))
5359 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5360 nil 'local)
5361 (unless org-sparse-tree-open-archived-trees
5362 (org-hide-archived-subtrees (point-min) (point-max)))
5363 (run-hooks 'org-occur-hook)
5364 (if (interactive-p)
5365 (message "%d match(es) for regexp %s" cnt regexp))
5366 cnt))
5368 (defun org-show-hierarchy-above ()
5369 "Make sure point and the headings hierarchy above is visible."
5370 (catch 'exit
5371 (if (org-on-heading-p t)
5372 (org-flag-heading nil) ; only show the heading
5373 (and (or (org-invisible-p) (org-invisible-p2))
5374 (org-show-hidden-entry))) ; show entire entry
5375 (save-excursion
5376 (and org-show-following-heading
5377 (outline-next-heading)
5378 (org-flag-heading nil))) ; show the next heading
5379 (when org-show-hierarchy-above
5380 (save-excursion ; show all higher headings
5381 (while (and (condition-case nil
5382 (progn (org-up-heading-all 1) t)
5383 (error nil))
5384 (not (bobp)))
5385 (org-flag-heading nil))))))
5387 ;; Overlay compatibility functions
5388 (defun org-make-overlay (beg end &optional buffer)
5389 (if (featurep 'xemacs)
5390 (make-extent beg end buffer)
5391 (make-overlay beg end buffer)))
5392 (defun org-delete-overlay (ovl)
5393 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5394 (defun org-detatch-overlay (ovl)
5395 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5396 (defun org-move-overlay (ovl beg end &optional buffer)
5397 (if (featurep 'xemacs)
5398 (set-extent-endpoints ovl beg end buffer)
5399 (move-overlay ovl beg end buffer)))
5400 (defun org-overlay-put (ovl prop value)
5401 (if (featurep 'xemacs)
5402 (set-extent-property ovl prop value)
5403 (overlay-put ovl prop value)))
5404 (defun org-overlays-at (pos)
5405 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5406 (defun org-overlay-start (o)
5407 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5408 (defun org-overlay-end (o)
5409 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5411 (defvar org-occur-highlights nil)
5412 (make-variable-buffer-local 'org-occur-highlights)
5413 (defun org-highlight-new-match (beg end)
5414 "Highlight from BEG to END and mark the highlight is an occur headline."
5415 (let ((ov (org-make-overlay beg end)))
5416 (org-overlay-put ov 'face 'secondary-selection)
5417 (push ov org-occur-highlights)))
5419 (defvar org-inhibit-highlight-removal nil)
5420 (defun org-remove-occur-highlights (&optional beg end noremove)
5421 "Remove the occur highlights from the buffer.
5422 BEG and END are ignored. If NOREMOVE is nil, remove this function
5423 from the `before-change-functions' in the current buffer."
5424 (interactive)
5425 (unless org-inhibit-highlight-removal
5426 (mapc 'org-delete-overlay org-occur-highlights)
5427 (setq org-occur-highlights nil)
5428 (unless noremove
5429 (remove-hook 'before-change-functions
5430 'org-remove-occur-highlights 'local))))
5432 ;;; Priorities
5434 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5435 "Regular expression matching the priority indicator.")
5437 (defvar org-remove-priority-next-time nil)
5439 (defun org-priority-up ()
5440 "Increase the priority of the current item."
5441 (interactive)
5442 (org-priority 'up))
5444 (defun org-priority-down ()
5445 "Decrease the priority of the current item."
5446 (interactive)
5447 (org-priority 'down))
5449 (defun org-priority (&optional action)
5450 "Change the priority of an item by ARG.
5451 ACTION can be set, up, or down."
5452 (interactive)
5453 (setq action (or action 'set))
5454 (let (current new news have remove)
5455 (save-excursion
5456 (org-back-to-heading)
5457 (if (looking-at org-priority-regexp)
5458 (setq current (string-to-char (match-string 2))
5459 have t)
5460 (setq current org-default-priority))
5461 (cond
5462 ((eq action 'set)
5463 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5464 (setq new (read-char-exclusive))
5465 (cond ((equal new ?\ ) (setq remove t))
5466 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5467 (error "Priority must be between `%c' and `%c'"
5468 ?A org-lowest-priority))))
5469 ((eq action 'up)
5470 (setq new (1- current)))
5471 ((eq action 'down)
5472 (setq new (1+ current)))
5473 (t (error "Invalid action")))
5474 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5475 (setq news (format "%c" new))
5476 (if have
5477 (if remove
5478 (replace-match "" t t nil 1)
5479 (replace-match news t t nil 2))
5480 (if remove
5481 (error "No priority cookie found in line")
5482 (looking-at org-todo-line-regexp)
5483 (if (match-end 2)
5484 (progn
5485 (goto-char (match-end 2))
5486 (insert " [#" news "]"))
5487 (goto-char (match-beginning 3))
5488 (insert "[#" news "] ")))))
5489 (if remove
5490 (message "Priority removed")
5491 (message "Priority of current item set to %s" news))))
5494 (defun org-get-priority (s)
5495 "Find priority cookie and return priority."
5496 (save-match-data
5497 (if (not (string-match org-priority-regexp s))
5498 (* 1000 (- org-lowest-priority org-default-priority))
5499 (* 1000 (- org-lowest-priority
5500 (string-to-char (match-string 2 s)))))))
5502 ;;; Timestamps
5504 (defvar org-last-changed-timestamp nil)
5506 (defun org-time-stamp (arg)
5507 "Prompt for a date/time and insert a time stamp.
5508 If the user specifies a time like HH:MM, or if this command is called
5509 with a prefix argument, the time stamp will contain date and time.
5510 Otherwise, only the date will be included. All parts of a date not
5511 specified by the user will be filled in from the current date/time.
5512 So if you press just return without typing anything, the time stamp
5513 will represent the current date/time. If there is already a timestamp
5514 at the cursor, it will be modified."
5515 (interactive "P")
5516 (let ((fmt (if arg (cdr org-time-stamp-formats)
5517 (car org-time-stamp-formats)))
5518 (org-time-was-given nil)
5519 time)
5520 (cond
5521 ((and (org-at-timestamp-p)
5522 (eq last-command 'org-time-stamp)
5523 (eq this-command 'org-time-stamp))
5524 (insert "--")
5525 (setq time (let ((this-command this-command))
5526 (org-read-date arg 'totime)))
5527 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5528 (insert (format-time-string fmt time)))
5529 ((org-at-timestamp-p)
5530 (setq time (let ((this-command this-command))
5531 (org-read-date arg 'totime)))
5532 (and (org-at-timestamp-p) (replace-match
5533 (setq org-last-changed-timestamp
5534 (format-time-string fmt time))
5535 t t))
5536 (message "Timestamp updated"))
5538 (setq time (let ((this-command this-command))
5539 (org-read-date arg 'totime)))
5540 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5541 (insert (format-time-string fmt time))))))
5543 (defun org-time-stamp-inactive (&optional arg)
5544 "Insert an inactive time stamp.
5545 An inactive time stamp is enclosed in square brackets instead of angle
5546 brackets. It is inactive in the sense that it does not trigger agenda entries,
5547 does not link to the calendar and cannot be changed with the S-cursor keys.
5548 So these are more for recording a certain time/date."
5549 (interactive "P")
5550 (let ((fmt (if arg (cdr org-time-stamp-formats)
5551 (car org-time-stamp-formats)))
5552 (org-time-was-given nil)
5553 time)
5554 (setq time (org-read-date arg 'totime))
5555 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5556 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5557 (insert (format-time-string fmt time))))
5559 (defvar org-date-ovl (org-make-overlay 1 1))
5560 (org-overlay-put org-date-ovl 'face 'org-warning)
5561 (org-detatch-overlay org-date-ovl)
5563 (defun org-read-date (&optional with-time to-time)
5564 "Read a date and make things smooth for the user.
5565 The prompt will suggest to enter an ISO date, but you can also enter anything
5566 which will at least partially be understood by `parse-time-string'.
5567 Unrecognized parts of the date will default to the current day, month, year,
5568 hour and minute. For example,
5569 3-2-5 --> 2003-02-05
5570 feb 15 --> currentyear-02-15
5571 sep 12 9 --> 2009-09-12
5572 12:45 --> today 12:45
5573 22 sept 0:34 --> currentyear-09-22 0:34
5574 12 --> currentyear-currentmonth-12
5575 Fri --> nearest Friday (today or later)
5576 etc.
5577 The function understands only English month and weekday abbreviations,
5578 but this can be configured with the variables `parse-time-months' and
5579 `parse-time-weekdays'.
5581 While prompting, a calendar is popped up - you can also select the
5582 date with the mouse (button 1). The calendar shows a period of three
5583 months. To scroll it to other months, use the keys `>' and `<'.
5584 If you don't like the calendar, turn it off with
5585 \(setq org-popup-calendar-for-date-prompt nil)
5587 With optional argument TO-TIME, the date will immediately be converted
5588 to an internal time.
5589 With an optional argument WITH-TIME, the prompt will suggest to also
5590 insert a time. Note that when WITH-TIME is not set, you can still
5591 enter a time, and this function will inform the calling routine about
5592 this change. The calling routine may then choose to change the format
5593 used to insert the time stamp into the buffer to include the time."
5594 (require 'parse-time)
5595 (let* ((org-time-stamp-rounding-minutes
5596 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5597 (ct (org-current-time))
5598 (default-time
5599 ;; Default time is either today, or, when entering a range,
5600 ;; the range start.
5601 (if (save-excursion
5602 (re-search-backward
5603 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5604 (- (point) 20) t))
5605 (apply
5606 'encode-time
5607 (mapcar (lambda(x) (or x 0))
5608 (parse-time-string (match-string 1))))
5609 ct))
5610 (calendar-move-hook nil)
5611 (view-diary-entries-initially nil)
5612 (view-calendar-holidays-initially nil)
5613 (timestr (format-time-string
5614 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5615 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5616 ans ans1 ans2
5617 second minute hour day month year tl wday wday1)
5619 (if org-popup-calendar-for-date-prompt
5620 (save-excursion
5621 (save-window-excursion
5622 (calendar)
5623 (calendar-forward-day (- (time-to-days default-time)
5624 (calendar-absolute-from-gregorian
5625 (calendar-current-date))))
5626 (org-eval-in-calendar nil)
5627 (let* ((old-map (current-local-map))
5628 (map (copy-keymap calendar-mode-map))
5629 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5630 (define-key map (kbd "RET") 'org-calendar-select)
5631 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5632 'org-calendar-select-mouse)
5633 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5634 'org-calendar-select-mouse)
5635 (define-key minibuffer-local-map [(meta shift left)]
5636 (lambda () (interactive)
5637 (org-eval-in-calendar '(calendar-backward-month 1))))
5638 (define-key minibuffer-local-map [(meta shift right)]
5639 (lambda () (interactive)
5640 (org-eval-in-calendar '(calendar-forward-month 1))))
5641 (define-key minibuffer-local-map [(shift up)]
5642 (lambda () (interactive)
5643 (org-eval-in-calendar '(calendar-backward-week 1))))
5644 (define-key minibuffer-local-map [(shift down)]
5645 (lambda () (interactive)
5646 (org-eval-in-calendar '(calendar-forward-week 1))))
5647 (define-key minibuffer-local-map [(shift left)]
5648 (lambda () (interactive)
5649 (org-eval-in-calendar '(calendar-backward-day 1))))
5650 (define-key minibuffer-local-map [(shift right)]
5651 (lambda () (interactive)
5652 (org-eval-in-calendar '(calendar-forward-day 1))))
5653 (define-key minibuffer-local-map ">"
5654 (lambda () (interactive)
5655 (org-eval-in-calendar '(scroll-calendar-left 1))))
5656 (define-key minibuffer-local-map "<"
5657 (lambda () (interactive)
5658 (org-eval-in-calendar '(scroll-calendar-right 1))))
5659 (unwind-protect
5660 (progn
5661 (use-local-map map)
5662 (setq ans (read-string prompt "" nil nil))
5663 (if (not (string-match "\\S-" ans)) (setq ans nil))
5664 (setq ans (or ans1 ans ans2)))
5665 (use-local-map old-map)))))
5666 ;; Naked prompt only
5667 (setq ans (read-string prompt "" nil timestr)))
5668 (org-detatch-overlay org-date-ovl)
5670 (if (string-match
5671 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5672 (progn
5673 (setq year (if (match-end 2)
5674 (string-to-number (match-string 2 ans))
5675 (string-to-number (format-time-string "%Y")))
5676 month (string-to-number (match-string 3 ans))
5677 day (string-to-number (match-string 4 ans)))
5678 (if (< year 100) (setq year (+ 2000 year)))
5679 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5680 t nil ans))))
5681 (setq tl (parse-time-string ans)
5682 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5683 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5684 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5685 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5686 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5687 second (or (nth 0 tl) 0)
5688 wday (nth 6 tl))
5689 (when (and wday (not (nth 3 tl)))
5690 ;; Weekday was given, but no day, so pick that day in the week
5691 ;; on or after the derived date.
5692 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5693 (unless (equal wday wday1)
5694 (setq day (+ day (% (- wday wday1 -7) 7)))))
5695 (if (and (boundp 'org-time-was-given)
5696 (nth 2 tl))
5697 (setq org-time-was-given t))
5698 (if (< year 100) (setq year (+ 2000 year)))
5699 (if to-time
5700 (encode-time second minute hour day month year)
5701 (if (or (nth 1 tl) (nth 2 tl))
5702 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5703 (format "%04d-%02d-%02d" year month day)))))
5705 (defun org-eval-in-calendar (form)
5706 "Eval FORM in the calendar window and return to current window.
5707 Also, store the cursor date in variable ans2."
5708 (let ((sw (selected-window)))
5709 (select-window (get-buffer-window "*Calendar*"))
5710 (eval form)
5711 (when (calendar-cursor-to-date)
5712 (let* ((date (calendar-cursor-to-date))
5713 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5714 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5715 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5716 (select-window sw)))
5718 (defun org-calendar-select ()
5719 "Return to `org-read-date' with the date currently selected.
5720 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5721 (interactive)
5722 (when (calendar-cursor-to-date)
5723 (let* ((date (calendar-cursor-to-date))
5724 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5725 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5726 (if (active-minibuffer-window) (exit-minibuffer))))
5728 (defun org-calendar-select-mouse (ev)
5729 "Return to `org-read-date' with the date currently selected.
5730 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5731 (interactive "e")
5732 (mouse-set-point ev)
5733 (when (calendar-cursor-to-date)
5734 (let* ((date (calendar-cursor-to-date))
5735 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5736 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5737 (if (active-minibuffer-window) (exit-minibuffer))))
5739 (defun org-check-deadlines (ndays)
5740 "Check if there are any deadlines due or past due.
5741 A deadline is considered due if it happens within `org-deadline-warning-days'
5742 days from today's date. If the deadline appears in an entry marked DONE,
5743 it is not shown. The prefix arg NDAYS can be used to test that many
5744 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5745 (interactive "P")
5746 (let* ((org-warn-days
5747 (cond
5748 ((equal ndays '(4)) 100000)
5749 (ndays (prefix-numeric-value ndays))
5750 (t org-deadline-warning-days)))
5751 (case-fold-search nil)
5752 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5753 (callback
5754 (lambda ()
5755 (and (let ((d1 (time-to-days (current-time)))
5756 (d2 (time-to-days
5757 (org-time-string-to-time (match-string 1)))))
5758 (< (- d2 d1) org-warn-days))
5759 (not (org-entry-is-done-p))))))
5760 (message "%d deadlines past-due or due within %d days"
5761 (org-occur regexp callback)
5762 org-warn-days)))
5764 (defun org-evaluate-time-range (&optional to-buffer)
5765 "Evaluate a time range by computing the difference between start and end.
5766 Normally the result is just printed in the echo area, but with prefix arg
5767 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5768 If the time range is actually in a table, the result is inserted into the
5769 next column.
5770 For time difference computation, a year is assumed to be exactly 365
5771 days in order to avoid rounding problems."
5772 (interactive "P")
5774 (org-clock-update-time-maybe)
5775 (save-excursion
5776 (unless (org-at-date-range-p)
5777 (goto-char (point-at-bol))
5778 (re-search-forward org-tr-regexp (point-at-eol) t))
5779 (if (not (org-at-date-range-p))
5780 (error "Not at a time-stamp range, and none found in current line")))
5781 (let* ((ts1 (match-string 1))
5782 (ts2 (match-string 2))
5783 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5784 (match-end (match-end 0))
5785 (time1 (org-time-string-to-time ts1))
5786 (time2 (org-time-string-to-time ts2))
5787 (t1 (time-to-seconds time1))
5788 (t2 (time-to-seconds time2))
5789 (diff (abs (- t2 t1)))
5790 (negative (< (- t2 t1) 0))
5791 ;; (ys (floor (* 365 24 60 60)))
5792 (ds (* 24 60 60))
5793 (hs (* 60 60))
5794 (fy "%dy %dd %02d:%02d")
5795 (fy1 "%dy %dd")
5796 (fd "%dd %02d:%02d")
5797 (fd1 "%dd")
5798 (fh "%02d:%02d")
5799 y d h m align)
5800 (if havetime
5801 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5803 d (floor (/ diff ds)) diff (mod diff ds)
5804 h (floor (/ diff hs)) diff (mod diff hs)
5805 m (floor (/ diff 60)))
5806 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5808 d (floor (+ (/ diff ds) 0.5))
5809 h 0 m 0))
5810 (if (not to-buffer)
5811 (message (org-make-tdiff-string y d h m))
5812 (when (org-at-table-p)
5813 (goto-char match-end)
5814 (setq align t)
5815 (and (looking-at " *|") (goto-char (match-end 0))))
5816 (if (looking-at
5817 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5818 (replace-match ""))
5819 (if negative (insert " -"))
5820 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5821 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5822 (insert " " (format fh h m))))
5823 (if align (org-table-align))
5824 (message "Time difference inserted")))))
5826 (defun org-make-tdiff-string (y d h m)
5827 (let ((fmt "")
5828 (l nil))
5829 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5830 l (push y l)))
5831 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5832 l (push d l)))
5833 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5834 l (push h l)))
5835 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5836 l (push m l)))
5837 (apply 'format fmt (nreverse l))))
5839 (defun org-time-string-to-time (s)
5840 (apply 'encode-time (org-parse-time-string s)))
5842 (defun org-parse-time-string (s &optional nodefault)
5843 "Parse the standard Org-mode time string.
5844 This should be a lot faster than the normal `parse-time-string'.
5845 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5846 hour and minute fields will be nil if not given."
5847 (if (string-match org-ts-regexp1 s)
5848 (list 0
5849 (if (or (match-beginning 8) (not nodefault))
5850 (string-to-number (or (match-string 8 s) "0")))
5851 (if (or (match-beginning 7) (not nodefault))
5852 (string-to-number (or (match-string 7 s) "0")))
5853 (string-to-number (match-string 4 s))
5854 (string-to-number (match-string 3 s))
5855 (string-to-number (match-string 2 s))
5856 nil nil nil)
5857 (make-list 9 0)))
5859 (defun org-timestamp-up (&optional arg)
5860 "Increase the date item at the cursor by one.
5861 If the cursor is on the year, change the year. If it is on the month or
5862 the day, change that.
5863 With prefix ARG, change by that many units."
5864 (interactive "p")
5865 (org-timestamp-change (prefix-numeric-value arg)))
5867 (defun org-timestamp-down (&optional arg)
5868 "Decrease the date item at the cursor by one.
5869 If the cursor is on the year, change the year. If it is on the month or
5870 the day, change that.
5871 With prefix ARG, change by that many units."
5872 (interactive "p")
5873 (org-timestamp-change (- (prefix-numeric-value arg))))
5875 (defun org-timestamp-up-day (&optional arg)
5876 "Increase the date in the time stamp by one day.
5877 With prefix ARG, change that many days."
5878 (interactive "p")
5879 (if (and (not (org-at-timestamp-p t))
5880 (org-on-heading-p))
5881 (org-todo 'up)
5882 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5884 (defun org-timestamp-down-day (&optional arg)
5885 "Decrease the date in the time stamp by one day.
5886 With prefix ARG, change that many days."
5887 (interactive "p")
5888 (if (and (not (org-at-timestamp-p t))
5889 (org-on-heading-p))
5890 (org-todo 'down)
5891 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5893 (defsubst org-pos-in-match-range (pos n)
5894 (and (match-beginning n)
5895 (<= (match-beginning n) pos)
5896 (>= (match-end n) pos)))
5898 (defun org-at-timestamp-p (&optional also-inactive)
5899 "Determine if the cursor is in or at a timestamp."
5900 (interactive)
5901 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5902 (pos (point))
5903 (ans (or (looking-at tsr)
5904 (save-excursion
5905 (skip-chars-backward "^[<\n\r\t")
5906 (if (> (point) 1) (backward-char 1))
5907 (and (looking-at tsr)
5908 (> (- (match-end 0) pos) -1))))))
5909 (and (boundp 'org-ts-what)
5910 (setq org-ts-what
5911 (cond
5912 ((org-pos-in-match-range pos 2) 'year)
5913 ((org-pos-in-match-range pos 3) 'month)
5914 ((org-pos-in-match-range pos 7) 'hour)
5915 ((org-pos-in-match-range pos 8) 'minute)
5916 ((or (org-pos-in-match-range pos 4)
5917 (org-pos-in-match-range pos 5)) 'day)
5918 (t 'day))))
5919 ans))
5921 (defun org-timestamp-change (n &optional what)
5922 "Change the date in the time stamp at point.
5923 The date will be changed by N times WHAT. WHAT can be `day', `month',
5924 `year', `minute', `second'. If WHAT is not given, the cursor position
5925 in the timestamp determines what will be changed."
5926 (let ((fmt (car org-time-stamp-formats))
5927 org-ts-what
5928 (pos (point))
5929 ts time time0)
5930 (if (not (org-at-timestamp-p t))
5931 (error "Not at a timestamp"))
5932 (setq org-ts-what (or what org-ts-what))
5933 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5934 (- (match-end 0) (match-beginning 0))))
5936 (cdr org-time-stamp-formats)
5937 (car org-time-stamp-formats)))
5938 (if (= (char-after (match-beginning 0)) ?\[)
5939 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5940 (setq ts (match-string 0))
5941 (replace-match "")
5942 (setq time0 (org-parse-time-string ts))
5943 (setq time
5944 (apply 'encode-time
5945 (append
5946 (list (or (car time0) 0))
5947 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5948 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5949 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5950 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5951 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5952 (nthcdr 6 time0))))
5953 (if (eq what 'calendar)
5954 (let ((cal-date
5955 (save-excursion
5956 (save-match-data
5957 (set-buffer "*Calendar*")
5958 (calendar-cursor-to-date)))))
5959 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5960 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5961 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5962 (setcar time0 (or (car time0) 0))
5963 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5964 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5965 (setq time (apply 'encode-time time0))))
5966 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5967 (org-clock-update-time-maybe)
5968 (goto-char pos)
5969 ;; Try to recenter the calendar window, if any
5970 (if (and org-calendar-follow-timestamp-change
5971 (get-buffer-window "*Calendar*" t)
5972 (memq org-ts-what '(day month year)))
5973 (org-recenter-calendar (time-to-days time)))))
5975 (defun org-recenter-calendar (date)
5976 "If the calendar is visible, recenter it to DATE."
5977 (let* ((win (selected-window))
5978 (cwin (get-buffer-window "*Calendar*" t))
5979 (calendar-move-hook nil))
5980 (when cwin
5981 (select-window cwin)
5982 (calendar-goto-date (if (listp date) date
5983 (calendar-gregorian-from-absolute date)))
5984 (select-window win))))
5986 (defun org-goto-calendar (&optional arg)
5987 "Go to the Emacs calendar at the current date.
5988 If there is a time stamp in the current line, go to that date.
5989 A prefix ARG can be used to force the current date."
5990 (interactive "P")
5991 (let ((tsr org-ts-regexp) diff
5992 (calendar-move-hook nil)
5993 (view-calendar-holidays-initially nil)
5994 (view-diary-entries-initially nil))
5995 (if (or (org-at-timestamp-p)
5996 (save-excursion
5997 (beginning-of-line 1)
5998 (looking-at (concat ".*" tsr))))
5999 (let ((d1 (time-to-days (current-time)))
6000 (d2 (time-to-days
6001 (org-time-string-to-time (match-string 1)))))
6002 (setq diff (- d2 d1))))
6003 (calendar)
6004 (calendar-goto-today)
6005 (if (and diff (not arg)) (calendar-forward-day diff))))
6007 (defun org-date-from-calendar ()
6008 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
6009 If there is already a time stamp at the cursor position, update it."
6010 (interactive)
6011 (org-timestamp-change 0 'calendar))
6013 ;;; The clock for measuring work time.
6015 (defvar org-clock-marker (make-marker)
6016 "Marker recording the last clock-in.")
6018 (defun org-clock-in ()
6019 "Start the clock on the current item.
6020 If necessary, clock-out of the currently active clock."
6021 (interactive)
6022 (org-clock-out t)
6023 (let (ts)
6024 (save-excursion
6025 (org-back-to-heading t)
6026 (beginning-of-line 2)
6027 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6028 (not (equal (match-string 1) org-clock-string)))
6029 (beginning-of-line 1))
6030 (insert "\n") (backward-char 1)
6031 (indent-relative)
6032 (insert org-clock-string " "
6033 (setq ts (concat "[" (format-time-string
6034 (substring
6035 (cdr org-time-stamp-formats) 1 -1)
6036 (current-time))
6037 "]")))
6038 (move-marker org-clock-marker (point))
6039 (message "Clock started at %s" ts))))
6041 (defun org-clock-out (&optional fail-quietly)
6042 "Stop the currently running clock.
6043 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
6044 (interactive)
6045 (catch 'exit
6046 (if (not (marker-buffer org-clock-marker))
6047 (if fail-quietly (throw 'exit t) (error "No active clock")))
6048 (let (ts te s h m)
6049 (save-excursion
6050 (set-buffer (marker-buffer org-clock-marker))
6051 (goto-char org-clock-marker)
6052 (beginning-of-line 1)
6053 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6054 (equal (match-string 1) org-clock-string))
6055 (setq ts (match-string 2))
6056 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
6057 (goto-char org-clock-marker)
6058 (setq te (concat "[" (format-time-string
6059 (substring
6060 (cdr org-time-stamp-formats) 1 -1)
6061 (current-time))
6062 "]"))
6063 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
6064 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
6065 h (floor (/ s 3600))
6066 s (- s (* 3600 h))
6067 m (floor (/ s 60))
6068 s (- s (* 60 s)))
6069 (insert "--" te " => " (format "%2d:%02d" h m))
6070 (move-marker org-clock-marker nil)
6071 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
6073 (defun org-clock-cancel ()
6074 "Cancel the running clock be removing the start timestamp."
6075 (interactive)
6076 (if (not (marker-buffer org-clock-marker))
6077 (error "No active clock"))
6078 (save-excursion
6079 (set-buffer (marker-buffer org-clock-marker))
6080 (goto-char org-clock-marker)
6081 (delete-region (1- (point-at-bol)) (point-at-eol)))
6082 (message "Clock canceled"))
6084 (defvar org-clock-file-total-minutes nil
6085 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
6086 (make-variable-buffer-local 'org-clock-file-total-minutes)
6088 (defun org-clock-sum (&optional tstart tend)
6089 "Sum the times for each subtree.
6090 Puts the resulting times in minutes as a text property on each headline."
6091 (interactive)
6092 (let* ((bmp (buffer-modified-p))
6093 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
6094 org-clock-string
6095 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
6096 (lmax 30)
6097 (ltimes (make-vector lmax 0))
6098 (t1 0)
6099 (level 0)
6100 ts te dt
6101 time)
6102 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
6103 (save-excursion
6104 (goto-char (point-max))
6105 (while (re-search-backward re nil t)
6106 (if (match-end 2)
6107 ;; A time
6108 (setq ts (match-string 2)
6109 te (match-string 3)
6110 ts (time-to-seconds
6111 (apply 'encode-time (org-parse-time-string ts)))
6112 te (time-to-seconds
6113 (apply 'encode-time (org-parse-time-string te)))
6114 ts (if tstart (max ts tstart) ts)
6115 te (if tend (min te tend) te)
6116 dt (- te ts)
6117 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
6118 ;; A headline
6119 (setq level (- (match-end 1) (match-beginning 1)))
6120 (when (or (> t1 0) (> (aref ltimes level) 0))
6121 (loop for l from 0 to level do
6122 (aset ltimes l (+ (aref ltimes l) t1)))
6123 (setq t1 0 time (aref ltimes level))
6124 (loop for l from level to (1- lmax) do
6125 (aset ltimes l 0))
6126 (goto-char (match-beginning 0))
6127 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
6128 (setq org-clock-file-total-minutes (aref ltimes 0)))
6129 (set-buffer-modified-p bmp)))
6131 (defun org-clock-display (&optional total-only)
6132 "Show subtree times in the entire buffer.
6133 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6134 in the echo area."
6135 (interactive)
6136 (org-remove-clock-overlays)
6137 (let (time h m p)
6138 (org-clock-sum)
6139 (unless total-only
6140 (save-excursion
6141 (goto-char (point-min))
6142 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6143 (goto-char p)
6144 (when (setq time (get-text-property p :org-clock-minutes))
6145 (org-put-clock-overlay time (funcall outline-level))))
6146 (setq h (/ org-clock-file-total-minutes 60)
6147 m (- org-clock-file-total-minutes (* 60 h)))
6148 ;; Arrange to remove the overlays upon next change.
6149 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6150 nil 'local)))
6151 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6153 (defvar org-clock-overlays nil)
6154 (make-variable-buffer-local 'org-clock-overlays)
6156 (defun org-put-clock-overlay (time &optional level)
6157 "Put an overlays on the current line, displaying TIME.
6158 If LEVEL is given, prefix time with a corresponding number of stars.
6159 This creates a new overlay and stores it in `org-clock-overlays', so that it
6160 will be easy to remove."
6161 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6162 (l (if level (org-get-legal-level level 0) 0))
6163 (off 0)
6164 ov tx)
6165 (move-to-column c)
6166 (unless (eolp) (skip-chars-backward "^ \t"))
6167 (skip-chars-backward " \t")
6168 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6169 tx (concat (buffer-substring (1- (point)) (point))
6170 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6171 (org-add-props (format "%s %2d:%02d%s"
6172 (make-string l ?*) h m
6173 (make-string (- 10 l) ?\ ))
6174 '(face secondary-selection))
6175 ""))
6176 (org-overlay-put ov 'display tx)
6177 (push ov org-clock-overlays)))
6179 (defun org-remove-clock-overlays (&optional beg end noremove)
6180 "Remove the occur highlights from the buffer.
6181 BEG and END are ignored. If NOREMOVE is nil, remove this function
6182 from the `before-change-functions' in the current buffer."
6183 (interactive)
6184 (unless org-inhibit-highlight-removal
6185 (mapc 'org-delete-overlay org-clock-overlays)
6186 (setq org-clock-overlays nil)
6187 (unless noremove
6188 (remove-hook 'before-change-functions
6189 'org-remove-clock-overlays 'local))))
6191 (defun org-clock-out-if-current ()
6192 "Clock out if the current entry contains the running clock.
6193 This is used to stop the clock after a TODO entry is marked DONE."
6194 (when (and (equal state org-done-string)
6195 (equal (marker-buffer org-clock-marker) (current-buffer))
6196 (< (point) org-clock-marker)
6197 (> (save-excursion (outline-next-heading) (point))
6198 org-clock-marker))
6199 (org-clock-out)))
6201 (add-hook 'org-after-todo-state-change-hook
6202 'org-clock-out-if-current)
6204 (defun org-check-running-clock ()
6205 "Check if the current buffer contains the running clock.
6206 If yes, offer to stop it and to save the buffer with the changes."
6207 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6208 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6209 (buffer-name))))
6210 (org-clock-out)
6211 (when (y-or-n-p "Save changed buffer?")
6212 (save-buffer))))
6214 (defun org-clock-report ()
6215 "Create a table containing a report about clocked time.
6216 If the buffer contains lines
6217 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6219 #+END: clocktable
6220 then the table will be inserted between these lines, replacing whatever
6221 is was there before. If these lines are not in the buffer, the table
6222 is inserted at point, surrounded by the special lines.
6223 The BEGIN line can contain parameters. Allowed are:
6224 :maxlevel The maximum level to be included in the table. Default is 3.
6225 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6226 (interactive)
6227 (org-remove-clock-overlays)
6228 (unless (org-find-dblock "clocktable")
6229 (org-create-dblock (list :name "clocktable"
6230 :maxlevel 2 :emphasize nil)))
6231 (org-update-dblock))
6233 (defun org-clock-update-time-maybe ()
6234 "If this is a CLOCK line, update it and return t.
6235 Otherwise, return nil."
6236 (interactive)
6237 (save-excursion
6238 (beginning-of-line 1)
6239 (skip-chars-forward " \t")
6240 (when (looking-at org-clock-string)
6241 (let ((re (concat "[ \t]*" org-clock-string
6242 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6243 "\\([ \t]*=>.*\\)?"))
6244 ts te h m s)
6245 (if (not (looking-at re))
6247 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6248 (end-of-line 1)
6249 (setq ts (match-string 1)
6250 te (match-string 2))
6251 (setq s (- (time-to-seconds
6252 (apply 'encode-time (org-parse-time-string te)))
6253 (time-to-seconds
6254 (apply 'encode-time (org-parse-time-string ts))))
6255 h (floor (/ s 3600))
6256 s (- s (* 3600 h))
6257 m (floor (/ s 60))
6258 s (- s (* 60 s)))
6259 (insert " => " (format "%2d:%02d" h m))
6260 t)))))
6262 (defun org-clock-special-range (key &optional time as-strings)
6263 "Return two times bordering a special time range.
6264 Key is a symbol specifying the range and can be one of `today', `yesterday',
6265 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6266 A week starts Monday 0:00 and ends Sunday 24:00.
6267 The range is determined relative to TIME. TIME defaults to the current time.
6268 The return value is a cons cell with two internal times like the ones
6269 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6270 the returned times will be formatted strings."
6271 (let* ((tm (decode-time (or time (current-time))))
6272 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6273 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6274 (dow (nth 6 tm))
6275 s1 m1 h1 d1 month1 y1 diff ts te fm)
6276 (cond
6277 ((eq key 'today)
6278 (setq h 0 m 0 h1 24 m1 0))
6279 ((eq key 'yesterday)
6280 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6281 ((eq key 'thisweek)
6282 (setq diff (if (= dow 0) 6 (1- dow))
6283 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6284 ((eq key 'lastweek)
6285 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6286 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6287 ((eq key 'thismonth)
6288 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6289 ((eq key 'lastmonth)
6290 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6291 ((eq key 'thisyear)
6292 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6293 ((eq key 'lastyear)
6294 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6295 (t (error "No such time block %s" key)))
6296 (setq ts (encode-time s m h d month y)
6297 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6298 (or d1 d) (or month1 month) (or y1 y)))
6299 (setq fm (cdr org-time-stamp-formats))
6300 (if as-strings
6301 (cons (format-time-string fm ts) (format-time-string fm te))
6302 (cons ts te))))
6304 (defun org-dblock-write:clocktable (params)
6305 "Write the standard clocktable."
6306 (let ((hlchars '((1 . "*") (2 . ?/)))
6307 (emph nil)
6308 (ins (make-marker))
6309 ipos time h m p level hlc hdl maxlevel
6310 ts te cc block)
6311 (setq maxlevel (or (plist-get params :maxlevel) 3)
6312 emph (plist-get params :emphasize)
6313 ts (plist-get params :tstart)
6314 te (plist-get params :tend)
6315 block (plist-get params :block))
6316 (when block
6317 (setq cc (org-clock-special-range block nil t)
6318 ts (car cc) te (cdr cc)))
6319 (if ts (setq ts (time-to-seconds
6320 (apply 'encode-time (org-parse-time-string ts)))))
6321 (if te (setq te (time-to-seconds
6322 (apply 'encode-time (org-parse-time-string te)))))
6323 (move-marker ins (point))
6324 (setq ipos (point))
6325 (insert-before-markers "Clock summary at ["
6326 (substring
6327 (format-time-string (cdr org-time-stamp-formats))
6328 1 -1)
6329 "]."
6330 (if block
6331 (format " Considered range is /%s/." block)
6333 "\n\n|L|Headline|Time|\n")
6334 (org-clock-sum ts te)
6335 (setq h (/ org-clock-file-total-minutes 60)
6336 m (- org-clock-file-total-minutes (* 60 h)))
6337 (insert-before-markers "|-\n|0|" "*Total file time*| "
6338 (format "*%d:%02d*" h m)
6339 "|\n")
6340 (goto-char (point-min))
6341 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6342 (goto-char p)
6343 (when (setq time (get-text-property p :org-clock-minutes))
6344 (save-excursion
6345 (beginning-of-line 1)
6346 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6347 (setq level (- (match-end 1) (match-beginning 1)))
6348 (<= level maxlevel))
6349 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6350 hdl (match-string 2)
6351 h (/ time 60)
6352 m (- time (* 60 h)))
6353 (goto-char ins)
6354 (if (= level 1) (insert-before-markers "|-\n"))
6355 (insert-before-markers
6356 "| " (int-to-string level) "|" hlc hdl hlc " |"
6357 (make-string (1- level) ?|)
6359 (format "%d:%02d" h m)
6361 " |\n")))))
6362 (goto-char ins)
6363 (backward-delete-char 1)
6364 (goto-char ipos)
6365 (skip-chars-forward "^|")
6366 (org-table-align)))
6368 (defun org-collect-clock-time-entries ()
6369 "Return an internal list with clocking information.
6370 This list has one entry for each CLOCK interval.
6371 FIXME: describe the elements."
6372 (interactive)
6373 (let ((re (concat "^[ \t]*" org-clock-string
6374 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6375 rtn beg end next cont level title total closedp leafp
6376 clockpos titlepos h m donep)
6377 (save-excursion
6378 (org-clock-sum)
6379 (goto-char (point-min))
6380 (while (re-search-forward re nil t)
6381 (setq clockpos (match-beginning 0)
6382 beg (match-string 1) end (match-string 2)
6383 cont (match-end 0))
6384 (setq beg (apply 'encode-time (org-parse-time-string beg))
6385 end (apply 'encode-time (org-parse-time-string end)))
6386 (org-back-to-heading t)
6387 (setq donep (org-entry-is-done-p))
6388 (setq titlepos (point)
6389 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6390 h (/ total 60) m (- total (* 60 h))
6391 total (cons h m))
6392 (looking-at "\\(\\*+\\) +\\(.*\\)")
6393 (setq level (- (match-end 1) (match-beginning 1))
6394 title (org-match-string-no-properties 2))
6395 (save-excursion (outline-next-heading) (setq next (point)))
6396 (setq closedp (re-search-forward org-closed-time-regexp next t))
6397 (goto-char next)
6398 (setq leafp (and (looking-at "^\\*+ ")
6399 (<= (- (match-end 0) (point)) level)))
6400 (push (list beg end clockpos closedp donep
6401 total title titlepos level leafp)
6402 rtn)
6403 (goto-char cont)))
6404 (nreverse rtn)))
6406 ;;; Agenda, and Diary Integration
6408 ;;; Define the mode
6410 (defvar org-agenda-mode-map (make-sparse-keymap)
6411 "Keymap for `org-agenda-mode'.")
6413 (defvar org-agenda-menu) ; defined later in this file.
6414 (defvar org-agenda-follow-mode nil)
6415 (defvar org-agenda-show-log nil)
6416 (defvar org-agenda-redo-command nil)
6417 (defvar org-agenda-mode-hook nil)
6418 (defvar org-agenda-type nil)
6419 (defvar org-agenda-force-single-file nil)
6421 (defun org-agenda-mode ()
6422 "Mode for time-sorted view on action items in Org-mode files.
6424 The following commands are available:
6426 \\{org-agenda-mode-map}"
6427 (interactive)
6428 (kill-all-local-variables)
6429 (setq major-mode 'org-agenda-mode)
6430 (setq mode-name "Org-Agenda")
6431 (use-local-map org-agenda-mode-map)
6432 (easy-menu-add org-agenda-menu)
6433 (if org-startup-truncated (setq truncate-lines t))
6434 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6435 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6436 (unless org-agenda-keep-modes
6437 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6438 org-agenda-show-log nil))
6439 (easy-menu-change
6440 '("Agenda") "Agenda Files"
6441 (append
6442 (list
6443 (vector
6444 (if (get 'org-agenda-files 'org-restrict)
6445 "Restricted to single file"
6446 "Edit File List")
6447 '(org-edit-agenda-file-list)
6448 (not (get 'org-agenda-files 'org-restrict)))
6449 "--")
6450 (mapcar 'org-file-menu-entry (org-agenda-files))))
6451 (org-agenda-set-mode-name)
6452 (apply
6453 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6454 (list 'org-agenda-mode-hook)))
6456 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6457 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6458 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6459 (define-key org-agenda-mode-map " " 'org-agenda-show)
6460 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6461 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6462 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6463 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6464 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6465 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6466 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6467 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6468 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6469 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6470 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6471 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6472 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6474 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6475 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6476 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6477 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6478 (while l (define-key org-agenda-mode-map
6479 (int-to-string (pop l)) 'digit-argument)))
6481 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6482 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6483 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6484 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6485 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6486 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6487 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6488 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6489 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6490 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6491 (define-key org-agenda-mode-map "n" 'next-line)
6492 (define-key org-agenda-mode-map "p" 'previous-line)
6493 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6494 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6495 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6496 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6497 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6498 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6499 (eval-after-load "calendar"
6500 '(define-key calendar-mode-map org-calendar-to-agenda-key
6501 'org-calendar-goto-agenda))
6502 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6503 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6504 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6505 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6506 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6507 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6508 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6509 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6510 (define-key org-agenda-mode-map "O" 'org-clock-out)
6511 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6512 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6513 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6514 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6515 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6516 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6517 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6518 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6519 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6520 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6521 "Local keymap for agenda entries from Org-mode.")
6523 (define-key org-agenda-keymap
6524 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6525 (define-key org-agenda-keymap
6526 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6527 (when org-agenda-mouse-1-follows-link
6528 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6529 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6530 '("Agenda"
6531 ("Agenda Files")
6532 "--"
6533 ["Show" org-agenda-show t]
6534 ["Go To (other window)" org-agenda-goto t]
6535 ["Go To (one window)" org-agenda-switch-to t]
6536 ["Follow Mode" org-agenda-follow-mode
6537 :style toggle :selected org-agenda-follow-mode :active t]
6538 "--"
6539 ["Cycle TODO" org-agenda-todo t]
6540 ("Tags"
6541 ["Show all Tags" org-agenda-show-tags t]
6542 ["Set Tags" org-agenda-set-tags t])
6543 ("Schedule"
6544 ["Schedule" org-agenda-schedule t]
6545 ["Set Deadline" org-agenda-deadline t]
6546 "--"
6547 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6548 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6549 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6550 ("Priority"
6551 ["Set Priority" org-agenda-priority t]
6552 ["Increase Priority" org-agenda-priority-up t]
6553 ["Decrease Priority" org-agenda-priority-down t]
6554 ["Show Priority" org-agenda-show-priority t])
6555 "--"
6556 ;; ["New agenda command" org-agenda t]
6557 ["Rebuild buffer" org-agenda-redo t]
6558 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6559 "--"
6560 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6561 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6562 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6563 "--"
6564 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6565 :style radio :selected (equal org-agenda-ndays 1)]
6566 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6567 :style radio :selected (equal org-agenda-ndays 7)]
6568 "--"
6569 ["Show Logbook entries" org-agenda-log-mode
6570 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6571 ["Include Diary" org-agenda-toggle-diary
6572 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6573 ["Use Time Grid" org-agenda-toggle-time-grid
6574 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6575 "--"
6576 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6577 ("Calendar Commands"
6578 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6579 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6580 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6581 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6582 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6583 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6584 "--"
6585 ["Quit" org-agenda-quit t]
6586 ["Exit and Release Buffers" org-agenda-exit t]
6589 (defvar org-agenda-restrict nil)
6590 (defvar org-agenda-restrict-begin (make-marker))
6591 (defvar org-agenda-restrict-end (make-marker))
6592 (defvar org-agenda-last-dispatch-buffer nil)
6594 ;;;###autoload
6595 (defun org-agenda (arg)
6596 "Dispatch agenda commands to collect entries to the agenda buffer.
6597 Prompts for a character to select a command. Any prefix arg will be passed
6598 on to the selected command. The default selections are:
6600 a Call `org-agenda-list' to display the agenda for current day or week.
6601 t Call `org-todo-list' to display the global todo list.
6602 T Call `org-todo-list' to display the global todo list, select only
6603 entries with a specific TODO keyword (the user gets a prompt).
6604 m Call `org-tags-view' to display headlines with tags matching
6605 a condition (the user is prompted for the condition).
6606 M Like `m', but select only TODO entries, no ordinary headlines.
6607 l Create a timeeline for the current buffer.
6609 More commands can be added by configuring the variable
6610 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6611 searches can be pre-defined in this way.
6613 If the current buffer is in Org-mode and visiting a file, you can also
6614 first press `1' to indicate that the agenda should be temporarily (until the
6615 next use of \\[org-agenda]) restricted to the current file."
6616 (interactive "P")
6617 (catch 'exit
6618 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6619 (buf (current-buffer))
6620 (bfn buffer-file-name)
6621 (custom org-agenda-custom-commands)
6622 c entry key type match lprops)
6623 ;; Turn off restriction
6624 (put 'org-agenda-files 'org-restrict nil)
6625 (setq org-agenda-restrict nil)
6626 (move-marker org-agenda-restrict-begin nil)
6627 (move-marker org-agenda-restrict-end nil)
6628 ;; Remember where this call originated
6629 (setq org-agenda-last-dispatch-buffer (current-buffer))
6630 (save-window-excursion
6631 (delete-other-windows)
6632 (switch-to-buffer-other-window " *Agenda Commands*")
6633 (erase-buffer)
6634 (insert
6635 "Press key for an agenda command:
6636 --------------------------------
6637 a Agenda for current week or day
6638 t List of all TODO entries T Entries with special TODO kwd
6639 m Match a TAGS query M Like m, but only TODO entries
6640 L Timeline for current buffer C Configure custom agenda commands")
6641 (while (setq entry (pop custom))
6642 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
6643 (insert (format "\n%-4s%-14s: %s"
6645 (cond
6646 ((stringp type) type)
6647 ((eq type 'tags) "Tags query")
6648 ((eq type 'todo) "TODO keyword")
6649 ((eq type 'tags-tree) "Tags tree")
6650 ((eq type 'todo-tree) "TODO kwd tree")
6651 ((eq type 'occur-tree) "Occur tree")
6652 (t "???"))
6653 (if (stringp match)
6654 (org-add-props match nil 'face 'org-warning)
6655 (format "set of %d commands" (+ -2 (length entry)))))))
6656 (if restrict-ok
6657 (insert "\n"
6658 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
6660 (goto-char (point-min))
6661 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6662 (message "Press key for agenda command%s"
6663 (if restrict-ok ", or [1] or [0] to restrict" ""))
6664 (setq c (read-char-exclusive))
6665 (message "")
6666 (when (memq c '(?L ?1 ?0))
6667 (if restrict-ok
6668 (put 'org-agenda-files 'org-restrict (list bfn))
6669 (error "Cannot restrict agenda to current buffer"))
6670 (with-current-buffer " *Agenda Commands*"
6671 (goto-char (point-max))
6672 (delete-region (point-at-bol) (point))
6673 (goto-char (point-min)))
6674 (when (eq c ?0)
6675 (setq org-agenda-restrict t)
6676 (with-current-buffer buf
6677 (if (org-region-active-p)
6678 (progn
6679 (move-marker org-agenda-restrict-begin (region-beginning))
6680 (move-marker org-agenda-restrict-end (region-end)))
6681 (save-excursion
6682 (org-back-to-heading t)
6683 (move-marker org-agenda-restrict-begin (point))
6684 (move-marker org-agenda-restrict-end
6685 (progn (org-end-of-subtree t)))))))
6686 (unless (eq c ?L)
6687 (message "Press key for agenda command%s"
6688 (if restrict-ok " (restricted to current file)" ""))
6689 (setq c (read-char-exclusive)))
6690 (message "")))
6691 (require 'calendar) ; FIXME: can we avoid this for some commands?
6692 ;; For example the todo list should not need it (but does...)
6693 (cond
6694 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6695 ((equal c ?a) (call-interactively 'org-agenda-list))
6696 ((equal c ?t) (call-interactively 'org-todo-list))
6697 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6698 ((equal c ?m) (call-interactively 'org-tags-view))
6699 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6700 ((equal c ?L)
6701 (unless restrict-ok
6702 (error "This is not an Org-mode file"))
6703 (org-call-with-arg 'org-timeline arg))
6704 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6705 (if (symbolp (nth 1 entry))
6706 (progn
6707 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
6708 lprops (nth 3 entry))
6709 (cond
6710 ((eq type 'tags)
6711 (org-let lprops '(org-tags-view current-prefix-arg match)))
6712 ((eq type 'tags-todo)
6713 (org-let lprops '(org-tags-view '(4) match)))
6714 ((eq type 'todo)
6715 (org-let lprops '(org-todo-list match)))
6716 ((eq type 'tags-tree)
6717 (org-check-for-org-mode)
6718 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
6719 ((eq type 'todo-tree)
6720 (org-check-for-org-mode)
6721 (org-let lprops
6722 '(org-occur (concat "^" outline-regexp "[ \t]*"
6723 (regexp-quote match) "\\>"))))
6724 ((eq type 'occur-tree)
6725 (org-check-for-org-mode)
6726 (org-let lprops '(org-occur match)))
6727 (t (error "Invalid custom agenda command type %s" type))))
6728 (org-run-agenda-series (cddr entry))))
6729 (t (error "Invalid key"))))))
6731 (defun org-run-agenda-series (series &optional window)
6732 (org-prepare-agenda)
6733 (let* ((org-agenda-multi t)
6734 (redo (list 'org-run-agenda-series (list 'quote series)))
6735 (org-select-agenda-window t)
6736 (cmds (car series))
6737 (gprops (nth 1 series))
6738 cmd type match lprops)
6739 (while (setq cmd (pop cmds))
6740 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
6741 (cond
6742 ((eq type 'agenda)
6743 (call-interactively 'org-agenda-list))
6744 ((eq type 'alltodo)
6745 (call-interactively 'org-todo-list))
6746 ((eq type 'tags)
6747 (org-let2 gprops lprops
6748 '(org-tags-view current-prefix-arg match)))
6749 ((eq type 'tags-todo)
6750 (org-let2 gprops lprops
6751 '(org-tags-view '(4) match)))
6752 ((eq type 'todo)
6753 (org-let2 gprops lprops
6754 '(org-todo-list match)))
6755 (t (error "Invalid type in command series"))))
6756 (widen)
6757 (setq org-agenda-redo-command redo)
6758 (goto-char (point-min))))
6760 ;;;###autoload
6761 (defmacro org-batch-agenda (cmd-key &rest parameters)
6762 "Run an agenda command in batch mode, send result to STDOUT.
6763 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
6764 Paramters are alternating variable names and values that will be bound
6765 before running the agenda command."
6766 (let (pars)
6767 (while parameters
6768 (push (list (pop parameters) (if parameters (pop parameters))) pars))
6769 (flet ((read-char-exclusive () (string-to-char cmd-key)))
6770 (eval (list 'let (nreverse pars) '(org-agenda nil))))
6771 (set-buffer "*Org Agenda*")
6772 (princ (buffer-string))))
6774 (defun org-check-for-org-mode ()
6775 "Make sure current buffer is in org-mode. Error if not."
6776 (or (org-mode-p)
6777 (error "Cannot execute org-mode agenda command on buffer in %s."
6778 major-mode)))
6780 (defun org-fit-agenda-window ()
6781 "Fit the window to the buffer size."
6782 (and org-fit-agenda-window
6783 (fboundp 'fit-window-to-buffer)
6784 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6785 (/ (frame-height) 2))))
6787 (defun org-agenda-files (&optional unrestricted)
6788 "Get the list of agenda files.
6789 Optional UNRESTRICTED means return the full list even if a restriction
6790 is currently in place."
6791 (cond
6792 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6793 ((stringp org-agenda-files) (org-read-agenda-file-list))
6794 ((listp org-agenda-files) org-agenda-files)
6795 (t (error "Invalid value of `org-agenda-files'"))))
6797 (defvar org-window-configuration)
6799 (defun org-edit-agenda-file-list ()
6800 "Edit the list of agenda files.
6801 Depending on setup, this either uses customize to edit the variable
6802 `org-agenda-files', or it visits the file that is holding the list. In the
6803 latter case, the buffer is set up in a way that saving it automatically kills
6804 the buffer and restores the previous window configuration."
6805 (interactive)
6806 (if (stringp org-agenda-files)
6807 (let ((cw (current-window-configuration)))
6808 (find-file org-agenda-files)
6809 (org-set-local 'org-window-configuration cw)
6810 (org-add-hook 'after-save-hook
6811 (lambda ()
6812 (set-window-configuration
6813 (prog1 org-window-configuration
6814 (kill-buffer (current-buffer))))
6815 (org-install-agenda-files-menu)
6816 (message "New agenda file list installed"))
6817 nil 'local)
6818 (message (substitute-command-keys
6819 "Edit list and finish with \\[save-buffer]")))
6820 (customize-variable 'org-agenda-files)))
6822 (defun org-store-new-agenda-file-list (list)
6823 "Set new value for the agenda file list and save it correcly."
6824 (if (stringp org-agenda-files)
6825 (let ((f org-agenda-files) b)
6826 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6827 (with-temp-file f
6828 (insert (mapconcat 'identity list "\n") "\n")))
6829 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6830 (setq org-agenda-files list)
6831 (customize-save-variable 'org-agenda-files org-agenda-files))))
6833 (defun org-read-agenda-file-list ()
6834 "Read the list of agenda files from a file."
6835 (when (stringp org-agenda-files)
6836 (with-temp-buffer
6837 (insert-file-contents org-agenda-files)
6838 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6840 (defvar org-agenda-markers nil
6841 "List of all currently active markers created by `org-agenda'.")
6842 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6843 "Creation time of the last agenda marker.")
6845 (defun org-agenda-new-marker (&optional pos)
6846 "Return a new agenda marker.
6847 Org-mode keeps a list of these markers and resets them when they are
6848 no longer in use."
6849 (let ((m (copy-marker (or pos (point)))))
6850 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6851 (push m org-agenda-markers)
6854 (defun org-agenda-maybe-reset-markers (&optional force)
6855 "Reset markers created by `org-agenda'. But only if they are old enough."
6856 (if (or (and force (not org-agenda-multi))
6857 (> (- (time-to-seconds (current-time))
6858 org-agenda-last-marker-time)
6860 (while org-agenda-markers
6861 (move-marker (pop org-agenda-markers) nil))))
6863 (defvar org-agenda-new-buffers nil
6864 "Buffers created to visit agenda files.")
6866 (defun org-get-agenda-file-buffer (file)
6867 "Get a buffer visiting FILE. If the buffer needs to be created, add
6868 it to the list of buffers which might be released later."
6869 (let ((buf (find-buffer-visiting file)))
6870 (if buf
6871 buf ; just return it
6872 ;; Make a new buffer and remember it
6873 (setq buf (find-file-noselect file))
6874 (if buf (push buf org-agenda-new-buffers))
6875 buf)))
6877 (defun org-release-buffers (blist)
6878 "Release all buffers in list, asking the user for confirmation when needed.
6879 When a buffer is unmodified, it is just killed. When modified, it is saved
6880 \(if the user agrees) and then killed."
6881 (let (buf file)
6882 (while (setq buf (pop blist))
6883 (setq file (buffer-file-name buf))
6884 (when (and (buffer-modified-p buf)
6885 file
6886 (y-or-n-p (format "Save file %s? " file)))
6887 (with-current-buffer buf (save-buffer)))
6888 (kill-buffer buf))))
6890 (defun org-timeline (&optional include-all keep-modes)
6891 "Show a time-sorted view of the entries in the current org file.
6892 Only entries with a time stamp of today or later will be listed. With
6893 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6894 under the current date.
6895 If the buffer contains an active region, only check the region for
6896 dates."
6897 (interactive "P")
6898 (require 'calendar)
6899 (org-compile-prefix-format 'timeline)
6900 (org-set-sorting-strategy 'timeline)
6901 (let* ((dopast t)
6902 (dotodo include-all)
6903 (doclosed org-agenda-show-log)
6904 (org-agenda-keep-modes keep-modes)
6905 (entry buffer-file-name)
6906 (date (calendar-current-date))
6907 (win (selected-window))
6908 (pos1 (point))
6909 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6910 (end (if (org-region-active-p) (region-end) (point-max)))
6911 (day-numbers (org-get-all-dates beg end 'no-ranges
6912 t doclosed ; always include today
6913 org-timeline-show-empty-dates))
6914 (today (time-to-days (current-time)))
6915 (past t)
6916 args
6917 s e rtn d emptyp)
6918 (setq org-agenda-redo-command
6919 (list 'progn
6920 (list 'switch-to-buffer-other-window (current-buffer))
6921 (list 'org-timeline (list 'quote include-all) t)))
6922 (if (not dopast)
6923 ;; Remove past dates from the list of dates.
6924 (setq day-numbers (delq nil (mapcar (lambda(x)
6925 (if (>= x today) x nil))
6926 day-numbers))))
6927 (org-prepare-agenda)
6928 (if doclosed (push :closed args))
6929 (push :timestamp args)
6930 (if dotodo (push :todo args))
6931 (while (setq d (pop day-numbers))
6932 (if (and (listp d) (eq (car d) :omitted))
6933 (progn
6934 (setq s (point))
6935 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6936 (put-text-property s (1- (point)) 'face 'org-level-3))
6937 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6938 (if (and (>= d today)
6939 dopast
6940 past)
6941 (progn
6942 (setq past nil)
6943 (insert (make-string 79 ?-) "\n")))
6944 (setq date (calendar-gregorian-from-absolute d))
6945 (setq s (point))
6946 (setq rtn (and (not emptyp)
6947 (apply 'org-agenda-get-day-entries
6948 entry date args)))
6949 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6950 (progn
6951 (insert (calendar-day-name date) " "
6952 (number-to-string (extract-calendar-day date)) " "
6953 (calendar-month-name (extract-calendar-month date)) " "
6954 (number-to-string (extract-calendar-year date)) "\n")
6955 (put-text-property s (1- (point)) 'face
6956 'org-level-3)
6957 (if (equal d today)
6958 (put-text-property s (1- (point)) 'org-today t))
6959 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6960 (put-text-property s (1- (point)) 'day d)))))
6961 (goto-char (point-min))
6962 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6963 (point-min)))
6964 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
6965 (org-agenda-align-tags)
6966 (setq buffer-read-only t)
6967 (when (not org-select-agenda-window)
6968 (select-window win)
6969 (goto-char pos1))))
6971 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
6972 (defvar org-agenda-last-arguments nil
6973 "The arguments of the previous call to org-agenda")
6975 ;;;###autoload
6976 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6977 "Produce a weekly view from all files in variable `org-agenda-files'.
6978 The view will be for the current week, but from the overview buffer you
6979 will be able to go to other weeks.
6980 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6981 also be shown, under the current date.
6982 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6983 on the days are also shown. See the variable `org-log-done' for how
6984 to turn on logging.
6985 START-DAY defaults to TODAY, or to the most recent match for the weekday
6986 given in `org-agenda-start-on-weekday'.
6987 NDAYS defaults to `org-agenda-ndays'."
6988 (interactive "P")
6989 (if org-agenda-overriding-arguments
6990 (setq include-all (car org-agenda-overriding-arguments)
6991 start-day (nth 1 org-agenda-overriding-arguments)
6992 ndays (nth 2 org-agenda-overriding-arguments)
6993 keep-modes (nth 3 org-agenda-overriding-arguments)))
6994 (setq org-agenda-last-arguments (list include-all start-day ndays keep-modes))
6995 (org-compile-prefix-format 'agenda)
6996 (org-set-sorting-strategy 'agenda)
6997 (require 'calendar)
6998 (let* ((org-agenda-start-on-weekday
6999 (if (or (equal ndays 1)
7000 (and (null ndays) (equal 1 org-agenda-ndays)))
7001 nil org-agenda-start-on-weekday))
7002 (org-agenda-keep-modes keep-modes)
7003 (thefiles (org-agenda-files))
7004 (files thefiles)
7005 (win (selected-window))
7006 (today (time-to-days (current-time)))
7007 (sd (or start-day today))
7008 (start (if (or (null org-agenda-start-on-weekday)
7009 (< org-agenda-ndays 7))
7011 (let* ((nt (calendar-day-of-week
7012 (calendar-gregorian-from-absolute sd)))
7013 (n1 org-agenda-start-on-weekday)
7014 (d (- nt n1)))
7015 (- sd (+ (if (< d 0) 7 0) d)))))
7016 (day-numbers (list start))
7017 (inhibit-redisplay t)
7018 s e rtn rtnall file date d start-pos end-pos todayp nd)
7019 (setq org-agenda-redo-command
7020 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
7021 ;; Make the list of days
7022 (setq ndays (or ndays org-agenda-ndays)
7023 nd ndays)
7024 (while (> ndays 1)
7025 (push (1+ (car day-numbers)) day-numbers)
7026 (setq ndays (1- ndays)))
7027 (setq day-numbers (nreverse day-numbers))
7028 (org-prepare-agenda)
7029 (org-set-local 'starting-day (car day-numbers))
7030 (org-set-local 'include-all-loc include-all)
7031 (when (and (or include-all org-agenda-include-all-todo)
7032 (member today day-numbers))
7033 (setq files thefiles
7034 rtnall nil)
7035 (while (setq file (pop files))
7036 (catch 'nextfile
7037 (org-check-agenda-file file)
7038 (setq date (calendar-gregorian-from-absolute today)
7039 rtn (org-agenda-get-day-entries
7040 file date :todo))
7041 (setq rtnall (append rtnall rtn))))
7042 (when rtnall
7043 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
7044 (add-text-properties (point-min) (1- (point))
7045 (list 'face 'org-level-3))
7046 (insert (org-finalize-agenda-entries rtnall) "\n")))
7047 (setq s (point))
7048 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
7049 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
7050 (while (setq d (pop day-numbers))
7051 (setq date (calendar-gregorian-from-absolute d)
7052 s (point))
7053 (if (or (setq todayp (= d today))
7054 (and (not start-pos) (= d sd)))
7055 (setq start-pos (point))
7056 (if (and start-pos (not end-pos))
7057 (setq end-pos (point))))
7058 (setq files thefiles
7059 rtnall nil)
7060 (while (setq file (pop files))
7061 (catch 'nextfile
7062 (org-check-agenda-file file)
7063 (if org-agenda-show-log
7064 (setq rtn (org-agenda-get-day-entries
7065 file date
7066 :deadline :scheduled :timestamp :closed))
7067 (setq rtn (org-agenda-get-day-entries
7068 file date
7069 :deadline :scheduled :timestamp)))
7070 (setq rtnall (append rtnall rtn))))
7071 (if org-agenda-include-diary
7072 (progn
7073 (require 'diary-lib)
7074 (setq rtn (org-get-entries-from-diary date))
7075 (setq rtnall (append rtnall rtn))))
7076 (if (or rtnall org-agenda-show-all-dates)
7077 (progn
7078 (insert (format "%-9s %2d %s %4d\n"
7079 (calendar-day-name date)
7080 (extract-calendar-day date)
7081 (calendar-month-name (extract-calendar-month date))
7082 (extract-calendar-year date)))
7083 (put-text-property s (1- (point)) 'face
7084 'org-level-3)
7085 (if todayp (put-text-property s (1- (point)) 'org-today t))
7087 (if rtnall (insert
7088 (org-finalize-agenda-entries
7089 (org-agenda-add-time-grid-maybe
7090 rtnall nd todayp))
7091 "\n"))
7092 (put-text-property s (1- (point)) 'day d))))
7093 (goto-char (point-min))
7094 (org-fit-agenda-window)
7095 (unless (and (pos-visible-in-window-p (point-min))
7096 (pos-visible-in-window-p (point-max)))
7097 (goto-char (1- (point-max)))
7098 (recenter -1)
7099 (if (not (pos-visible-in-window-p (or start-pos 1)))
7100 (progn
7101 (goto-char (or start-pos 1))
7102 (recenter 1))))
7103 (goto-char (or start-pos 1))
7104 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
7105 (org-agenda-align-tags)
7106 (setq buffer-read-only t)
7107 (if (not org-select-agenda-window) (select-window win))
7108 (message "")))
7110 (defvar org-select-this-todo-keyword nil)
7112 ;;;###autoload
7113 (defun org-todo-list (arg &optional keep-modes)
7114 "Show all TODO entries from all agenda file in a single list.
7115 The prefix arg can be used to select a specific TODO keyword and limit
7116 the list to these. When using \\[universal-argument], you will be prompted
7117 for a keyword. A numeric prefix directly selects the Nth keyword in
7118 `org-todo-keywords'."
7119 (interactive "P")
7120 (org-compile-prefix-format 'todo)
7121 (org-set-sorting-strategy 'todo)
7122 (let* ((org-agenda-keep-modes keep-modes)
7123 (today (time-to-days (current-time)))
7124 (date (calendar-gregorian-from-absolute today))
7125 (win (selected-window))
7126 (kwds org-todo-keywords)
7127 (completion-ignore-case t)
7128 (org-select-this-todo-keyword
7129 (if (stringp arg) arg
7130 (and arg (integerp arg) (> arg 0)
7131 (nth (1- arg) org-todo-keywords))))
7132 rtn rtnall files file pos)
7133 (when (equal arg '(4))
7134 (setq org-select-this-todo-keyword
7135 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
7136 nil t)))
7137 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
7138 (org-prepare-agenda)
7139 (org-set-local 'last-arg arg)
7140 (org-set-local 'org-todo-keywords kwds)
7141 (setq org-agenda-redo-command
7142 '(org-todo-list (or current-prefix-arg last-arg) t))
7143 (setq files (org-agenda-files)
7144 rtnall nil)
7145 (while (setq file (pop files))
7146 (catch 'nextfile
7147 (org-check-agenda-file file)
7148 (setq rtn (org-agenda-get-day-entries file date :todo))
7149 (setq rtnall (append rtnall rtn))))
7150 (insert "Global list of TODO items of type: ")
7151 (add-text-properties (point-min) (1- (point))
7152 (list 'face 'org-level-3))
7153 (setq pos (point))
7154 (insert (or org-select-this-todo-keyword "ALL") "\n")
7155 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7156 (setq pos (point))
7157 (unless org-agenda-multi
7158 (insert
7159 "Available with `N r': (0)ALL "
7160 (let ((n 0))
7161 (mapconcat (lambda (x)
7162 (format "(%d)%s" (setq n (1+ n)) x))
7163 org-todo-keywords " "))
7164 "\n"))
7165 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7166 (when rtnall
7167 (insert (org-finalize-agenda-entries rtnall) "\n"))
7168 (goto-char (point-min))
7169 (org-fit-agenda-window)
7170 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
7171 (org-agenda-align-tags)
7172 (setq buffer-read-only t)
7173 (if (not org-select-agenda-window) (select-window win))))
7175 (defun org-check-agenda-file (file)
7176 "Make sure FILE exists. If not, ask user what to do."
7177 (when (not (file-exists-p file))
7178 (message "non-existent file %s. [R]emove from list or [A]bort?"
7179 (abbreviate-file-name file))
7180 (let ((r (downcase (read-char-exclusive))))
7181 (cond
7182 ((equal r ?r)
7183 (org-remove-file file)
7184 (throw 'nextfile t))
7185 (t (error "Abort"))))))
7187 (defun org-agenda-check-type (error &rest types)
7188 "Check if agenda buffer is of allowed type.
7189 If ERROR is non-nil, throw an error, otherwise just return nil."
7190 (if (memq org-agenda-type types)
7192 (if error
7193 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
7194 nil)))
7196 (defun org-agenda-quit ()
7197 "Exit agenda by removing the window or the buffer."
7198 (interactive)
7199 (let ((buf (current-buffer)))
7200 (if (not (one-window-p)) (delete-window))
7201 (kill-buffer buf)
7202 (org-agenda-maybe-reset-markers 'force)))
7204 (defun org-agenda-exit ()
7205 "Exit agenda by removing the window or the buffer.
7206 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
7207 Org-mode buffers visited directly by the user will not be touched."
7208 (interactive)
7209 (org-release-buffers org-agenda-new-buffers)
7210 (setq org-agenda-new-buffers nil)
7211 (org-agenda-quit))
7213 ;; FIXME: move this function.
7214 (defun org-save-all-org-buffers ()
7215 "Save all Org-mode buffers without user confirmation."
7216 (interactive)
7217 (message "Saving all Org-mode buffers...")
7218 (save-some-buffers t 'org-mode-p)
7219 (message "Saving all Org-mode buffers... done"))
7221 (defun org-agenda-redo ()
7222 "Rebuild Agenda.
7223 When this is the global TODO list, a prefix argument will be interpreted."
7224 (interactive)
7225 (let* ((line (org-current-line))
7226 (window-line (- line (org-current-line (window-start)))))
7227 (message "Rebuilding agenda buffer...")
7228 (eval org-agenda-redo-command)
7229 (message "Rebuilding agenda buffer...done")
7230 (goto-line line)
7231 (recenter window-line)))
7233 (defun org-agenda-goto-today ()
7234 "Go to today."
7235 (interactive)
7236 (org-agenda-check-type t 'timeline 'agenda)
7237 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
7238 (cond
7239 (tdpos (goto-char tdpos))
7240 ((eq org-agenda-type 'agenda)
7241 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
7242 (setf (nth 1 org-agenda-overriding-arguments) nil)
7243 (org-agenda-redo)
7244 (org-agenda-find-today-or-agenda)))
7245 (t (error "Cannot find today")))))
7247 (defun org-agenda-find-today-or-agenda ()
7248 (goto-char
7249 (or (text-property-any (point-min) (point-max) 'org-today t)
7250 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
7251 (point-min))))
7253 (defun org-agenda-later (arg)
7254 "Go forward in time by `org-agenda-ndays' days.
7255 With prefix ARG, go forward that many times `org-agenda-ndays'."
7256 (interactive "p")
7257 (org-agenda-check-type t 'agenda)
7258 (let ((org-agenda-overriding-arguments
7259 (list (car org-agenda-last-arguments)
7260 (+ starting-day (* arg org-agenda-ndays))
7261 nil t)))
7262 (org-agenda-redo)
7263 (org-agenda-find-today-or-agenda)))
7265 (defun org-agenda-earlier (arg)
7266 "Go back in time by `org-agenda-ndays' days.
7267 With prefix ARG, go back that many times `org-agenda-ndays'."
7268 (interactive "p")
7269 (org-agenda-check-type t 'agenda)
7270 (let ((org-agenda-overriding-arguments
7271 (list (car org-agenda-last-arguments)
7272 (- starting-day (* arg org-agenda-ndays))
7273 nil t)))
7274 (org-agenda-redo)
7275 (org-agenda-find-today-or-agenda)))
7277 (defun org-agenda-week-view ()
7278 "Switch to weekly view for agenda."
7279 (interactive)
7280 (org-agenda-check-type t 'agenda)
7281 (if (= org-agenda-ndays 7)
7282 (error "This is already the week view"))
7283 (setq org-agenda-ndays 7)
7284 (let ((org-agenda-overriding-arguments
7285 (list (car org-agenda-last-arguments)
7286 (or (get-text-property (point) 'day)
7287 starting-day)
7288 nil t)))
7289 (org-agenda-redo)
7290 (org-agenda-find-today-or-agenda))
7291 (org-agenda-set-mode-name)
7292 (message "Switched to week view"))
7294 (defun org-agenda-day-view ()
7295 "Switch to daily view for agenda."
7296 (interactive)
7297 (org-agenda-check-type t 'agenda)
7298 (if (= org-agenda-ndays 1)
7299 (error "This is already the day view"))
7300 (setq org-agenda-ndays 1)
7301 (let ((org-agenda-overriding-arguments
7302 (list (car org-agenda-last-arguments)
7303 (or (get-text-property (point) 'day)
7304 starting-day)
7305 nil t)))
7306 (org-agenda-redo)
7307 (org-agenda-find-today-or-agenda))
7308 (org-agenda-set-mode-name)
7309 (message "Switched to day view"))
7311 (defun org-agenda-next-date-line (&optional arg)
7312 "Jump to the next line indicating a date in agenda buffer."
7313 (interactive "p")
7314 (org-agenda-check-type t 'agenda 'timeline)
7315 (beginning-of-line 1)
7316 (if (looking-at "^\\S-") (forward-char 1))
7317 (if (not (re-search-forward "^\\S-" nil t arg))
7318 (progn
7319 (backward-char 1)
7320 (error "No next date after this line in this buffer")))
7321 (goto-char (match-beginning 0)))
7323 (defun org-agenda-previous-date-line (&optional arg)
7324 "Jump to the previous line indicating a date in agenda buffer."
7325 (interactive "p")
7326 (org-agenda-check-type t 'agenda 'timeline)
7327 (beginning-of-line 1)
7328 (if (not (re-search-backward "^\\S-" nil t arg))
7329 (error "No previous date before this line in this buffer")))
7331 ;; Initialize the highlight
7332 (defvar org-hl (org-make-overlay 1 1))
7333 (org-overlay-put org-hl 'face 'highlight)
7335 (defun org-highlight (begin end &optional buffer)
7336 "Highlight a region with overlay."
7337 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7338 org-hl begin end (or buffer (current-buffer))))
7340 (defun org-unhighlight ()
7341 "Detach overlay INDEX."
7342 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7345 (defun org-agenda-follow-mode ()
7346 "Toggle follow mode in an agenda buffer."
7347 (interactive)
7348 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7349 (org-agenda-set-mode-name)
7350 (message "Follow mode is %s"
7351 (if org-agenda-follow-mode "on" "off")))
7353 (defun org-agenda-log-mode ()
7354 "Toggle log mode in an agenda buffer."
7355 (interactive)
7356 (org-agenda-check-type t 'agenda 'timeline)
7357 (setq org-agenda-show-log (not org-agenda-show-log))
7358 (org-agenda-set-mode-name)
7359 (org-agenda-redo)
7360 (message "Log mode is %s"
7361 (if org-agenda-show-log "on" "off")))
7363 (defun org-agenda-toggle-diary ()
7364 "Toggle diary inclusion in an agenda buffer."
7365 (interactive)
7366 (org-agenda-check-type t 'agenda)
7367 (setq org-agenda-include-diary (not org-agenda-include-diary))
7368 (org-agenda-redo)
7369 (org-agenda-set-mode-name)
7370 (message "Diary inclusion turned %s"
7371 (if org-agenda-include-diary "on" "off")))
7373 (defun org-agenda-toggle-time-grid ()
7374 "Toggle time grid in an agenda buffer."
7375 (interactive)
7376 (org-agenda-check-type t 'agenda)
7377 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7378 (org-agenda-redo)
7379 (org-agenda-set-mode-name)
7380 (message "Time-grid turned %s"
7381 (if org-agenda-use-time-grid "on" "off")))
7383 (defun org-agenda-set-mode-name ()
7384 "Set the mode name to indicate all the small mode settings."
7385 (setq mode-name
7386 (concat "Org-Agenda"
7387 (if (equal org-agenda-ndays 1) " Day" "")
7388 (if (equal org-agenda-ndays 7) " Week" "")
7389 (if org-agenda-follow-mode " Follow" "")
7390 (if org-agenda-include-diary " Diary" "")
7391 (if org-agenda-use-time-grid " Grid" "")
7392 (if org-agenda-show-log " Log" "")))
7393 (force-mode-line-update))
7395 (defun org-agenda-post-command-hook ()
7396 (and (eolp) (not (bolp)) (backward-char 1))
7397 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
7398 (if (and org-agenda-follow-mode
7399 (get-text-property (point) 'org-marker))
7400 (org-agenda-show)))
7402 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7404 (defun org-get-entries-from-diary (date)
7405 "Get the (Emacs Calendar) diary entries for DATE."
7406 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7407 (diary-display-hook '(fancy-diary-display))
7408 (list-diary-entries-hook
7409 (cons 'org-diary-default-entry list-diary-entries-hook))
7410 (diary-file-name-prefix-function nil) ; turn this feature off
7411 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7412 entries
7413 (org-disable-agenda-to-diary t))
7414 (save-excursion
7415 (save-window-excursion
7416 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7417 (if (not (get-buffer fancy-diary-buffer))
7418 (setq entries nil)
7419 (with-current-buffer fancy-diary-buffer
7420 (setq buffer-read-only nil)
7421 (if (= (point-max) 1)
7422 ;; No entries
7423 (setq entries nil)
7424 ;; Omit the date and other unnecessary stuff
7425 (org-agenda-cleanup-fancy-diary)
7426 ;; Add prefix to each line and extend the text properties
7427 (if (= (point-max) 1)
7428 (setq entries nil)
7429 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7430 (set-buffer-modified-p nil)
7431 (kill-buffer fancy-diary-buffer)))
7432 (when entries
7433 (setq entries (org-split-string entries "\n"))
7434 (setq entries
7435 (mapcar
7436 (lambda (x)
7437 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7438 ;; Extend the text properties to the beginning of the line
7439 (org-add-props x (text-properties-at (1- (length x)) x)))
7440 entries)))))
7442 (defun org-agenda-cleanup-fancy-diary ()
7443 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7444 This gets rid of the date, the underline under the date, and
7445 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7446 date. It also removes lines that contain only whitespace."
7447 (goto-char (point-min))
7448 (if (looking-at ".*?:[ \t]*")
7449 (progn
7450 (replace-match "")
7451 (re-search-forward "\n=+$" nil t)
7452 (replace-match "")
7453 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7454 (re-search-forward "\n=+$" nil t)
7455 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7456 (goto-char (point-min))
7457 (while (re-search-forward "^ +\n" nil t)
7458 (replace-match ""))
7459 (goto-char (point-min))
7460 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7461 (replace-match "")))
7463 ;; Make sure entries from the diary have the right text properties.
7464 (eval-after-load "diary-lib"
7465 '(if (boundp 'diary-modify-entry-list-string-function)
7466 ;; We can rely on the hook, nothing to do
7468 ;; Hook not avaiable, must use advice to make this work
7469 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7470 "Make the position visible."
7471 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7472 (stringp string)
7473 buffer-file-name)
7474 (setq string (org-modify-diary-entry-string string))))))
7476 (defun org-modify-diary-entry-string (string)
7477 "Add text properties to string, allowing org-mode to act on it."
7478 (org-add-props string nil
7479 'mouse-face 'highlight
7480 'keymap org-agenda-keymap
7481 'help-echo (format "mouse-2 or RET jump to diary file %s"
7482 (abbreviate-file-name buffer-file-name))
7483 'org-agenda-diary-link t
7484 'org-marker (org-agenda-new-marker (point-at-bol))))
7486 (defun org-diary-default-entry ()
7487 "Add a dummy entry to the diary.
7488 Needed to avoid empty dates which mess up holiday display."
7489 ;; Catch the error if dealing with the new add-to-diary-alist
7490 (when org-disable-agenda-to-diary
7491 (condition-case nil
7492 (add-to-diary-list original-date "Org-mode dummy" "")
7493 (error
7494 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7496 (defun org-cycle-agenda-files ()
7497 "Cycle through the files in `org-agenda-files'.
7498 If the current buffer visits an agenda file, find the next one in the list.
7499 If the current buffer does not, find the first agenda file."
7500 (interactive)
7501 (let* ((fs (org-agenda-files t))
7502 (files (append fs (list (car fs))))
7503 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7504 file)
7505 (unless files (error "No agenda files"))
7506 (catch 'exit
7507 (while (setq file (pop files))
7508 (if (equal (file-truename file) tcf)
7509 (when (car files)
7510 (find-file (car files))
7511 (throw 'exit t))))
7512 (find-file (car fs)))))
7514 (defun org-agenda-file-to-end ()
7515 "Move/add the current file to the end of the agenda file list.
7516 If the file is not present in the list, it is appended to the list. If it is
7517 present, it is moved there."
7518 (interactive)
7519 (org-agenda-file-to-front 'to-end))
7521 (defun org-agenda-file-to-front (&optional to-end)
7522 "Move/add the current file to the top of the agenda file list.
7523 If the file is not present in the list, it is added to the front. If it is
7524 present, it is moved there. With optional argument TO-END, add/move to the
7525 end of the list."
7526 (interactive "P")
7527 (let ((file-alist (mapcar (lambda (x)
7528 (cons (file-truename x) x))
7529 (org-agenda-files t)))
7530 (ctf (file-truename buffer-file-name))
7531 x had)
7532 (setq x (assoc ctf file-alist) had x)
7534 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7535 (if to-end
7536 (setq file-alist (append (delq x file-alist) (list x)))
7537 (setq file-alist (cons x (delq x file-alist))))
7538 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7539 (org-install-agenda-files-menu)
7540 (message "File %s to %s of agenda file list"
7541 (if had "moved" "added") (if to-end "end" "front"))))
7543 (defun org-remove-file (&optional file)
7544 "Remove current file from the list of files in variable `org-agenda-files'.
7545 These are the files which are being checked for agenda entries.
7546 Optional argument FILE means, use this file instead of the current."
7547 (interactive)
7548 (let* ((file (or file buffer-file-name))
7549 (true-file (file-truename file))
7550 (afile (abbreviate-file-name file))
7551 (files (delq nil (mapcar
7552 (lambda (x)
7553 (if (equal true-file
7554 (file-truename x))
7555 nil x))
7556 (org-agenda-files t)))))
7557 (if (not (= (length files) (length (org-agenda-files t))))
7558 (progn
7559 (org-store-new-agenda-file-list files)
7560 (org-install-agenda-files-menu)
7561 (message "Removed file: %s" afile))
7562 (message "File was not in list: %s" afile))))
7564 (defun org-file-menu-entry (file)
7565 (vector file (list 'find-file file) t))
7567 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7568 "Return a list of all relevant day numbers from BEG to END buffer positions.
7569 If NO-RANGES is non-nil, include only the start and end dates of a range,
7570 not every single day in the range. If FORCE-TODAY is non-nil, make
7571 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7572 inactive time stamps (those in square brackets) are included.
7573 When EMPTY is non-nil, also include days without any entries."
7574 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7575 dates dates1 date day day1 day2 ts1 ts2)
7576 (if force-today
7577 (setq dates (list (time-to-days (current-time)))))
7578 (save-excursion
7579 (goto-char beg)
7580 (while (re-search-forward re end t)
7581 (setq day (time-to-days (org-time-string-to-time
7582 (substring (match-string 1) 0 10))))
7583 (or (memq day dates) (push day dates)))
7584 (unless no-ranges
7585 (goto-char beg)
7586 (while (re-search-forward org-tr-regexp end t)
7587 (setq ts1 (substring (match-string 1) 0 10)
7588 ts2 (substring (match-string 2) 0 10)
7589 day1 (time-to-days (org-time-string-to-time ts1))
7590 day2 (time-to-days (org-time-string-to-time ts2)))
7591 (while (< (setq day1 (1+ day1)) day2)
7592 (or (memq day1 dates) (push day1 dates)))))
7593 (setq dates (sort dates '<))
7594 (when empty
7595 (while (setq day (pop dates))
7596 (setq day2 (car dates))
7597 (push day dates1)
7598 (when (and day2 empty)
7599 (if (or (eq empty t)
7600 (and (numberp empty) (<= (- day2 day) empty)))
7601 (while (< (setq day (1+ day)) day2)
7602 (push (list day) dates1))
7603 (push (cons :omitted (- day2 day)) dates1))))
7604 (setq dates (nreverse dates1)))
7605 dates)))
7607 ;;;###autoload
7608 (defun org-diary (&rest args)
7609 "Return diary information from org-files.
7610 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7611 It accesses org files and extracts information from those files to be
7612 listed in the diary. The function accepts arguments specifying what
7613 items should be listed. The following arguments are allowed:
7615 :timestamp List the headlines of items containing a date stamp or
7616 date range matching the selected date. Deadlines will
7617 also be listed, on the expiration day.
7619 :deadline List any deadlines past due, or due within
7620 `org-deadline-warning-days'. The listing occurs only
7621 in the diary for *today*, not at any other date. If
7622 an entry is marked DONE, it is no longer listed.
7624 :scheduled List all items which are scheduled for the given date.
7625 The diary for *today* also contains items which were
7626 scheduled earlier and are not yet marked DONE.
7628 :todo List all TODO items from the org-file. This may be a
7629 long list - so this is not turned on by default.
7630 Like deadlines, these entries only show up in the
7631 diary for *today*, not at any other date.
7633 The call in the diary file should look like this:
7635 &%%(org-diary) ~/path/to/some/orgfile.org
7637 Use a separate line for each org file to check. Or, if you omit the file name,
7638 all files listed in `org-agenda-files' will be checked automatically:
7640 &%%(org-diary)
7642 If you don't give any arguments (as in the example above), the default
7643 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7644 also be written as
7646 &%%(org-diary :deadline :timestamp :scheduled)
7648 The function expects the lisp variables `entry' and `date' to be provided
7649 by the caller, because this is how the calendar works. Don't use this
7650 function from a program - use `org-agenda-get-day-entries' instead."
7651 (org-agenda-maybe-reset-markers) ;; FIXME: does this still do the right thing?
7652 (org-compile-prefix-format 'agenda)
7653 (org-set-sorting-strategy 'agenda)
7654 (setq args (or args '(:deadline :scheduled :timestamp)))
7655 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7656 (list entry)
7657 (org-agenda-files t)))
7658 file rtn results)
7659 ;; If this is called during org-agenda, don't return any entries to
7660 ;; the calendar. Org Agenda will list these entries itself.
7661 (if org-disable-agenda-to-diary (setq files nil))
7662 (while (setq file (pop files))
7663 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7664 (setq results (append results rtn)))
7665 (if results
7666 (concat (org-finalize-agenda-entries results) "\n"))))
7667 (defvar org-category-table nil)
7668 (defun org-get-category-table ()
7669 "Get the table of categories and positions in current buffer."
7670 (let (tbl)
7671 (save-excursion
7672 (goto-char (point-min))
7673 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7674 (push (cons (point) (org-trim (match-string 2))) tbl)))
7675 tbl))
7676 (defun org-get-category (&optional pos)
7677 "Get the category applying to position POS."
7678 (if (not org-category-table)
7679 (cond
7680 ((null org-category)
7681 (setq org-category
7682 (if buffer-file-name
7683 (file-name-sans-extension
7684 (file-name-nondirectory buffer-file-name))
7685 "???")))
7686 ((symbolp org-category) (symbol-name org-category))
7687 (t org-category))
7688 (let ((tbl org-category-table)
7689 (pos (or pos (point))))
7690 (while (and tbl (> (caar tbl) pos))
7691 (pop tbl))
7692 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7693 org-category-table))))))
7695 (defun org-agenda-get-day-entries (file date &rest args)
7696 "Does the work for `org-diary' and `org-agenda'.
7697 FILE is the path to a file to be checked for entries. DATE is date like
7698 the one returned by `calendar-current-date'. ARGS are symbols indicating
7699 which kind of entries should be extracted. For details about these, see
7700 the documentation of `org-diary'."
7701 (setq args (or args '(:deadline :scheduled :timestamp)))
7702 (let* ((org-startup-with-deadline-check nil)
7703 (org-startup-folded nil)
7704 (org-startup-align-all-tables nil)
7705 (buffer (if (file-exists-p file)
7706 (org-get-agenda-file-buffer file)
7707 (error "No such file %s" file)))
7708 arg results rtn)
7709 (if (not buffer)
7710 ;; If file does not exist, make sure an error message ends up in diary
7711 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7712 (with-current-buffer buffer
7713 (unless (org-mode-p)
7714 (error "Agenda file %s is not in `org-mode'" file))
7715 (setq org-category-table (org-get-category-table))
7716 (let ((case-fold-search nil))
7717 (save-excursion
7718 (save-restriction
7719 (if org-agenda-restrict
7720 (narrow-to-region org-agenda-restrict-begin
7721 org-agenda-restrict-end)
7722 (widen))
7723 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7724 (while (setq arg (pop args))
7725 (cond
7726 ((and (eq arg :todo)
7727 (equal date (calendar-current-date)))
7728 (setq rtn (org-agenda-get-todos))
7729 (setq results (append results rtn)))
7730 ((eq arg :timestamp)
7731 (setq rtn (org-agenda-get-blocks))
7732 (setq results (append results rtn))
7733 (setq rtn (org-agenda-get-timestamps))
7734 (setq results (append results rtn)))
7735 ((eq arg :scheduled)
7736 (setq rtn (org-agenda-get-scheduled))
7737 (setq results (append results rtn)))
7738 ((eq arg :closed)
7739 (setq rtn (org-agenda-get-closed))
7740 (setq results (append results rtn)))
7741 ((and (eq arg :deadline)
7742 (equal date (calendar-current-date)))
7743 (setq rtn (org-agenda-get-deadlines))
7744 (setq results (append results rtn))))))))
7745 results))))
7747 (defun org-entry-is-done-p ()
7748 "Is the current entry marked DONE?"
7749 (save-excursion
7750 (and (re-search-backward "[\r\n]\\*" nil t)
7751 (looking-at org-nl-done-regexp))))
7753 (defun org-at-date-range-p ()
7754 "Is the cursor inside a date range?"
7755 (interactive)
7756 (save-excursion
7757 (catch 'exit
7758 (let ((pos (point)))
7759 (skip-chars-backward "^<\r\n")
7760 (skip-chars-backward "<")
7761 (and (looking-at org-tr-regexp)
7762 (>= (match-end 0) pos)
7763 (throw 'exit t))
7764 (skip-chars-backward "^<\r\n")
7765 (skip-chars-backward "<")
7766 (and (looking-at org-tr-regexp)
7767 (>= (match-end 0) pos)
7768 (throw 'exit t)))
7769 nil)))
7771 (defun org-agenda-get-todos ()
7772 "Return the TODO information for agenda display."
7773 (let* ((props (list 'face nil
7774 'done-face 'org-done
7775 'org-not-done-regexp org-not-done-regexp
7776 'mouse-face 'highlight
7777 'keymap org-agenda-keymap
7778 'help-echo
7779 (format "mouse-2 or RET jump to org file %s"
7780 (abbreviate-file-name buffer-file-name))))
7781 (regexp (concat "[\n\r]\\*+ *\\("
7782 (if org-select-this-todo-keyword
7783 (concat "\\<\\(" org-select-this-todo-keyword
7784 "\\)\\>")
7785 org-not-done-regexp)
7786 "[^\n\r]*\\)"))
7787 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7788 marker priority category tags
7789 ee txt)
7790 (goto-char (point-min))
7791 (while (re-search-forward regexp nil t)
7792 (catch :skip
7793 (when (and org-agenda-todo-ignore-scheduled
7794 (looking-at sched-re))
7795 ;; FIXME: the following test also happens below, but we need it here
7796 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
7797 (throw :skip nil))
7798 (org-agenda-skip)
7799 (goto-char (match-beginning 1))
7800 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7801 category (org-get-category)
7802 tags (org-get-tags-at (point))
7803 txt (org-format-agenda-item "" (match-string 1) category tags)
7804 priority
7805 (+ (org-get-priority txt)
7806 (if org-todo-kwd-priority-p
7807 (- org-todo-kwd-max-priority -2
7808 (length
7809 (member (match-string 2) org-todo-keywords)))
7810 1)))
7811 (org-add-props txt props
7812 'org-marker marker 'org-hd-marker marker
7813 'priority priority 'category category)
7814 (push txt ee)
7815 (if org-agenda-todo-list-sublevels
7816 (goto-char (match-end 1))
7817 (org-end-of-subtree 'invisible))))
7818 (nreverse ee)))
7820 (defconst org-agenda-no-heading-message
7821 "No heading for this item in buffer or region.")
7823 (defun org-agenda-get-timestamps ()
7824 "Return the date stamp information for agenda display."
7825 (let* ((props (list 'face nil
7826 'org-not-done-regexp org-not-done-regexp
7827 'mouse-face 'highlight
7828 'keymap org-agenda-keymap
7829 'help-echo
7830 (format "mouse-2 or RET jump to org file %s"
7831 (abbreviate-file-name buffer-file-name))))
7832 (regexp (regexp-quote
7833 (substring
7834 (format-time-string
7835 (car org-time-stamp-formats)
7836 (apply 'encode-time ; DATE bound by calendar
7837 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7838 0 11)))
7839 marker hdmarker deadlinep scheduledp donep tmp priority category
7840 ee txt timestr tags)
7841 (goto-char (point-min))
7842 (while (re-search-forward regexp nil t)
7843 (catch :skip
7844 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7845 (org-agenda-skip)
7846 (setq marker (org-agenda-new-marker (match-beginning 0))
7847 category (org-get-category (match-beginning 0))
7848 tmp (buffer-substring (max (point-min)
7849 (- (match-beginning 0)
7850 org-ds-keyword-length))
7851 (match-beginning 0))
7852 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7853 deadlinep (string-match org-deadline-regexp tmp)
7854 scheduledp (string-match org-scheduled-regexp tmp)
7855 donep (org-entry-is-done-p))
7856 (if (string-match ">" timestr)
7857 ;; substring should only run to end of time stamp
7858 (setq timestr (substring timestr 0 (match-end 0))))
7859 (save-excursion
7860 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7861 (progn
7862 (goto-char (match-end 1))
7863 (setq hdmarker (org-agenda-new-marker)
7864 tags (org-get-tags-at))
7865 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7866 (setq txt (org-format-agenda-item
7867 (format "%s%s"
7868 (if deadlinep "Deadline: " "")
7869 (if scheduledp "Scheduled: " ""))
7870 (match-string 1) category tags timestr)))
7871 (setq txt org-agenda-no-heading-message))
7872 (setq priority (org-get-priority txt))
7873 (org-add-props txt props
7874 'org-marker marker 'org-hd-marker hdmarker)
7875 (if deadlinep
7876 (org-add-props txt nil
7877 'face (if donep 'org-done 'org-warning)
7878 'undone-face 'org-warning 'done-face 'org-done
7879 'category category 'priority (+ 100 priority))
7880 (if scheduledp
7881 (org-add-props txt nil
7882 'face 'org-scheduled-today
7883 'undone-face 'org-scheduled-today 'done-face 'org-done
7884 'category category 'priority (+ 99 priority))
7885 (org-add-props txt nil 'priority priority 'category category)))
7886 (push txt ee))
7887 (outline-next-heading)))
7888 (nreverse ee)))
7890 (defun org-agenda-get-closed ()
7891 "Return the logged TODO entries for agenda display."
7892 (let* ((props (list 'mouse-face 'highlight
7893 'org-not-done-regexp org-not-done-regexp
7894 'keymap org-agenda-keymap
7895 'help-echo
7896 (format "mouse-2 or RET jump to org file %s"
7897 (abbreviate-file-name buffer-file-name))))
7898 (regexp (concat
7899 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7900 (regexp-quote
7901 (substring
7902 (format-time-string
7903 (car org-time-stamp-formats)
7904 (apply 'encode-time ; DATE bound by calendar
7905 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7906 1 11))))
7907 marker hdmarker priority category tags closedp
7908 ee txt timestr)
7909 (goto-char (point-min))
7910 (while (re-search-forward regexp nil t)
7911 (catch :skip
7912 (org-agenda-skip)
7913 (setq marker (org-agenda-new-marker (match-beginning 0))
7914 closedp (equal (match-string 1) org-closed-string)
7915 category (org-get-category (match-beginning 0))
7916 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7917 ;; donep (org-entry-is-done-p)
7919 (if (string-match "\\]" timestr)
7920 ;; substring should only run to end of time stamp
7921 (setq timestr (substring timestr 0 (match-end 0))))
7922 (save-excursion
7923 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7924 (progn
7925 (goto-char (match-end 1))
7926 (setq hdmarker (org-agenda-new-marker)
7927 tags (org-get-tags-at))
7928 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7929 (setq txt (org-format-agenda-item
7930 (if closedp "Closed: " "Clocked: ")
7931 (match-string 1) category tags timestr)))
7932 (setq txt org-agenda-no-heading-message))
7933 (setq priority 100000)
7934 (org-add-props txt props
7935 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7936 'priority priority 'category category
7937 'undone-face 'org-warning 'done-face 'org-done)
7938 (push txt ee))
7939 (outline-next-heading)))
7940 (nreverse ee)))
7942 (defun org-agenda-get-deadlines ()
7943 "Return the deadline information for agenda display."
7944 (let* ((wdays org-deadline-warning-days)
7945 (props (list 'mouse-face 'highlight
7946 'org-not-done-regexp org-not-done-regexp
7947 'keymap org-agenda-keymap
7948 'help-echo
7949 (format "mouse-2 or RET jump to org file %s"
7950 (abbreviate-file-name buffer-file-name))))
7951 (regexp org-deadline-time-regexp)
7952 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7953 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7954 d2 diff pos pos1 category tags
7955 ee txt head face)
7956 (goto-char (point-min))
7957 (while (re-search-forward regexp nil t)
7958 (catch :skip
7959 (org-agenda-skip)
7960 (setq pos (1- (match-beginning 1))
7961 d2 (time-to-days
7962 (org-time-string-to-time (match-string 1)))
7963 diff (- d2 d1))
7964 ;; When to show a deadline in the calendar:
7965 ;; If the expiration is within wdays warning time.
7966 ;; Past-due deadlines are only shown on the current date
7967 (if (and (< diff wdays) todayp (not (= diff 0)))
7968 (save-excursion
7969 (setq category (org-get-category))
7970 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7971 (progn
7972 (goto-char (match-end 0))
7973 (setq pos1 (match-end 1))
7974 (setq tags (org-get-tags-at pos1))
7975 (setq head (buffer-substring-no-properties
7976 (point)
7977 (progn (skip-chars-forward "^\r\n")
7978 (point))))
7979 (if (string-match org-looking-at-done-regexp head)
7980 (setq txt nil)
7981 (setq txt (org-format-agenda-item
7982 (format "In %3d d.: " diff) head category tags))))
7983 (setq txt org-agenda-no-heading-message))
7984 (when txt
7985 (setq face (cond ((<= diff 0) 'org-warning)
7986 ((<= diff 5) 'org-upcoming-deadline)
7987 (t nil)))
7988 (org-add-props txt props
7989 'org-marker (org-agenda-new-marker pos)
7990 'org-hd-marker (org-agenda-new-marker pos1)
7991 'priority (+ (- 10 diff) (org-get-priority txt))
7992 'category category
7993 'face face 'undone-face face 'done-face 'org-done)
7994 (push txt ee))))))
7995 ee))
7997 (defun org-agenda-get-scheduled ()
7998 "Return the scheduled information for agenda display."
7999 (let* ((props (list 'face 'org-scheduled-previously
8000 'org-not-done-regexp org-not-done-regexp
8001 'undone-face 'org-scheduled-previously
8002 'done-face 'org-done
8003 'mouse-face 'highlight
8004 'keymap org-agenda-keymap
8005 'help-echo
8006 (format "mouse-2 or RET jump to org file %s"
8007 (abbreviate-file-name buffer-file-name))))
8008 (regexp org-scheduled-time-regexp)
8009 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8010 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8011 d2 diff pos pos1 category tags
8012 ee txt head)
8013 (goto-char (point-min))
8014 (while (re-search-forward regexp nil t)
8015 (catch :skip
8016 (org-agenda-skip)
8017 (setq pos (1- (match-beginning 1))
8018 d2 (time-to-days
8019 (org-time-string-to-time (match-string 1)))
8020 diff (- d2 d1))
8021 ;; When to show a scheduled item in the calendar:
8022 ;; If it is on or past the date.
8023 (if (and (< diff 0) todayp)
8024 (save-excursion
8025 (setq category (org-get-category))
8026 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8027 (progn
8028 (goto-char (match-end 0))
8029 (setq pos1 (match-end 1))
8030 (setq tags (org-get-tags-at))
8031 (setq head (buffer-substring-no-properties
8032 (point)
8033 (progn (skip-chars-forward "^\r\n") (point))))
8034 (if (string-match org-looking-at-done-regexp head)
8035 (setq txt nil)
8036 (setq txt (org-format-agenda-item
8037 (format "Sched.%2dx: " (- 1 diff)) head
8038 category tags))))
8039 (setq txt org-agenda-no-heading-message))
8040 (when txt
8041 (org-add-props txt props
8042 'org-marker (org-agenda-new-marker pos)
8043 'org-hd-marker (org-agenda-new-marker pos1)
8044 'priority (+ (- 5 diff) (org-get-priority txt))
8045 'category category)
8046 (push txt ee))))))
8047 ee))
8049 (defun org-agenda-get-blocks ()
8050 "Return the date-range information for agenda display."
8051 (let* ((props (list 'face nil
8052 'org-not-done-regexp org-not-done-regexp
8053 'mouse-face 'highlight
8054 'keymap org-agenda-keymap
8055 'help-echo
8056 (format "mouse-2 or RET jump to org file %s"
8057 (abbreviate-file-name buffer-file-name))))
8058 (regexp org-tr-regexp)
8059 (d0 (calendar-absolute-from-gregorian date))
8060 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
8061 (goto-char (point-min))
8062 (while (re-search-forward regexp nil t)
8063 (catch :skip
8064 (org-agenda-skip)
8065 (setq pos (point))
8066 (setq timestr (match-string 0)
8067 s1 (match-string 1)
8068 s2 (match-string 2)
8069 d1 (time-to-days (org-time-string-to-time s1))
8070 d2 (time-to-days (org-time-string-to-time s2)))
8071 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
8072 ;; Only allow days between the limits, because the normal
8073 ;; date stamps will catch the limits.
8074 (save-excursion
8075 (setq marker (org-agenda-new-marker (point)))
8076 (setq category (org-get-category))
8077 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8078 (progn
8079 (setq hdmarker (org-agenda-new-marker (match-end 1)))
8080 (goto-char (match-end 1))
8081 (setq tags (org-get-tags-at))
8082 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8083 (setq txt (org-format-agenda-item
8084 (format (if (= d1 d2) "" "(%d/%d): ")
8085 (1+ (- d0 d1)) (1+ (- d2 d1)))
8086 (match-string 1) category tags
8087 (if (= d0 d1) timestr))))
8088 (setq txt org-agenda-no-heading-message))
8089 (org-add-props txt props
8090 'org-marker marker 'org-hd-marker hdmarker
8091 'priority (org-get-priority txt) 'category category)
8092 (push txt ee)))
8093 (goto-char pos)))
8094 ; (outline-next-heading))) ;FIXME: correct to be removed??????
8095 ;; Sort the entries by expiration date.
8096 (nreverse ee)))
8098 (defconst org-plain-time-of-day-regexp
8099 (concat
8100 "\\(\\<[012]?[0-9]"
8101 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8102 "\\(--?"
8103 "\\(\\<[012]?[0-9]"
8104 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8105 "\\)?")
8106 "Regular expression to match a plain time or time range.
8107 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
8108 groups carry important information:
8109 0 the full match
8110 1 the first time, range or not
8111 8 the second time, if it is a range.")
8113 (defconst org-stamp-time-of-day-regexp
8114 (concat
8115 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
8116 "\\([012][0-9]:[0-5][0-9]\\)>"
8117 "\\(--?"
8118 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
8119 "Regular expression to match a timestamp time or time range.
8120 After a match, the following groups carry important information:
8121 0 the full match
8122 1 date plus weekday, for backreferencing to make sure both times on same day
8123 2 the first time, range or not
8124 4 the second time, if it is a range.")
8126 (defvar org-prefix-has-time nil
8127 "A flag, set by `org-compile-prefix-format'.
8128 The flag is set if the currently compiled format contains a `%t'.")
8129 (defvar org-prefix-has-tag nil
8130 "A flag, set by `org-compile-prefix-format'.
8131 The flag is set if the currently compiled format contains a `%T'.")
8133 (defun org-format-agenda-item (extra txt &optional category tags dotime
8134 noprefix)
8135 "Format TXT to be inserted into the agenda buffer.
8136 In particular, it adds the prefix and corresponding text properties. EXTRA
8137 must be a string and replaces the `%s' specifier in the prefix format.
8138 CATEGORY (string, symbol or nil) may be used to overrule the default
8139 category taken from local variable or file name. It will replace the `%c'
8140 specifier in the format. DOTIME, when non-nil, indicates that a
8141 time-of-day should be extracted from TXT for sorting of this entry, and for
8142 the `%t' specifier in the format. When DOTIME is a string, this string is
8143 searched for a time before TXT is. NOPREFIX is a flag and indicates that
8144 only the correctly processes TXT should be returned - this is used by
8145 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
8146 (save-match-data
8147 ;; Diary entries sometimes have extra whitespace at the beginning
8148 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
8149 (let* ((category (or category
8150 org-category
8151 (if buffer-file-name
8152 (file-name-sans-extension
8153 (file-name-nondirectory buffer-file-name))
8154 "")))
8155 (tag (if tags (nth (1- (length tags)) tags) ""))
8156 time ;; needed for the eval of the prefix format
8157 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
8158 (time-of-day (and dotime (org-get-time-of-day ts)))
8159 stamp plain s0 s1 s2 rtn)
8160 (when (and dotime time-of-day org-prefix-has-time)
8161 ;; Extract starting and ending time and move them to prefix
8162 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
8163 (setq plain (string-match org-plain-time-of-day-regexp ts)))
8164 (setq s0 (match-string 0 ts)
8165 s1 (match-string (if plain 1 2) ts)
8166 s2 (match-string (if plain 8 4) ts))
8168 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
8169 ;; them, we might want to remove them there to avoid duplication.
8170 ;; The user can turn this off with a variable.
8171 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
8172 (string-match (concat (regexp-quote s0) " *") txt)
8173 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
8174 (= (match-beginning 0) 0)
8176 (setq txt (replace-match "" nil nil txt))))
8177 ;; Normalize the time(s) to 24 hour
8178 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
8179 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
8181 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
8182 ;; Tags are in the string
8183 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
8184 (and org-agenda-remove-tags-when-in-prefix
8185 org-prefix-has-tag))
8186 (setq txt (replace-match "" t t txt))
8187 (setq txt (replace-match
8188 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
8189 (match-string 2 txt))
8190 t t txt))))
8192 ;; Create the final string
8193 (if noprefix
8194 (setq rtn txt)
8195 ;; Prepare the variables needed in the eval of the compiled format
8196 (setq time (cond (s2 (concat s1 "-" s2))
8197 (s1 (concat s1 "......"))
8198 (t ""))
8199 extra (or extra "")
8200 category (if (symbolp category) (symbol-name category) category))
8201 ;; Evaluate the compiled format
8202 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
8204 ;; And finally add the text properties
8205 (org-add-props rtn nil
8206 'category (downcase category) 'tags tags
8207 'prefix-length (- (length rtn) (length txt))
8208 'time-of-day time-of-day
8209 'dotime dotime))))
8211 (defvar org-agenda-sorting-strategy)
8212 (defvar org-agenda-sorting-strategy-selected nil)
8214 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
8215 (catch 'exit
8216 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
8217 ((and todayp (member 'today (car org-agenda-time-grid))))
8218 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
8219 ((member 'weekly (car org-agenda-time-grid)))
8220 (t (throw 'exit list)))
8221 (let* ((have (delq nil (mapcar
8222 (lambda (x) (get-text-property 1 'time-of-day x))
8223 list)))
8224 (string (nth 1 org-agenda-time-grid))
8225 (gridtimes (nth 2 org-agenda-time-grid))
8226 (req (car org-agenda-time-grid))
8227 (remove (member 'remove-match req))
8228 new time)
8229 (if (and (member 'require-timed req) (not have))
8230 ;; don't show empty grid
8231 (throw 'exit list))
8232 (while (setq time (pop gridtimes))
8233 (unless (and remove (member time have))
8234 (setq time (int-to-string time))
8235 (push (org-format-agenda-item
8236 nil string "" nil
8237 (concat (substring time 0 -2) ":" (substring time -2)))
8238 new)
8239 (put-text-property
8240 1 (length (car new)) 'face 'org-time-grid (car new))))
8241 (if (member 'time-up org-agenda-sorting-strategy-selected)
8242 (append new list)
8243 (append list new)))))
8245 (defun org-compile-prefix-format (key)
8246 "Compile the prefix format into a Lisp form that can be evaluated.
8247 The resulting form is returned and stored in the variable
8248 `org-prefix-format-compiled'."
8249 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8250 (let ((s (cond
8251 ((stringp org-agenda-prefix-format)
8252 org-agenda-prefix-format)
8253 ((assq key org-agenda-prefix-format)
8254 (cdr (assq key org-agenda-prefix-format)))
8255 (t " %-12:c%?-12t% s")))
8256 (start 0)
8257 varform vars var e c f opt)
8258 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8259 s start)
8260 (setq var (cdr (assoc (match-string 4 s)
8261 '(("c" . category) ("t" . time) ("s" . extra)
8262 ("T" . tag))))
8263 c (or (match-string 3 s) "")
8264 opt (match-beginning 1)
8265 start (1+ (match-beginning 0)))
8266 (if (equal var 'time) (setq org-prefix-has-time t))
8267 (if (equal var 'tag) (setq org-prefix-has-tag t))
8268 (setq f (concat "%" (match-string 2 s) "s"))
8269 (if opt
8270 (setq varform
8271 `(if (equal "" ,var)
8273 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8274 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8275 (setq s (replace-match "%s" t nil s))
8276 (push varform vars))
8277 (setq vars (nreverse vars))
8278 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8280 (defun org-set-sorting-strategy (key)
8281 (if (symbolp (car org-agenda-sorting-strategy))
8282 ;; the old format
8283 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
8284 (setq org-agenda-sorting-strategy-selected
8285 (or (cdr (assq key org-agenda-sorting-strategy))
8286 (cdr (assq 'agenda org-agenda-sorting-strategy))
8287 '(time-up category-keep priority-down)))))
8289 (defun org-get-time-of-day (s &optional string mod24)
8290 "Check string S for a time of day.
8291 If found, return it as a military time number between 0 and 2400.
8292 If not found, return nil.
8293 The optional STRING argument forces conversion into a 5 character wide string
8294 HH:MM."
8295 (save-match-data
8296 (when
8298 (string-match
8299 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8300 (string-match
8301 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8302 (let* ((h (string-to-number (match-string 1 s)))
8303 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8304 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8305 (am-p (equal ampm "am"))
8306 (h1 (cond ((not ampm) h)
8307 ((= h 12) (if am-p 0 12))
8308 (t (+ h (if am-p 0 12)))))
8309 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8310 (mod h1 24) h1))
8311 (t0 (+ (* 100 h2) m))
8312 (t1 (concat (if (>= h1 24) "+" " ")
8313 (if (< t0 100) "0" "")
8314 (if (< t0 10) "0" "")
8315 (int-to-string t0))))
8316 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8318 (defun org-finalize-agenda-entries (list &optional nosort)
8319 "Sort and concatenate the agenda items."
8320 (setq list (mapcar 'org-agenda-highlight-todo list))
8321 (if nosort
8322 list
8323 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
8325 (defun org-agenda-highlight-todo (x)
8326 (let (re pl)
8327 (if (eq x 'line)
8328 (save-excursion
8329 (beginning-of-line 1)
8330 (setq re (get-text-property (point) 'org-not-done-regexp))
8331 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
8332 (and (looking-at (concat "[ \t]*" re))
8333 (add-text-properties (match-beginning 0) (match-end 0)
8334 '(face org-todo))))
8335 (setq re (get-text-property 0 'org-not-done-regexp x)
8336 pl (get-text-property 0 'prefix-length x))
8337 (and re (equal (string-match re x pl) pl)
8338 (add-text-properties (match-beginning 0) (match-end 0)
8339 '(face org-todo) x))
8340 x)))
8342 (defsubst org-cmp-priority (a b)
8343 "Compare the priorities of string A and B."
8344 (let ((pa (or (get-text-property 1 'priority a) 0))
8345 (pb (or (get-text-property 1 'priority b) 0)))
8346 (cond ((> pa pb) +1)
8347 ((< pa pb) -1)
8348 (t nil))))
8350 (defsubst org-cmp-category (a b)
8351 "Compare the string values of categories of strings A and B."
8352 (let ((ca (or (get-text-property 1 'category a) ""))
8353 (cb (or (get-text-property 1 'category b) "")))
8354 (cond ((string-lessp ca cb) -1)
8355 ((string-lessp cb ca) +1)
8356 (t nil))))
8358 (defsubst org-cmp-tag (a b)
8359 "Compare the string values of categories of strings A and B."
8360 (let ((ta (car (last (get-text-property 1 'tags a))))
8361 (tb (car (last (get-text-property 1 'tags b)))))
8362 (cond ((not ta) +1)
8363 ((not tb) -1)
8364 ((string-lessp ta tb) -1)
8365 ((string-lessp tb ta) +1)
8366 (t nil))))
8368 (defsubst org-cmp-time (a b)
8369 "Compare the time-of-day values of strings A and B."
8370 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8371 (ta (or (get-text-property 1 'time-of-day a) def))
8372 (tb (or (get-text-property 1 'time-of-day b) def)))
8373 (cond ((< ta tb) -1)
8374 ((< tb ta) +1)
8375 (t nil))))
8377 (defun org-entries-lessp (a b)
8378 "Predicate for sorting agenda entries."
8379 ;; The following variables will be used when the form is evaluated.
8380 (let* ((time-up (org-cmp-time a b))
8381 (time-down (if time-up (- time-up) nil))
8382 (priority-up (org-cmp-priority a b))
8383 (priority-down (if priority-up (- priority-up) nil))
8384 (category-up (org-cmp-category a b))
8385 (category-down (if category-up (- category-up) nil))
8386 (category-keep (if category-up +1 nil))
8387 (tag-up (org-cmp-tag a b))
8388 (tag-down (if tag-up (- tag-up) nil)))
8389 (cdr (assoc
8390 (eval (cons 'or org-agenda-sorting-strategy-selected))
8391 '((-1 . t) (1 . nil) (nil . nil))))))
8393 (defun org-agenda-show-priority ()
8394 "Show the priority of the current item.
8395 This priority is composed of the main priority given with the [#A] cookies,
8396 and by additional input from the age of a schedules or deadline entry."
8397 (interactive)
8398 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8399 (message "Priority is %d" (if pri pri -1000))))
8401 (defun org-agenda-show-tags ()
8402 "Show the tags applicable to the current item."
8403 (interactive)
8404 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8405 (if tags
8406 (message "Tags are :%s:"
8407 (org-no-properties (mapconcat 'identity tags ":")))
8408 (message "No tags associated with this line"))))
8410 (defun org-agenda-goto (&optional highlight)
8411 "Go to the Org-mode file which contains the item at point."
8412 (interactive)
8413 (let* ((marker (or (get-text-property (point) 'org-marker)
8414 (org-agenda-error)))
8415 (buffer (marker-buffer marker))
8416 (pos (marker-position marker)))
8417 (switch-to-buffer-other-window buffer)
8418 (widen)
8419 (goto-char pos)
8420 (when (org-mode-p)
8421 (org-show-hidden-entry)
8422 (save-excursion
8423 (and (outline-next-heading)
8424 (org-flag-heading nil)))) ; show the next heading
8425 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8427 (defun org-agenda-switch-to ()
8428 "Go to the Org-mode file which contains the item at point."
8429 (interactive)
8430 (let* ((marker (or (get-text-property (point) 'org-marker)
8431 (org-agenda-error)))
8432 (buffer (marker-buffer marker))
8433 (pos (marker-position marker)))
8434 (switch-to-buffer buffer)
8435 (delete-other-windows)
8436 (widen)
8437 (goto-char pos)
8438 (when (org-mode-p)
8439 (org-show-hidden-entry)
8440 (save-excursion
8441 (and (outline-next-heading)
8442 (org-flag-heading nil)))))) ; show the next heading
8444 (defun org-agenda-goto-mouse (ev)
8445 "Go to the Org-mode file which contains the item at the mouse click."
8446 (interactive "e")
8447 (mouse-set-point ev)
8448 (org-agenda-goto))
8450 (defun org-agenda-show ()
8451 "Display the Org-mode file which contains the item at point."
8452 (interactive)
8453 (let ((win (selected-window)))
8454 (org-agenda-goto t)
8455 (select-window win)))
8457 (defun org-agenda-recenter (arg)
8458 "Display the Org-mode file which contains the item at point and recenter."
8459 (interactive "P")
8460 (let ((win (selected-window)))
8461 (org-agenda-goto t)
8462 (recenter arg)
8463 (select-window win)))
8465 (defun org-agenda-show-mouse (ev)
8466 "Display the Org-mode file which contains the item at the mouse click."
8467 (interactive "e")
8468 (mouse-set-point ev)
8469 (org-agenda-show))
8471 (defun org-agenda-check-no-diary ()
8472 "Check if the entry is a diary link and abort if yes."
8473 (if (get-text-property (point) 'org-agenda-diary-link)
8474 (org-agenda-error)))
8476 (defun org-agenda-error ()
8477 (error "Command not allowed in this line"))
8479 (defvar org-last-heading-marker (make-marker)
8480 "Marker pointing to the headline that last changed its TODO state
8481 by a remote command from the agenda.")
8483 (defun org-agenda-todo (&optional arg)
8484 "Cycle TODO state of line at point, also in Org-mode file.
8485 This changes the line at point, all other lines in the agenda referring to
8486 the same tree node, and the headline of the tree node in the Org-mode file."
8487 (interactive "P")
8488 (org-agenda-check-no-diary)
8489 (let* ((col (current-column))
8490 (marker (or (get-text-property (point) 'org-marker)
8491 (org-agenda-error)))
8492 (buffer (marker-buffer marker))
8493 (pos (marker-position marker))
8494 (hdmarker (get-text-property (point) 'org-hd-marker))
8495 (buffer-read-only nil)
8496 newhead)
8497 (with-current-buffer buffer
8498 (widen)
8499 (goto-char pos)
8500 (org-show-hidden-entry)
8501 (save-excursion
8502 (and (outline-next-heading)
8503 (org-flag-heading nil))) ; show the next heading
8504 (org-todo arg)
8505 (and (bolp) (forward-char 1))
8506 (setq newhead (org-get-heading))
8507 (save-excursion
8508 (org-back-to-heading)
8509 (move-marker org-last-heading-marker (point))))
8510 (beginning-of-line 1)
8511 (save-excursion
8512 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8513 (move-to-column col)))
8515 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8516 "Change all lines in the agenda buffer which match HDMARKER.
8517 The new content of the line will be NEWHEAD (as modified by
8518 `org-format-agenda-item'). HDMARKER is checked with
8519 `equal' against all `org-hd-marker' text properties in the file.
8520 If FIXFACE is non-nil, the face of each item is modified acording to
8521 the new TODO state."
8522 (let* (props m pl undone-face done-face finish new dotime cat tags)
8523 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8524 (save-excursion
8525 (goto-char (point-max))
8526 (beginning-of-line 1)
8527 (while (not finish)
8528 (setq finish (bobp))
8529 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8530 (equal m hdmarker))
8531 (setq props (text-properties-at (point))
8532 dotime (get-text-property (point) 'dotime)
8533 cat (get-text-property (point) 'category)
8534 tags (get-text-property (point) 'tags)
8535 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8536 pl (get-text-property (point) 'prefix-length)
8537 undone-face (get-text-property (point) 'undone-face)
8538 done-face (get-text-property (point) 'done-face))
8539 (move-to-column pl)
8540 (if (looking-at ".*")
8541 (progn
8542 (replace-match new t t)
8543 (beginning-of-line 1)
8544 (add-text-properties (point-at-bol) (point-at-eol) props)
8545 (when fixface
8546 (add-text-properties
8547 (point-at-bol) (point-at-eol)
8548 (list 'face
8549 (if org-last-todo-state-is-todo
8550 undone-face done-face)))
8551 (org-agenda-highlight-todo 'line))
8552 (org-agenda-align-tags 'line)
8553 (beginning-of-line 1))
8554 (error "Line update did not work")))
8555 (beginning-of-line 0)))))
8557 (defun org-agenda-align-tags (&optional line)
8558 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
8559 (let ((buffer-read-only))
8560 (save-excursion
8561 (goto-char (if line (point-at-bol) (point-min)))
8562 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
8563 (if line (point-at-eol) nil) t)
8564 (delete-region (match-beginning 1) (match-end 1))
8565 (goto-char (match-beginning 1))
8566 (insert (org-add-props
8567 (make-string (max 1 (- org-agenda-align-tags-to-column
8568 (current-column))) ?\ )
8569 (text-properties-at (point))))))))
8571 (defun org-agenda-priority-up ()
8572 "Increase the priority of line at point, also in Org-mode file."
8573 (interactive)
8574 (org-agenda-priority 'up))
8576 (defun org-agenda-priority-down ()
8577 "Decrease the priority of line at point, also in Org-mode file."
8578 (interactive)
8579 (org-agenda-priority 'down))
8581 (defun org-agenda-priority (&optional force-direction)
8582 "Set the priority of line at point, also in Org-mode file.
8583 This changes the line at point, all other lines in the agenda referring to
8584 the same tree node, and the headline of the tree node in the Org-mode file."
8585 (interactive)
8586 (org-agenda-check-no-diary)
8587 (let* ((marker (or (get-text-property (point) 'org-marker)
8588 (org-agenda-error)))
8589 (buffer (marker-buffer marker))
8590 (pos (marker-position marker))
8591 (hdmarker (get-text-property (point) 'org-hd-marker))
8592 (buffer-read-only nil)
8593 newhead)
8594 (with-current-buffer buffer
8595 (widen)
8596 (goto-char pos)
8597 (org-show-hidden-entry)
8598 (save-excursion
8599 (and (outline-next-heading)
8600 (org-flag-heading nil))) ; show the next heading
8601 (funcall 'org-priority force-direction)
8602 (end-of-line 1)
8603 (setq newhead (org-get-heading)))
8604 (org-agenda-change-all-lines newhead hdmarker)
8605 (beginning-of-line 1)))
8607 (defun org-get-tags-at (&optional pos)
8608 "Get a list of all headline tags applicable at POS.
8609 POS defaults to point. If tags are inherited, the list contains
8610 the targets in the same sequence as the headlines appear, i.e.
8611 the tags of the current headline come last."
8612 (interactive)
8613 (let (tags)
8614 (save-excursion
8615 (goto-char (or pos (point)))
8616 (save-match-data
8617 (org-back-to-heading t)
8618 (condition-case nil
8619 (while t
8620 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8621 (setq tags (append (org-split-string
8622 (org-match-string-no-properties 1) ":")
8623 tags)))
8624 (or org-use-tag-inheritance (error ""))
8625 (org-up-heading-all 1))
8626 (error nil))))
8627 tags))
8629 (defun org-agenda-set-tags ()
8630 "Set tags for the current headline."
8631 (interactive)
8632 (org-agenda-check-no-diary)
8633 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8634 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8635 (org-agenda-error)))
8636 (buffer (marker-buffer hdmarker))
8637 (pos (marker-position hdmarker))
8638 (buffer-read-only nil)
8639 newhead)
8640 (with-current-buffer buffer
8641 (widen)
8642 (goto-char pos)
8643 (org-show-hidden-entry)
8644 (save-excursion
8645 (and (outline-next-heading)
8646 (org-flag-heading nil))) ; show the next heading
8647 (call-interactively 'org-set-tags)
8648 (end-of-line 1)
8649 (setq newhead (org-get-heading)))
8650 (org-agenda-change-all-lines newhead hdmarker)
8651 (beginning-of-line 1)))
8653 (defun org-agenda-date-later (arg &optional what)
8654 "Change the date of this item to one day later."
8655 (interactive "p")
8656 (org-agenda-check-type t 'agenda 'timeline)
8657 (org-agenda-check-no-diary)
8658 (let* ((marker (or (get-text-property (point) 'org-marker)
8659 (org-agenda-error)))
8660 (buffer (marker-buffer marker))
8661 (pos (marker-position marker)))
8662 (with-current-buffer buffer
8663 (widen)
8664 (goto-char pos)
8665 (if (not (org-at-timestamp-p))
8666 (error "Cannot find time stamp"))
8667 (org-timestamp-change arg (or what 'day))
8668 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8670 (defun org-agenda-date-earlier (arg &optional what)
8671 "Change the date of this item to one day earlier."
8672 (interactive "p")
8673 (org-agenda-date-later (- arg) what))
8675 (defun org-agenda-date-prompt (arg)
8676 "Change the date of this item. Date is prompted for, with default today.
8677 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8678 be used to request time specification in the time stamp."
8679 (interactive "P")
8680 (org-agenda-check-type t 'agenda 'timeline)
8681 (org-agenda-check-no-diary)
8682 (let* ((marker (or (get-text-property (point) 'org-marker)
8683 (org-agenda-error)))
8684 (buffer (marker-buffer marker))
8685 (pos (marker-position marker)))
8686 (with-current-buffer buffer
8687 (widen)
8688 (goto-char pos)
8689 (if (not (org-at-timestamp-p))
8690 (error "Cannot find time stamp"))
8691 (org-time-stamp arg)
8692 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8694 (defun org-agenda-schedule (arg)
8695 "Schedule the item at point."
8696 (interactive "P")
8697 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8698 (org-agenda-check-no-diary)
8699 (let* ((marker (or (get-text-property (point) 'org-marker)
8700 (org-agenda-error)))
8701 (buffer (marker-buffer marker))
8702 (pos (marker-position marker))
8703 (org-insert-labeled-timestamps-at-point nil)
8705 (with-current-buffer buffer
8706 (widen)
8707 (goto-char pos)
8708 (setq ts (org-schedule))
8709 (message "Item scheduled for %s" ts))))
8711 (defun org-agenda-deadline (arg)
8712 "Schedule the item at point."
8713 (interactive "P")
8714 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8715 (org-agenda-check-no-diary)
8716 (let* ((marker (or (get-text-property (point) 'org-marker)
8717 (org-agenda-error)))
8718 (buffer (marker-buffer marker))
8719 (pos (marker-position marker))
8720 (org-insert-labeled-timestamps-at-point nil)
8722 (with-current-buffer buffer
8723 (widen)
8724 (goto-char pos)
8725 (setq ts (org-deadline))
8726 (message "Deadline for this item set to %s" ts))))
8728 (defun org-get-heading ()
8729 "Return the heading of the current entry, without the stars."
8730 (save-excursion
8731 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8732 (if (and (re-search-backward "[\r\n]\\*" nil t)
8733 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8734 (match-string 1)
8735 "")))
8737 (defun org-agenda-clock-in (&optional arg)
8738 "Start the clock on the currently selected item."
8739 (interactive "P")
8740 (org-agenda-check-no-diary)
8741 (let* ((marker (or (get-text-property (point) 'org-marker)
8742 (org-agenda-error)))
8743 (pos (marker-position marker)))
8744 (with-current-buffer (marker-buffer marker)
8745 (widen)
8746 (goto-char pos)
8747 (org-clock-in))))
8749 (defun org-agenda-diary-entry ()
8750 "Make a diary entry, like the `i' command from the calendar.
8751 All the standard commands work: block, weekly etc."
8752 (interactive)
8753 (org-agenda-check-type t 'agenda 'timeline)
8754 (require 'diary-lib)
8755 (let* ((char (progn
8756 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8757 (read-char-exclusive)))
8758 (cmd (cdr (assoc char
8759 '((?d . insert-diary-entry)
8760 (?w . insert-weekly-diary-entry)
8761 (?m . insert-monthly-diary-entry)
8762 (?y . insert-yearly-diary-entry)
8763 (?a . insert-anniversary-diary-entry)
8764 (?b . insert-block-diary-entry)
8765 (?c . insert-cyclic-diary-entry)))))
8766 (oldf (symbol-function 'calendar-cursor-to-date))
8767 (point (point))
8768 (mark (or (mark t) (point))))
8769 (unless cmd
8770 (error "No command associated with <%c>" char))
8771 (unless (and (get-text-property point 'day)
8772 (or (not (equal ?b char))
8773 (get-text-property mark 'day)))
8774 (error "Don't know which date to use for diary entry"))
8775 ;; We implement this by hacking the `calendar-cursor-to-date' function
8776 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8777 (let ((calendar-mark-ring
8778 (list (calendar-gregorian-from-absolute
8779 (or (get-text-property mark 'day)
8780 (get-text-property point 'day))))))
8781 (unwind-protect
8782 (progn
8783 (fset 'calendar-cursor-to-date
8784 (lambda (&optional error)
8785 (calendar-gregorian-from-absolute
8786 (get-text-property point 'day))))
8787 (call-interactively cmd))
8788 (fset 'calendar-cursor-to-date oldf)))))
8791 (defun org-agenda-execute-calendar-command (cmd)
8792 "Execute a calendar command from the agenda, with the date associated to
8793 the cursor position."
8794 (org-agenda-check-type t 'agenda 'timeline)
8795 (require 'diary-lib)
8796 (unless (get-text-property (point) 'day)
8797 (error "Don't know which date to use for calendar command"))
8798 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8799 (point (point))
8800 (date (calendar-gregorian-from-absolute
8801 (get-text-property point 'day)))
8802 (displayed-day (extract-calendar-day date))
8803 (displayed-month (extract-calendar-month date))
8804 (displayed-year (extract-calendar-year date)))
8805 (unwind-protect
8806 (progn
8807 (fset 'calendar-cursor-to-date
8808 (lambda (&optional error)
8809 (calendar-gregorian-from-absolute
8810 (get-text-property point 'day))))
8811 (call-interactively cmd))
8812 (fset 'calendar-cursor-to-date oldf))))
8814 (defun org-agenda-phases-of-moon ()
8815 "Display the phases of the moon for the 3 months around the cursor date."
8816 (interactive)
8817 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8819 (defun org-agenda-holidays ()
8820 "Display the holidays for the 3 months around the cursor date."
8821 (interactive)
8822 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8824 (defun org-agenda-sunrise-sunset (arg)
8825 "Display sunrise and sunset for the cursor date.
8826 Latitude and longitude can be specified with the variables
8827 `calendar-latitude' and `calendar-longitude'. When called with prefix
8828 argument, latitude and longitude will be prompted for."
8829 (interactive "P")
8830 (let ((calendar-longitude (if arg nil calendar-longitude))
8831 (calendar-latitude (if arg nil calendar-latitude))
8832 (calendar-location-name
8833 (if arg "the given coordinates" calendar-location-name)))
8834 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8836 (defun org-agenda-goto-calendar ()
8837 "Open the Emacs calendar with the date at the cursor."
8838 (interactive)
8839 (org-agenda-check-type t 'agenda 'timeline)
8840 (let* ((day (or (get-text-property (point) 'day)
8841 (error "Don't know which date to open in calendar")))
8842 (date (calendar-gregorian-from-absolute day))
8843 (calendar-move-hook nil)
8844 (view-calendar-holidays-initially nil)
8845 (view-diary-entries-initially nil))
8846 (calendar)
8847 (calendar-goto-date date)))
8849 (defun org-calendar-goto-agenda ()
8850 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8851 This is a command that has to be installed in `calendar-mode-map'."
8852 (interactive)
8853 (org-agenda-list nil (calendar-absolute-from-gregorian
8854 (calendar-cursor-to-date))
8855 nil t))
8857 (defun org-agenda-convert-date ()
8858 (interactive)
8859 (org-agenda-check-type t 'agenda 'timeline)
8860 (let ((day (get-text-property (point) 'day))
8861 date s)
8862 (unless day
8863 (error "Don't know which date to convert"))
8864 (setq date (calendar-gregorian-from-absolute day))
8865 (setq s (concat
8866 "Gregorian: " (calendar-date-string date) "\n"
8867 "ISO: " (calendar-iso-date-string date) "\n"
8868 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8869 "Julian: " (calendar-julian-date-string date) "\n"
8870 "Astron. JD: " (calendar-astro-date-string date)
8871 " (Julian date number at noon UTC)\n"
8872 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8873 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8874 "French: " (calendar-french-date-string date) "\n"
8875 "Mayan: " (calendar-mayan-date-string date) "\n"
8876 "Coptic: " (calendar-coptic-date-string date) "\n"
8877 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8878 "Persian: " (calendar-persian-date-string date) "\n"
8879 "Chinese: " (calendar-chinese-date-string date) "\n"))
8880 (with-output-to-temp-buffer "*Dates*"
8881 (princ s))
8882 (if (fboundp 'fit-window-to-buffer)
8883 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8885 ;;; Tags
8887 (defun org-scan-tags (action matcher &optional todo-only)
8888 "Scan headline tags with inheritance and produce output ACTION.
8889 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8890 evaluated, testing if a given set of tags qualifies a headline for
8891 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8892 are included in the output."
8893 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8894 (mapconcat 'regexp-quote
8895 (nreverse (cdr (reverse org-todo-keywords)))
8896 "\\|")
8897 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8898 (props (list 'face nil
8899 'done-face 'org-done
8900 'undone-face nil
8901 'mouse-face 'highlight
8902 'org-not-done-regexp org-not-done-regexp
8903 'keymap org-agenda-keymap
8904 'help-echo
8905 (format "mouse-2 or RET jump to org file %s"
8906 (abbreviate-file-name buffer-file-name))))
8907 lspos
8908 tags tags-list tags-alist (llast 0) rtn level category i txt
8909 todo marker)
8910 (save-excursion
8911 (goto-char (point-min))
8912 (when (eq action 'sparse-tree) (org-overview))
8913 (while (re-search-forward re nil t)
8914 (catch :skip
8915 (and (eq action 'agenda) (org-agenda-skip))
8916 (setq todo (if (match-end 1) (match-string 2))
8917 tags (if (match-end 4) (match-string 4)))
8918 (goto-char (setq lspos (1+ (match-beginning 0))))
8919 (setq level (funcall outline-level)
8920 category (org-get-category))
8921 (setq i llast llast level)
8922 ;; remove tag lists from same and sublevels
8923 (while (>= i level)
8924 (when (setq entry (assoc i tags-alist))
8925 (setq tags-alist (delete entry tags-alist)))
8926 (setq i (1- i)))
8927 ;; add the nex tags
8928 (when tags
8929 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8930 tags-alist
8931 (cons (cons level tags) tags-alist)))
8932 ;; compile tags for current headline
8933 (setq tags-list
8934 (if org-use-tag-inheritance
8935 (apply 'append (mapcar 'cdr tags-alist))
8936 tags))
8937 (when (and (or (not todo-only) todo)
8938 (eval matcher)
8939 (or (not org-agenda-skip-archived-trees)
8940 (not (member org-archive-tag tags-list))))
8941 ;; list this headline
8942 (if (eq action 'sparse-tree)
8943 (progn
8944 (org-show-hierarchy-above))
8945 (setq txt (org-format-agenda-item
8947 (concat
8948 (if org-tags-match-list-sublevels
8949 (make-string (1- level) ?.) "")
8950 (org-get-heading))
8951 category tags-list))
8952 (goto-char lspos)
8953 (setq marker (org-agenda-new-marker))
8954 (org-add-props txt props
8955 'org-marker marker 'org-hd-marker marker 'category category)
8956 (push txt rtn))
8957 ;; if we are to skip sublevels, jump to end of subtree
8958 (point)
8959 (or org-tags-match-list-sublevels (org-end-of-subtree))))))
8960 (when (and (eq action 'sparse-tree)
8961 (not org-sparse-tree-open-archived-trees))
8962 (org-hide-archived-subtrees (point-min) (point-max)))
8963 (nreverse rtn)))
8965 (defun org-tags-sparse-tree (&optional arg match)
8966 "Create a sparse tree according to tags search string MATCH.
8967 MATCH can contain positive and negative selection of tags, like
8968 \"+WORK+URGENT-WITHBOSS\"."
8969 (interactive "P")
8970 (let ((org-show-following-heading nil)
8971 (org-show-hierarchy-above nil))
8972 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8974 (defun org-make-tags-matcher (match)
8975 "Create the TAGS matcher form for the tags-selecting string MATCH."
8976 (unless match
8977 ;; Get a new match request, with completion
8978 (setq org-last-tags-completion-table
8979 (or (org-get-buffer-tags)
8980 org-last-tags-completion-table))
8981 (setq match (completing-read
8982 "Tags: " 'org-tags-completion-function nil nil nil
8983 'org-tags-history)))
8984 ;; parse the string and create a lisp form
8985 (let ((match0 match) minus tag mm matcher orterms term orlist)
8986 (setq orterms (org-split-string match "|"))
8987 (while (setq term (pop orterms))
8988 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8989 (setq minus (and (match-end 1)
8990 (equal (match-string 1 term) "-"))
8991 tag (match-string 2 term)
8992 term (substring term (match-end 0))
8993 mm (list 'member (downcase tag) 'tags-list)
8994 mm (if minus (list 'not mm) mm))
8995 (push mm matcher))
8996 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8997 orlist)
8998 (setq matcher nil))
8999 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9000 ;; Return the string and lisp forms of the matcher
9001 (cons match0 matcher)))
9003 ;;;###autoload
9004 (defun org-tags-view (&optional todo-only match keep-modes)
9005 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
9006 The prefix arg TODO-ONLY limits the search to TODO entries."
9007 (interactive "P")
9008 (org-compile-prefix-format 'tags)
9009 (org-set-sorting-strategy 'tags)
9010 (let* ((org-agenda-keep-modes keep-modes)
9011 (org-tags-match-list-sublevels
9012 (if todo-only t org-tags-match-list-sublevels))
9013 (win (selected-window))
9014 (completion-ignore-case t)
9015 rtn rtnall files file pos matcher
9016 buffer)
9017 (setq matcher (org-make-tags-matcher match)
9018 match (car matcher) matcher (cdr matcher))
9019 (org-prepare-agenda)
9020 (setq org-agenda-redo-command
9021 (list 'org-tags-view (list 'quote todo-only)
9022 (list 'if 'current-prefix-arg nil match) t))
9023 (setq files (org-agenda-files)
9024 rtnall nil)
9025 (while (setq file (pop files))
9026 (catch 'nextfile
9027 (org-check-agenda-file file)
9028 (setq buffer (if (file-exists-p file)
9029 (org-get-agenda-file-buffer file)
9030 (error "No such file %s" file)))
9031 (if (not buffer)
9032 ;; If file does not exist, merror message to agenda
9033 (setq rtn (list
9034 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
9035 rtnall (append rtnall rtn))
9036 (with-current-buffer buffer
9037 (unless (org-mode-p)
9038 (error "Agenda file %s is not in `org-mode'" file))
9039 (setq org-category-table (org-get-category-table))
9040 (save-excursion
9041 (save-restriction
9042 (if org-agenda-restrict
9043 (narrow-to-region org-agenda-restrict-begin
9044 org-agenda-restrict-end)
9045 (widen))
9046 (setq rtn (org-scan-tags 'agenda matcher todo-only))
9047 (setq rtnall (append rtnall rtn))))))))
9048 (insert "Headlines with TAGS match: ")
9049 (add-text-properties (point-min) (1- (point))
9050 (list 'face 'org-level-3))
9051 (setq pos (point))
9052 (insert match "\n")
9053 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
9054 (setq pos (point))
9055 (unless org-agenda-multi
9056 (insert "Press `C-u r' to search again with new search string\n"))
9057 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
9058 (when rtnall
9059 (insert (org-finalize-agenda-entries rtnall) "\n"))
9060 (goto-char (point-min))
9061 (org-fit-agenda-window)
9062 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
9063 (org-agenda-align-tags)
9064 (setq buffer-read-only t)
9065 (if (not org-select-agenda-window) (select-window win))))
9067 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9068 (defun org-set-tags (&optional arg just-align)
9069 "Set the tags for the current headline.
9070 With prefix ARG, realign all tags in headings in the current buffer."
9071 (interactive "P")
9072 (let* ((re (concat "^" outline-regexp))
9073 (col (current-column))
9074 (current (org-get-tags))
9075 table current-tags inherited-tags ; computed below when needed
9076 tags hd empty invis)
9077 (if arg
9078 (save-excursion
9079 (goto-char (point-min))
9080 (while (re-search-forward re nil t)
9081 (org-set-tags nil t))
9082 (message "All tags realigned to column %d" org-tags-column))
9083 (if just-align
9084 (setq tags current)
9085 (setq table (or org-tag-alist (org-get-buffer-tags))
9086 org-last-tags-completion-table table
9087 current-tags (org-split-string current ":")
9088 inherited-tags (nreverse
9089 (nthcdr (length current-tags)
9090 (nreverse (org-get-tags-at))))
9091 tags
9092 (if (or (eq t org-use-fast-tag-selection)
9093 (and org-use-fast-tag-selection
9094 (delq nil (mapcar 'cdr table))))
9095 (org-fast-tag-selection current-tags inherited-tags table)
9096 (let ((org-add-colon-after-tag-completion t))
9097 (completing-read "Tags: " 'org-tags-completion-function
9098 nil nil current 'org-tags-history))))
9099 (while (string-match "[-+&]+" tags)
9100 (setq tags (replace-match ":" t t tags))))
9102 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
9103 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9104 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9105 (if (equal current "")
9106 (progn
9107 (end-of-line 1)
9108 (or empty (insert " ")))
9109 (beginning-of-line 1)
9110 (setq invis (org-invisible-p))
9111 (looking-at (concat ".*?\\([ \t]*" (regexp-quote current) "\\)[ \t]*"))
9112 (delete-region (match-beginning 1) (match-end 1))
9113 (goto-char (match-beginning 1))
9114 (insert (if empty "" " ")))
9115 (if (equal tags "")
9116 (save-excursion
9117 (beginning-of-line 1)
9118 (skip-chars-forward "*")
9119 (if (= (char-after) ?\ ) (forward-char 1))
9120 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
9121 (replace-match "")))
9122 (move-to-column (max (current-column)
9123 (if (> org-tags-column 0)
9124 org-tags-column
9125 (- (- org-tags-column) (length tags))))
9127 (insert tags)
9128 (if (and (not invis) (org-invisible-p))
9129 (outline-flag-region (point-at-bol) (point) nil)))
9130 (move-to-column col))))
9132 (defun org-tags-completion-function (string predicate &optional flag)
9133 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9134 (confirm (lambda (x) (stringp (car x)))))
9135 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9136 (setq s1 (match-string 1 string)
9137 s2 (match-string 2 string))
9138 (setq s1 "" s2 string))
9139 (cond
9140 ((eq flag nil)
9141 ;; try completion
9142 (setq rtn (try-completion s2 ctable confirm))
9143 (if (stringp rtn)
9144 (concat s1 s2 (substring rtn (length s2))
9145 (if (and org-add-colon-after-tag-completion
9146 (assoc rtn ctable))
9147 ":" "")))
9149 ((eq flag t)
9150 ;; all-completions
9151 (all-completions s2 ctable confirm)
9153 ((eq flag 'lambda)
9154 ;; exact match?
9155 (assoc s2 ctable)))
9158 (defun org-fast-tag-insert (kwd tags face &optional end)
9159 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9160 (insert (format "%-12s" (concat kwd ":"))
9161 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9162 (or end "")))
9164 (defun org-fast-tag-selection (current inherited table)
9165 "Fast tag selection with single keys.
9166 CURRENT is the current list of tags in the headline, INHERITED is the
9167 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9168 possibly with grouping information.
9169 If the keys are nil, a-z are automatically assigned.
9170 Returns the new tags string, or nil to not change the current settings."
9171 (let* ((maxlen (apply 'max (mapcar
9172 (lambda (x)
9173 (if (stringp (car x)) (string-width (car x)) 0))
9174 table)))
9175 (fwidth (+ maxlen 3 1 3))
9176 (ncol (/ (- (window-width) 4) fwidth))
9177 (i-face 'org-done)
9178 (c-face 'org-tag)
9179 tg cnt e c char c1 c2 ntable tbl rtn
9180 groups ingroup)
9181 (save-window-excursion
9182 (delete-other-windows)
9183 (split-window-vertically)
9184 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
9185 (erase-buffer)
9186 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9187 (org-fast-tag-insert "Current" current c-face "\n\n")
9188 (setq tbl table char ?a cnt 0)
9189 (while (setq e (pop tbl))
9190 (cond
9191 ((equal e '(:startgroup))
9192 (push '() groups) (setq ingroup t)
9193 (when (not (= cnt 0))
9194 (setq cnt 0)
9195 (insert "\n"))
9196 (insert "{ "))
9197 ((equal e '(:endgroup))
9198 (setq ingroup nil cnt 0)
9199 (insert "}\n"))
9201 (setq tg (car e) c2 nil)
9202 (if (cdr e)
9203 (setq c (cdr e))
9204 ;; automatically assign a character.
9205 (setq c1 (string-to-char
9206 (downcase (substring
9207 tg (if (= (string-to-char tg) ?@) 1 0)))))
9208 (if (or (rassoc c1 ntable) (rassoc c1 table))
9209 (while (or (rassoc char ntable) (rassoc char table))
9210 (setq char (1+ char)))
9211 (setq c2 c1))
9212 (setq c (or c2 char)))
9213 (if ingroup (push tg (car groups)))
9214 (setq tg (org-add-props tg nil 'face
9215 (cond
9216 ((member tg current) c-face)
9217 ((member tg inherited) i-face)
9218 (t nil))))
9219 (if (and (= cnt 0) (not ingroup)) (insert " "))
9220 (insert "[" c "] " tg (make-string
9221 (- fwidth 4 (length tg)) ?\ ))
9222 (push (cons tg c) ntable)
9223 (when (= (setq cnt (1+ cnt)) ncol)
9224 (insert "\n")
9225 (if ingroup (insert " "))
9226 (setq cnt 0)))))
9227 (setq ntable (nreverse ntable))
9228 (insert "\n")
9229 (goto-char (point-min))
9230 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
9231 (setq rtn
9232 (catch 'exit
9233 (while t
9234 (message "[key]:Toggle SPC: clear current RET accept%s"
9235 (if groups " [!] ignore goups" ""))
9236 (setq c (read-char-exclusive))
9237 (cond
9238 ((= c ?\r) (throw 'exit t))
9239 ((= c ?!)
9240 (setq groups nil)
9241 (goto-char (point-min))
9242 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9243 ((or (= c ?\C-g)
9244 (and (= c ?q) (not (rassoc c ntable))))
9245 (setq quit-flag t))
9246 ((= c ?\ ) (setq current nil))
9247 ((setq e (rassoc c ntable) tg (car e))
9248 (if (member tg current)
9249 (setq current (delete tg current))
9250 (loop for g in groups do
9251 (if (member tg g)
9252 (mapcar (lambda (x)
9253 (setq current (delete x current)))
9254 g)))
9255 (setq current (cons tg current)))))
9256 ;; Create a sorted list
9257 (setq current
9258 (sort current
9259 (lambda (a b)
9260 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9261 (goto-char (point-min))
9262 (beginning-of-line 2)
9263 (delete-region (point) (point-at-eol))
9264 (org-fast-tag-insert "Current" current c-face)
9265 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
9266 (setq tg (match-string 1))
9267 (add-text-properties (match-beginning 1) (match-end 1)
9268 (list 'face
9269 (cond
9270 ((member tg current) c-face)
9271 ((member tg inherited) i-face)
9272 (t nil)))))
9273 (goto-char (point-min)))))
9274 (if rtn
9275 (mapconcat 'identity current ":")
9276 nil))))
9278 (defun org-get-tags ()
9279 "Get the TAGS string in the current headline."
9280 (unless (org-on-heading-p t)
9281 (error "Not on a heading"))
9282 (save-excursion
9283 (beginning-of-line 1)
9284 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9285 (org-match-string-no-properties 1)
9286 "")))
9288 (defun org-get-buffer-tags ()
9289 "Get a table of all tags used in the buffer, for completion."
9290 (let (tags)
9291 (save-excursion
9292 (goto-char (point-min))
9293 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9294 (mapc (lambda (x) (add-to-list 'tags x))
9295 (org-split-string (org-match-string-no-properties 1) ":"))))
9296 (mapcar 'list tags)))
9298 ;;; Link Stuff
9300 (defvar org-create-file-search-functions nil
9301 "List of functions to construct the right search string for a file link.
9302 These functions are called in turn with point at the location to
9303 which the link should point.
9305 A function in the hook should first test if it would like to
9306 handle this file type, for example by checking the major-mode or
9307 the file extension. If it decides not to handle this file, it
9308 should just return nil to give other functions a chance. If it
9309 does handle the file, it must return the search string to be used
9310 when following the link. The search string will be part of the
9311 file link, given after a double colon, and `org-open-at-point'
9312 will automatically search for it. If special measures must be
9313 taken to make the search successful, another function should be
9314 added to the companion hook `org-execute-file-search-functions',
9315 which see.
9317 A function in this hook may also use `setq' to set the variable
9318 `description' to provide a suggestion for the descriptive text to
9319 be used for this link when it gets inserted into an Org-mode
9320 buffer with \\[org-insert-link].")
9322 (defvar org-execute-file-search-functions nil
9323 "List of functions to execute a file search triggered by a link.
9325 Functions added to this hook must accept a single argument, the
9326 search string that was part of the file link, the part after the
9327 double colon. The function must first check if it would like to
9328 handle this search, for example by checking the major-mode or the
9329 file extension. If it decides not to handle this search, it
9330 should just return nil to give other functions a chance. If it
9331 does handle the search, it must return a non-nil value to keep
9332 other functions from trying.
9334 Each function can access the current prefix argument through the
9335 variable `current-prefix-argument'. Note that a single prefix is
9336 used to force opening a link in Emacs, so it may be good to only
9337 use a numeric or double prefix to guide the search function.
9339 In case this is needed, a function in this hook can also restore
9340 the window configuration before `org-open-at-point' was called using:
9342 (set-window-configuration org-window-config-before-follow-link)")
9344 (defun org-find-file-at-mouse (ev)
9345 "Open file link or URL at mouse."
9346 (interactive "e")
9347 (mouse-set-point ev)
9348 (org-open-at-point 'in-emacs))
9350 (defun org-open-at-mouse (ev)
9351 "Open file link or URL at mouse."
9352 (interactive "e")
9353 (mouse-set-point ev)
9354 (org-open-at-point))
9356 (defvar org-window-config-before-follow-link nil
9357 "The window configuration before following a link.
9358 This is saved in case the need arises to restore it.")
9360 (defun org-open-at-point (&optional in-emacs)
9361 "Open link at or after point.
9362 If there is no link at point, this function will search forward up to
9363 the end of the current subtree.
9364 Normally, files will be opened by an appropriate application. If the
9365 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9366 (interactive "P")
9367 (setq org-window-config-before-follow-link (current-window-configuration))
9368 (org-remove-occur-highlights nil nil t)
9369 (if (org-at-timestamp-p)
9370 (org-agenda-list nil (time-to-days (org-time-string-to-time
9371 (substring (match-string 1) 0 10)))
9373 (let (type path link line search (pos (point)))
9374 (catch 'match
9375 (save-excursion
9376 (skip-chars-forward "^]\n\r")
9377 (when (and (re-search-backward "\\[\\[" nil t)
9378 (looking-at org-bracket-link-regexp)
9379 (<= (match-beginning 0) pos)
9380 (>= (match-end 0) pos))
9381 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9382 (while (string-match " *\n *" link)
9383 (setq link (replace-match " " t t link)))
9384 (if (string-match org-link-re-with-space2 link)
9385 (setq type (match-string 1 link)
9386 path (match-string 2 link))
9387 (setq type "thisfile"
9388 path link))
9389 (throw 'match t)))
9391 (when (get-text-property (point) 'org-linked-text)
9392 (setq type "thisfile"
9393 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9394 (1+ (point)) (point))
9395 path (buffer-substring
9396 (previous-single-property-change pos 'org-linked-text)
9397 (next-single-property-change pos 'org-linked-text)))
9398 (throw 'match t))
9400 (save-excursion
9401 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9402 (if (equal (char-before) ?<) (backward-char 1))
9403 (when (or (looking-at org-angle-link-re)
9404 (looking-at org-plain-link-re)
9405 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9406 (re-search-forward org-plain-link-re (point-at-eol) t))
9407 (<= (match-beginning 0) pos)
9408 (>= (match-end 0) pos)))
9409 (setq type (match-string 1)
9410 path (match-string 2))
9411 (throw 'match t)))
9412 (save-excursion
9413 (skip-chars-backward "^ \t\n\r")
9414 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9415 (setq type "tags"
9416 path (match-string 1))
9417 (while (string-match ":" path)
9418 (setq path (replace-match "+" t t path)))
9419 (throw 'match t)))
9420 (save-excursion
9421 (skip-chars-backward "a-zA-Z_")
9422 (when (and (memq 'camel org-activate-links)
9423 (looking-at org-camel-regexp))
9424 (setq type "camel" path (match-string 0))
9425 (if (equal (char-before) ?*)
9426 (setq path (concat "*" path))))
9427 (throw 'match t)))
9428 (unless path
9429 (error "No link found"))
9430 ;; Remove any trailing spaces in path
9431 (if (string-match " +\\'" path)
9432 (setq path (replace-match "" t t path)))
9434 (cond
9436 ((equal type "mailto")
9437 (let ((cmd (car org-link-mailto-program))
9438 (args (cdr org-link-mailto-program)) args1
9439 (address path) (subject "") a)
9440 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9441 (setq address (match-string 1 path)
9442 subject (org-link-escape (match-string 2 path))))
9443 (while args
9444 (cond
9445 ((not (stringp (car args))) (push (pop args) args1))
9446 (t (setq a (pop args))
9447 (if (string-match "%a" a)
9448 (setq a (replace-match address t t a)))
9449 (if (string-match "%s" a)
9450 (setq a (replace-match subject t t a)))
9451 (push a args1))))
9452 (apply cmd (nreverse args1))))
9454 ((member type '("http" "https" "ftp" "news"))
9455 (browse-url (concat type ":" path)))
9457 ((string= type "tags")
9458 (org-tags-view in-emacs path))
9459 ((or (string= type "camel")
9460 (string= type "thisfile"))
9461 (org-mark-ring-push)
9462 (org-link-search
9463 path
9464 (cond ((equal in-emacs '(4)) 'occur)
9465 ((equal in-emacs '(16)) 'org-occur)
9466 (t nil))))
9468 ((string= type "file")
9469 (if (string-match "::\\([0-9]+\\)\\'" path)
9470 (setq line (string-to-number (match-string 1 path))
9471 path (substring path 0 (match-beginning 0)))
9472 (if (string-match "::\\(.+\\)\\'" path)
9473 (setq search (match-string 1 path)
9474 path (substring path 0 (match-beginning 0)))))
9475 (org-open-file path in-emacs line search))
9477 ((string= type "news")
9478 (org-follow-gnus-link path))
9480 ((string= type "bbdb")
9481 (org-follow-bbdb-link path))
9483 ((string= type "info")
9484 (org-follow-info-link path))
9486 ((string= type "gnus")
9487 (let (group article)
9488 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9489 (error "Error in Gnus link"))
9490 (setq group (match-string 1 path)
9491 article (match-string 3 path))
9492 (org-follow-gnus-link group article)))
9494 ((string= type "vm")
9495 (let (folder article)
9496 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9497 (error "Error in VM link"))
9498 (setq folder (match-string 1 path)
9499 article (match-string 3 path))
9500 ;; in-emacs is the prefix arg, will be interpreted as read-only
9501 (org-follow-vm-link folder article in-emacs)))
9503 ((string= type "wl")
9504 (let (folder article)
9505 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9506 (error "Error in Wanderlust link"))
9507 (setq folder (match-string 1 path)
9508 article (match-string 3 path))
9509 (org-follow-wl-link folder article)))
9511 ((string= type "mhe")
9512 (let (folder article)
9513 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9514 (error "Error in MHE link"))
9515 (setq folder (match-string 1 path)
9516 article (match-string 3 path))
9517 (org-follow-mhe-link folder article)))
9519 ((string= type "rmail")
9520 (let (folder article)
9521 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9522 (error "Error in RMAIL link"))
9523 (setq folder (match-string 1 path)
9524 article (match-string 3 path))
9525 (org-follow-rmail-link folder article)))
9527 ((string= type "shell")
9528 (let ((cmd path))
9529 (while (string-match "@{" cmd)
9530 (setq cmd (replace-match "<" t t cmd)))
9531 (while (string-match "@}" cmd)
9532 (setq cmd (replace-match ">" t t cmd)))
9533 (if (or (not org-confirm-shell-link-function)
9534 (funcall org-confirm-shell-link-function
9535 (format "Execute \"%s\" in shell? "
9536 (org-add-props cmd nil
9537 'face 'org-warning))))
9538 (progn
9539 (message "Executing %s" cmd)
9540 (shell-command cmd))
9541 (error "Abort"))))
9543 ((string= type "elisp")
9544 (let ((cmd path))
9545 (if (or (not org-confirm-elisp-link-function)
9546 (funcall org-confirm-elisp-link-function
9547 (format "Execute \"%s\" as elisp? "
9548 (org-add-props cmd nil
9549 'face 'org-warning))))
9550 (message "%s => %s" cmd (eval (read cmd)))
9551 (error "Abort"))))
9554 (browse-url-at-point))))))
9556 (defun org-link-search (s &optional type)
9557 "Search for a link search option.
9558 When S is a CamelCaseWord, search for a target, or for a sentence containing
9559 the words. If S is surrounded by forward slashes, it is interpreted as a
9560 regular expression. In org-mode files, this will create an `org-occur'
9561 sparse tree. In ordinary files, `occur' will be used to list matches.
9562 If the current buffer is in `dired-mode', grep will be used to search
9563 in all files."
9564 (let ((case-fold-search t)
9565 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9566 (pos (point))
9567 (pre "") (post "")
9568 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9569 (cond
9570 ;; First check if there are any special
9571 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9572 ;; Now try the builtin stuff
9573 ((save-excursion
9574 (goto-char (point-min))
9575 (and
9576 (re-search-forward
9577 (concat "<<" (regexp-quote s0) ">>") nil t)
9578 (setq pos (match-beginning 0))))
9579 ;; There is an exact target for this
9580 (goto-char pos))
9581 ((string-match "^/\\(.*\\)/$" s)
9582 ;; A regular expression
9583 (cond
9584 ((org-mode-p)
9585 (org-occur (match-string 1 s)))
9586 ;;((eq major-mode 'dired-mode)
9587 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9588 (t (org-do-occur (match-string 1 s)))))
9589 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9591 ;; A camel or a normal search string
9592 (when (equal (string-to-char s) ?*)
9593 ;; Anchor on headlines, post may include tags.
9594 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9595 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9596 s (substring s 1)))
9597 (remove-text-properties
9598 0 (length s)
9599 '(face nil mouse-face nil keymap nil fontified nil) s)
9600 ;; Make a series of regular expressions to find a match
9601 (setq words
9602 (if camel
9603 (org-camel-to-words s)
9604 (org-split-string s "[ \n\r\t]+"))
9605 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9606 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9607 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9608 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9609 re1 (concat pre re2 post)
9610 re3 (concat pre re4 post)
9611 re5 (concat pre ".*" re4)
9612 re2 (concat pre re2)
9613 re2a (concat pre re2a)
9614 re4 (concat pre re4)
9615 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9616 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9617 re5 "\\)"
9619 (cond
9620 ((eq type 'org-occur) (org-occur reall))
9621 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9622 (t (goto-char (point-min))
9623 (if (or (org-search-not-link re0 nil t)
9624 (org-search-not-link re1 nil t)
9625 (org-search-not-link re2 nil t)
9626 (org-search-not-link re2a nil t)
9627 (org-search-not-link re3 nil t)
9628 (org-search-not-link re4 nil t)
9629 (org-search-not-link re5 nil t)
9631 (goto-char (match-beginning 1))
9632 (goto-char pos)
9633 (error "No match")))))
9635 ;; Normal string-search
9636 (goto-char (point-min))
9637 (if (search-forward s nil t)
9638 (goto-char (match-beginning 0))
9639 (error "No match"))))
9640 (and (org-mode-p) (org-show-hierarchy-above))))
9642 (defun org-search-not-link (&rest args)
9643 "Execute `re-search-forward', but only accept matches that are not a link."
9644 (catch 'exit
9645 (let (p1)
9646 (while (apply 're-search-forward args)
9647 (setq p1 (point))
9648 (if (not (save-match-data
9649 (and (re-search-backward "\\[\\[" nil t)
9650 (looking-at org-bracket-link-regexp)
9651 (<= (match-beginning 0) p1)
9652 (>= (match-end 0) p1))))
9653 (progn (goto-char (match-end 0))
9654 (throw 'exit (point)))
9655 (goto-char (match-end 0)))))))
9657 (defun org-do-occur (regexp &optional cleanup)
9658 "Call the Emacs command `occur'.
9659 If CLEANUP is non-nil, remove the printout of the regular expression
9660 in the *Occur* buffer. This is useful if the regex is long and not useful
9661 to read."
9662 (occur regexp)
9663 (when cleanup
9664 (let ((cwin (selected-window)) win beg end)
9665 (when (setq win (get-buffer-window "*Occur*"))
9666 (select-window win))
9667 (goto-char (point-min))
9668 (when (re-search-forward "match[a-z]+" nil t)
9669 (setq beg (match-end 0))
9670 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9671 (setq end (1- (match-beginning 0)))))
9672 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9673 (goto-char (point-min))
9674 (select-window cwin))))
9676 (defvar org-mark-ring nil
9677 "Mark ring for positions before jumps in Org-mode.")
9678 (defvar org-mark-ring-last-goto nil
9679 "Last position in the mark ring used to go back.")
9680 ;; Fill and close the ring
9681 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9682 (loop for i from 1 to org-mark-ring-length do
9683 (push (make-marker) org-mark-ring))
9684 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9685 org-mark-ring)
9687 (defun org-mark-ring-push (&optional pos buffer)
9688 "Put the current position or POS into the mark ring and rotate it."
9689 (interactive)
9690 (setq pos (or pos (point)))
9691 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9692 (move-marker (car org-mark-ring)
9693 (or pos (point))
9694 (or buffer (current-buffer)))
9695 (message
9696 (substitute-command-keys
9697 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9699 (defun org-mark-ring-goto (&optional n)
9700 "Jump to the previous position in the mark ring.
9701 With prefix arg N, jump back that many stored positions. When
9702 called several times in succession, walk through the entire ring.
9703 Org-mode commands jumping to a different position in the current file,
9704 or to another Org-mode file, automatically push the old position
9705 onto the ring."
9706 (interactive "p")
9707 (let (p m)
9708 (if (eq last-command this-command)
9709 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9710 (setq p org-mark-ring))
9711 (setq org-mark-ring-last-goto p)
9712 (setq m (car p))
9713 (switch-to-buffer (marker-buffer m))
9714 (goto-char m)
9715 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9717 (defun org-camel-to-words (s)
9718 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9719 (let ((case-fold-search nil)
9720 words)
9721 (while (string-match "[a-z][A-Z]" s)
9722 (push (substring s 0 (1+ (match-beginning 0))) words)
9723 (setq s (substring s (1+ (match-beginning 0)))))
9724 (nreverse (cons s words))))
9726 (defun org-remove-angle-brackets (s)
9727 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9728 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9730 (defun org-add-angle-brackets (s)
9731 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9732 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9735 (defun org-follow-bbdb-link (name)
9736 "Follow a BBDB link to NAME."
9737 (require 'bbdb)
9738 (let ((inhibit-redisplay t)
9739 (bbdb-electric-p nil))
9740 (catch 'exit
9741 ;; Exact match on name
9742 (bbdb-name (concat "\\`" name "\\'") nil)
9743 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9744 ;; Exact match on name
9745 (bbdb-company (concat "\\`" name "\\'") nil)
9746 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9747 ;; Partial match on name
9748 (bbdb-name name nil)
9749 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9750 ;; Partial match on company
9751 (bbdb-company name nil)
9752 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9753 ;; General match including network address and notes
9754 (bbdb name nil)
9755 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9756 (delete-window (get-buffer-window "*BBDB*"))
9757 (error "No matching BBDB record")))))
9760 (defun org-follow-info-link (name)
9761 "Follow an info file & node link to NAME."
9762 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9763 (string-match "\\(.*\\)" name))
9764 (progn
9765 (require 'info)
9766 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9767 (Info-find-node (match-string 1 name) (match-string 2 name))
9768 (Info-find-node (match-string 1 name) "Top")))
9769 (message (concat "Could not open: " name))))
9771 (defun org-follow-gnus-link (&optional group article)
9772 "Follow a Gnus link to GROUP and ARTICLE."
9773 (require 'gnus)
9774 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9775 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
9776 (if group (gnus-fetch-group group))
9777 (if article
9778 (or (gnus-summary-goto-article article nil 'force)
9779 (if (fboundp 'gnus-summary-insert-cached-articles)
9780 (progn
9781 (gnus-summary-insert-cached-articles)
9782 (gnus-summary-goto-article article nil 'force))
9783 (message "Message could not be found.")))))
9785 (defun org-follow-vm-link (&optional folder article readonly)
9786 "Follow a VM link to FOLDER and ARTICLE."
9787 (require 'vm)
9788 (setq article (org-add-angle-brackets article))
9789 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9790 ;; ange-ftp or efs or tramp access
9791 (let ((user (or (match-string 1 folder) (user-login-name)))
9792 (host (match-string 2 folder))
9793 (file (match-string 3 folder)))
9794 (cond
9795 ((featurep 'tramp)
9796 ;; use tramp to access the file
9797 (if (featurep 'xemacs)
9798 (setq folder (format "[%s@%s]%s" user host file))
9799 (setq folder (format "/%s@%s:%s" user host file))))
9801 ;; use ange-ftp or efs
9802 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9803 (setq folder (format "/%s@%s:%s" user host file))))))
9804 (when folder
9805 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9806 (sit-for 0.1)
9807 (when article
9808 (vm-select-folder-buffer)
9809 (widen)
9810 (let ((case-fold-search t))
9811 (goto-char (point-min))
9812 (if (not (re-search-forward
9813 (concat "^" "message-id: *" (regexp-quote article))))
9814 (error "Could not find the specified message in this folder"))
9815 (vm-isearch-update)
9816 (vm-isearch-narrow)
9817 (vm-beginning-of-message)
9818 (vm-summarize)))))
9820 (defun org-follow-wl-link (folder article)
9821 "Follow a Wanderlust link to FOLDER and ARTICLE."
9822 (setq article (org-add-angle-brackets article))
9823 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9824 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9825 (wl-summary-redisplay))
9827 (defun org-follow-rmail-link (folder article)
9828 "Follow an RMAIL link to FOLDER and ARTICLE."
9829 (setq article (org-add-angle-brackets article))
9830 (let (message-number)
9831 (save-excursion
9832 (save-window-excursion
9833 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9834 (setq message-number
9835 (save-restriction
9836 (widen)
9837 (goto-char (point-max))
9838 (if (re-search-backward
9839 (concat "^Message-ID:\\s-+" (regexp-quote
9840 (or article "")))
9841 nil t)
9842 (rmail-what-message))))))
9843 (if message-number
9844 (progn
9845 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9846 (rmail-show-message message-number)
9847 message-number)
9848 (error "Message not found"))))
9850 ;; mh-e integration based on planner-mode
9851 (defun org-mhe-get-message-real-folder ()
9852 "Return the name of the current message real folder, so if you use
9853 sequences, it will now work."
9854 (save-excursion
9855 (let* ((folder
9856 (if (equal major-mode 'mh-folder-mode)
9857 mh-current-folder
9858 ;; Refer to the show buffer
9859 mh-show-folder-buffer))
9860 (end-index
9861 (if (boundp 'mh-index-folder)
9862 (min (length mh-index-folder) (length folder))))
9864 ;; a simple test on mh-index-data does not work, because
9865 ;; mh-index-data is always nil in a show buffer.
9866 (if (and (boundp 'mh-index-folder)
9867 (string= mh-index-folder (substring folder 0 end-index)))
9868 (if (equal major-mode 'mh-show-mode)
9869 (save-window-excursion
9870 (when (buffer-live-p (get-buffer folder))
9871 (progn
9872 (pop-to-buffer folder)
9873 (org-mhe-get-message-folder-from-index)
9876 (org-mhe-get-message-folder-from-index)
9878 folder
9882 (defun org-mhe-get-message-folder-from-index ()
9883 "Returns the name of the message folder in a index folder buffer."
9884 (save-excursion
9885 (mh-index-previous-folder)
9886 (re-search-forward "^\\(+.*\\)$" nil t)
9887 (message (match-string 1))))
9889 (defun org-mhe-get-message-folder ()
9890 "Return the name of the current message folder. Be careful if you
9891 use sequences."
9892 (save-excursion
9893 (if (equal major-mode 'mh-folder-mode)
9894 mh-current-folder
9895 ;; Refer to the show buffer
9896 mh-show-folder-buffer)))
9898 (defun org-mhe-get-message-num ()
9899 "Return the number of the current message. Be careful if you
9900 use sequences."
9901 (save-excursion
9902 (if (equal major-mode 'mh-folder-mode)
9903 (mh-get-msg-num nil)
9904 ;; Refer to the show buffer
9905 (mh-show-buffer-message-number))))
9907 (defun org-mhe-get-header (header)
9908 "Return a header of the message in folder mode. This will create a
9909 show buffer for the corresponding message. If you have a more clever
9910 idea..."
9911 (let* ((folder (org-mhe-get-message-folder))
9912 (num (org-mhe-get-message-num))
9913 (buffer (get-buffer-create (concat "show-" folder)))
9914 (header-field))
9915 (with-current-buffer buffer
9916 (mh-display-msg num folder)
9917 (if (equal major-mode 'mh-folder-mode)
9918 (mh-header-display)
9919 (mh-show-header-display))
9920 (set-buffer buffer)
9921 (setq header-field (mh-get-header-field header))
9922 (if (equal major-mode 'mh-folder-mode)
9923 (mh-show)
9924 (mh-show-show))
9925 header-field)))
9927 (defun org-follow-mhe-link (folder article)
9928 "Follow an MHE link to FOLDER and ARTICLE.
9929 If ARTICLE is nil FOLDER is shown. If the configuration variable
9930 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9931 ARTICLE is searched in all folders. Indexed searches (swish++,
9932 namazu, and others supported by MH-E) will always search in all
9933 folders."
9934 (require 'mh-e)
9935 (require 'mh-search)
9936 (require 'mh-utils)
9937 (mh-find-path)
9938 (if (not article)
9939 (mh-visit-folder (mh-normalize-folder-name folder))
9940 (setq article (org-add-angle-brackets article))
9941 (mh-search-choose)
9942 (if (equal mh-searcher 'pick)
9943 (progn
9944 (mh-search folder (list "--message-id" article))
9945 (when (and org-mhe-search-all-folders
9946 (not (org-mhe-get-message-real-folder)))
9947 (kill-this-buffer)
9948 (mh-search "+" (list "--message-id" article))))
9949 (mh-search "+" article))
9950 (if (org-mhe-get-message-real-folder)
9951 (mh-show-msg 1)
9952 (kill-this-buffer)
9953 (error "Message not found"))))
9955 ;; BibTeX links
9957 ;; Use the custom search meachnism to construct and use search strings for
9958 ;; file links to BibTeX database entries.
9960 (defun org-create-file-search-in-bibtex ()
9961 "Create the search string and description for a BibTeX database entry."
9962 (when (eq major-mode 'bibtex-mode)
9963 ;; yes, we want to construct this search string.
9964 ;; Make a good description for this entry, using names, year and the title
9965 ;; Put it into the `description' variable which is dynamically scoped.
9966 (let ((bibtex-autokey-names 1)
9967 (bibtex-autokey-names-stretch 1)
9968 (bibtex-autokey-name-case-convert-function 'identity)
9969 (bibtex-autokey-name-separator " & ")
9970 (bibtex-autokey-additional-names " et al.")
9971 (bibtex-autokey-year-length 4)
9972 (bibtex-autokey-name-year-separator " ")
9973 (bibtex-autokey-titlewords 3)
9974 (bibtex-autokey-titleword-separator " ")
9975 (bibtex-autokey-titleword-case-convert-function 'identity)
9976 (bibtex-autokey-titleword-length 'infty)
9977 (bibtex-autokey-year-title-separator ": "))
9978 (setq description (bibtex-generate-autokey)))
9979 ;; Now parse the entry, get the key and return it.
9980 (save-excursion
9981 (bibtex-beginning-of-entry)
9982 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9984 (defun org-execute-file-search-in-bibtex (s)
9985 "Find the link search string S as a key for a database entry."
9986 (when (eq major-mode 'bibtex-mode)
9987 ;; Yes, we want to do the search in this file.
9988 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9989 (goto-char (point-min))
9990 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9991 (regexp-quote s) "[ \t\n]*,") nil t)
9992 (goto-char (match-beginning 0)))
9993 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9994 ;; Use double prefix to indicate that any web link should be browsed
9995 (let ((b (current-buffer)) (p (point)))
9996 ;; Restore the window configuration because we just use the web link
9997 (set-window-configuration org-window-config-before-follow-link)
9998 (save-excursion (set-buffer b) (goto-char p)
9999 (bibtex-url)))
10000 (recenter 0)) ; Move entry start to beginning of window
10001 ;; return t to indicate that the search is done.
10004 ;; Finally add the functions to the right hooks.
10005 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10006 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10008 ;; end of Bibtex link setup
10010 (defun org-upgrade-old-links (&optional query-description)
10011 "Transfer old <...> style links to new [[...]] style links.
10012 With arg query-description, ask at each match for a description text to use
10013 for this link."
10014 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
10015 (save-excursion
10016 (goto-char (point-min))
10017 (let ((re (concat "\\([^[]\\)<\\("
10018 "\\(" (mapconcat 'identity org-link-types "\\|")
10019 "\\):"
10020 "[^" org-non-link-chars "]+\\)>"))
10021 l1 l2 (cnt 0))
10022 (while (re-search-forward re nil t)
10023 (setq cnt (1+ cnt)
10024 l1 (org-match-string-no-properties 2)
10025 l2 (save-match-data (org-link-escape l1)))
10026 (when query-description (setq l1 (read-string "Desc: " l1)))
10027 (if (equal l1 l2)
10028 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
10029 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
10030 (message "%d matches have beed treated" cnt))))
10032 (defun org-open-file (path &optional in-emacs line search)
10033 "Open the file at PATH.
10034 First, this expands any special file name abbreviations. Then the
10035 configuration variable `org-file-apps' is checked if it contains an
10036 entry for this file type, and if yes, the corresponding command is launched.
10037 If no application is found, Emacs simply visits the file.
10038 With optional argument IN-EMACS, Emacs will visit the file.
10039 Optional LINE specifies a line to go to, optional SEARCH a string to
10040 search for. If LINE or SEARCH is given, the file will always be
10041 opened in Emacs.
10042 If the file does not exist, an error is thrown."
10043 (setq in-emacs (or in-emacs line search))
10044 (let* ((file (if (equal path "")
10045 buffer-file-name
10046 (substitute-in-file-name (expand-file-name path))))
10047 (apps (append org-file-apps (org-default-apps)))
10048 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10049 (dirp (if remp nil (file-directory-p file)))
10050 (dfile (downcase file))
10051 (old-buffer (current-buffer))
10052 (old-pos (point))
10053 (old-mode major-mode)
10054 ext cmd)
10055 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10056 (setq ext (match-string 1 dfile))
10057 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10058 (setq ext (match-string 1 dfile))))
10059 (if in-emacs
10060 (setq cmd 'emacs)
10061 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10062 (and dirp (cdr (assoc 'directory apps)))
10063 (cdr (assoc ext apps))
10064 (cdr (assoc t apps)))))
10065 (when (eq cmd 'mailcap)
10066 (require 'mailcap)
10067 (mailcap-parse-mailcaps)
10068 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10069 (command (mailcap-mime-info mime-type)))
10070 (if (stringp command)
10071 (setq cmd command)
10072 (setq cmd 'emacs))))
10073 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10074 (not (file-exists-p file))
10075 (not org-open-non-existing-files))
10076 (error "No such file: %s" file))
10077 (cond
10078 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10079 ;; Normalize use of quote, this can vary.
10080 (if (string-match "['\"]%s['\"]" cmd)
10081 (setq cmd (replace-match "'%s'" t t cmd)))
10082 (setq cmd (format cmd file))
10083 (save-window-excursion
10084 (shell-command (concat cmd " &"))))
10085 ((or (stringp cmd)
10086 (eq cmd 'emacs))
10087 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
10088 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
10089 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10090 (if line (goto-line line)
10091 (if search (org-link-search search))))
10092 ((consp cmd)
10093 (eval cmd))
10094 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10095 (and (org-mode-p) (eq old-mode 'org-mode)
10096 (or (not (equal old-buffer (current-buffer)))
10097 (not (equal old-pos (point))))
10098 (org-mark-ring-push old-pos old-buffer))))
10100 (defun org-default-apps ()
10101 "Return the default applications for this operating system."
10102 (cond
10103 ((eq system-type 'darwin)
10104 org-file-apps-defaults-macosx)
10105 ((eq system-type 'windows-nt)
10106 org-file-apps-defaults-windowsnt)
10107 (t org-file-apps-defaults-gnu)))
10109 (defun org-expand-file-name (path)
10110 "Replace special path abbreviations and expand the file name."
10111 (expand-file-name path))
10113 (defun org-file-remote-p (file)
10114 "Test whether FILE specifies a location on a remote system.
10115 Return non-nil if the location is indeed remote.
10117 For example, the filename \"/user@host:/foo\" specifies a location
10118 on the system \"/user@host:\"."
10119 (cond ((fboundp 'file-remote-p)
10120 (file-remote-p file))
10121 ((fboundp 'tramp-handle-file-remote-p)
10122 (tramp-handle-file-remote-p file))
10123 ((and (boundp 'ange-ftp-name-format)
10124 (string-match ange-ftp-name-format file))
10126 (t nil)))
10128 (defvar org-insert-link-history nil
10129 "Minibuffer history for links inserted with `org-insert-link'.")
10131 (defvar org-stored-links nil
10132 "Contains the links stored with `org-store-link'.")
10134 ;;;###autoload
10135 (defun org-store-link (arg)
10136 "\\<org-mode-map>Store an org-link to the current location.
10137 This link can later be inserted into an org-buffer with
10138 \\[org-insert-link].
10139 For some link types, a prefix arg is interpreted:
10140 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10141 For file links, arg negates `org-context-in-file-links'."
10142 (interactive "P")
10143 (let (link cpltxt desc description search txt (pos (point)))
10144 (cond
10146 ((eq major-mode 'bbdb-mode)
10147 (setq cpltxt (concat
10148 "bbdb:"
10149 (or (bbdb-record-name (bbdb-current-record))
10150 (bbdb-record-company (bbdb-current-record))))
10151 link (org-make-link cpltxt)))
10153 ((eq major-mode 'Info-mode)
10154 (setq link (org-make-link "info:"
10155 (file-name-nondirectory Info-current-file)
10156 ":" Info-current-node))
10157 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10158 ":" Info-current-node)))
10160 ((eq major-mode 'calendar-mode)
10161 (let ((cd (calendar-cursor-to-date)))
10162 (setq link
10163 (format-time-string
10164 (car org-time-stamp-formats)
10165 (apply 'encode-time
10166 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10167 nil nil nil))))))
10169 ((or (eq major-mode 'vm-summary-mode)
10170 (eq major-mode 'vm-presentation-mode))
10171 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10172 (vm-follow-summary-cursor)
10173 (save-excursion
10174 (vm-select-folder-buffer)
10175 (let* ((message (car vm-message-pointer))
10176 (folder buffer-file-name)
10177 (subject (vm-su-subject message))
10178 (author (vm-su-full-name message))
10179 (message-id (vm-su-message-id message)))
10180 (setq message-id (org-remove-angle-brackets message-id))
10181 (setq folder (abbreviate-file-name folder))
10182 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10183 folder)
10184 (setq folder (replace-match "" t t folder)))
10185 (setq cpltxt (concat author " on: " subject))
10186 (setq link (org-make-link "vm:" folder "#" message-id)))))
10188 ((eq major-mode 'wl-summary-mode)
10189 (let* ((msgnum (wl-summary-message-number))
10190 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10191 msgnum 'message-id))
10192 (wl-message-entity (elmo-msgdb-overview-get-entity
10193 msgnum (wl-summary-buffer-msgdb)))
10194 (author (wl-summary-line-from)) ; FIXME: correct?
10195 (subject "???")) ; FIXME:
10196 (setq message-id (org-remove-angle-brackets message-id))
10197 (setq cpltxt (concat author " on: " subject))
10198 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10199 "#" message-id))))
10201 ((or (equal major-mode 'mh-folder-mode)
10202 (equal major-mode 'mh-show-mode))
10203 (let ((from-header (org-mhe-get-header "From:"))
10204 (to-header (org-mhe-get-header "To:"))
10205 (subject (org-mhe-get-header "Subject:")))
10206 (setq cpltxt (concat from-header " on: " subject))
10207 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10208 (org-remove-angle-brackets
10209 (org-mhe-get-header "Message-Id:"))))))
10211 ((eq major-mode 'rmail-mode)
10212 (save-excursion
10213 (save-restriction
10214 (rmail-narrow-to-non-pruned-header)
10215 (let ((folder buffer-file-name)
10216 (message-id (mail-fetch-field "message-id"))
10217 (author (mail-fetch-field "from"))
10218 (subject (mail-fetch-field "subject")))
10219 (setq message-id (org-remove-angle-brackets message-id))
10220 (setq cpltxt (concat author " on: " subject))
10221 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10223 ((eq major-mode 'gnus-group-mode)
10224 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10225 (gnus-group-group-name)) ; version
10226 ((fboundp 'gnus-group-name)
10227 (gnus-group-name))
10228 (t "???"))))
10229 (setq cpltxt (concat
10230 (if (org-xor arg org-usenet-links-prefer-google)
10231 "http://groups.google.com/groups?group="
10232 "gnus:")
10233 group)
10234 link (org-make-link cpltxt))))
10236 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10237 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10238 (gnus-summary-beginning-of-article)
10239 (let* ((group (car gnus-article-current))
10240 (article (cdr gnus-article-current))
10241 (header (gnus-summary-article-header article))
10242 (author (mail-header-from header))
10243 (message-id (mail-header-id header))
10244 (date (mail-header-date header))
10245 (subject (gnus-summary-subject-string)))
10246 (setq cpltxt (concat author " on: " subject))
10247 (if (org-xor arg org-usenet-links-prefer-google)
10248 (setq link
10249 (concat
10250 cpltxt "\n "
10251 (format "http://groups.google.com/groups?as_umsgid=%s"
10252 (org-fixup-message-id-for-http message-id))))
10253 (setq link (org-make-link "gnus:" group
10254 "#" (number-to-string article))))))
10256 ((eq major-mode 'w3-mode)
10257 (setq cpltxt (url-view-url t)
10258 link (org-make-link cpltxt)))
10259 ((eq major-mode 'w3m-mode)
10260 (setq cpltxt (or w3m-current-title w3m-current-url)
10261 link (org-make-link w3m-current-url)))
10263 ((setq search (run-hook-with-args-until-success
10264 'org-create-file-search-functions))
10265 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10266 "::" search))
10267 (setq cpltxt (or description link)))
10269 ((eq major-mode 'image-mode)
10270 (setq cpltxt (concat "file:"
10271 (abbreviate-file-name buffer-file-name))
10272 link (org-make-link cpltxt)))
10274 ((eq major-mode 'dired-mode)
10275 ;; link to the file in the current line
10276 (setq cpltxt (concat "file:"
10277 (abbreviate-file-name
10278 (expand-file-name
10279 (dired-get-filename nil t))))
10280 link (org-make-link cpltxt)))
10282 ((org-mode-p)
10283 ;; Just link to current headline
10284 (setq cpltxt (concat "file:"
10285 (abbreviate-file-name buffer-file-name)))
10286 ;; Add a context search string
10287 (when (org-xor org-context-in-file-links arg)
10288 ;; Check if we are on a target
10289 (if (save-excursion
10290 (skip-chars-forward "^>\n\r")
10291 (and (re-search-backward "<<" nil t)
10292 (looking-at "<<\\(.*?\\)>>")
10293 (<= (match-beginning 0) pos)
10294 (>= (match-end 0) pos)))
10295 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10296 (setq txt (cond
10297 ((org-on-heading-p) nil)
10298 ((org-region-active-p)
10299 (buffer-substring (region-beginning) (region-end)))
10300 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10301 (when (or (null txt) (string-match "\\S-" txt))
10302 (setq cpltxt
10303 (concat cpltxt "::"
10304 (if org-file-link-context-use-camel-case
10305 (org-make-org-heading-camel txt)
10306 (org-make-org-heading-search-string txt)))
10307 desc "NONE"))))
10308 (if (string-match "::\\'" cpltxt)
10309 (setq cpltxt (substring cpltxt 0 -2)))
10310 (setq link (org-make-link cpltxt)))
10312 (buffer-file-name
10313 ;; Just link to this file here.
10314 (setq cpltxt (concat "file:"
10315 (abbreviate-file-name buffer-file-name)))
10316 ;; Add a context string
10317 (when (org-xor org-context-in-file-links arg)
10318 (setq txt (if (org-region-active-p)
10319 (buffer-substring (region-beginning) (region-end))
10320 (buffer-substring (point-at-bol) (point-at-eol))))
10321 ;; Only use search option if there is some text.
10322 (when (string-match "\\S-" txt)
10323 (setq cpltxt
10324 (concat cpltxt "::"
10325 (if org-file-link-context-use-camel-case
10326 (org-make-org-heading-camel txt)
10327 (org-make-org-heading-search-string txt)))
10328 desc "NONE")))
10329 (setq link (org-make-link cpltxt)))
10331 ((interactive-p)
10332 (error "Cannot link to a buffer which is not visiting a file"))
10334 (t (setq link nil)))
10336 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10337 (setq link (or link cpltxt)
10338 desc (or desc cpltxt))
10339 (if (equal desc "NONE") (setq desc nil))
10341 (if (and (interactive-p) link)
10342 (progn
10343 (setq org-stored-links
10344 (cons (list cpltxt link desc) org-stored-links))
10345 (message "Stored: %s" (or cpltxt link)))
10346 (org-make-link-string link desc))))
10348 (defun org-make-org-heading-search-string (&optional string heading)
10349 "Make search string for STRING or current headline."
10350 (interactive)
10351 (let ((s (or string (org-get-heading))))
10352 (unless (and string (not heading))
10353 ;; We are using a headline, clean up garbage in there.
10354 (if (string-match org-todo-regexp s)
10355 (setq s (replace-match "" t t s)))
10356 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10357 (setq s (replace-match "" t t s)))
10358 (setq s (org-trim s))
10359 (if (string-match (concat "^\\(" org-quote-string "\\|"
10360 org-comment-string "\\)") s)
10361 (setq s (replace-match "" t t s)))
10362 (while (string-match org-ts-regexp s)
10363 (setq s (replace-match "" t t s))))
10364 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10365 (setq s (replace-match " " t t s)))
10366 (or string (setq s (concat "*" s))) ; Add * for headlines
10367 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10369 (defun org-make-org-heading-camel (&optional string heading)
10370 "Make a CamelCase string for STRING or the current headline."
10371 (interactive)
10372 (let ((s (or string (org-get-heading))))
10373 (unless (and string (not heading))
10374 ;; We are using a headline, clean up garbage in there.
10375 (if (string-match org-todo-regexp s)
10376 (setq s (replace-match "" t t s)))
10377 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10378 (setq s (replace-match "" t t s)))
10379 (setq s (org-trim s))
10380 (if (string-match (concat "^\\(" org-quote-string "\\|"
10381 org-comment-string "\\)") s)
10382 (setq s (replace-match "" t t s)))
10383 (while (string-match org-ts-regexp s)
10384 (setq s (replace-match "" t t s))))
10385 (while (string-match "[^a-zA-Z_ \t]+" s)
10386 (setq s (replace-match " " t t s)))
10387 (or string (setq s (concat "*" s))) ; Add * for headlines
10388 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10390 (defun org-make-link (&rest strings)
10391 "Concatenate STRINGS, format resulting string with `org-link-format'."
10392 (format org-link-format (apply 'concat strings)))
10394 (defun org-make-link-string (link &optional description)
10395 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10396 (if (eq org-link-style 'plain)
10397 (if (equal description link)
10398 link
10399 (concat description "\n" link))
10400 (when (stringp description)
10401 ;; Remove brackets from the description, they are fatal.
10402 (while (string-match "\\[\\|\\]" description)
10403 (setq description (replace-match "" t t description))))
10404 (when (equal (org-link-escape link) description)
10405 ;; No description needed, it is identical
10406 (setq description nil))
10407 (when (and (not description)
10408 (not (equal link (org-link-escape link))))
10409 (setq description link))
10410 (concat "[[" (org-link-escape link) "]"
10411 (if description (concat "[" description "]") "")
10412 "]")))
10414 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10415 "Association list of escapes for some characters problematic in links.")
10417 (defun org-link-escape (text)
10418 "Escape charaters in TEXT that are problematic for links."
10419 (when text
10420 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10421 org-link-escape-chars "\\|")))
10422 (while (string-match re text)
10423 (setq text
10424 (replace-match
10425 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10426 t t text)))
10427 text)))
10429 (defun org-link-unescape (text)
10430 "Reverse the action of `org-link-escape'."
10431 (when text
10432 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10433 org-link-escape-chars "\\|")))
10434 (while (string-match re text)
10435 (setq text
10436 (replace-match
10437 (car (rassoc (match-string 0 text) org-link-escape-chars))
10438 t t text)))
10439 text)))
10441 (defun org-xor (a b)
10442 "Exclusive or."
10443 (if a (not b) b))
10445 (defun org-get-header (header)
10446 "Find a header field in the current buffer."
10447 (save-excursion
10448 (goto-char (point-min))
10449 (let ((case-fold-search t) s)
10450 (cond
10451 ((eq header 'from)
10452 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10453 (setq s (match-string 1)))
10454 (while (string-match "\"" s)
10455 (setq s (replace-match "" t t s)))
10456 (if (string-match "[<(].*" s)
10457 (setq s (replace-match "" t t s))))
10458 ((eq header 'message-id)
10459 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10460 (setq s (match-string 1))))
10461 ((eq header 'subject)
10462 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10463 (setq s (match-string 1)))))
10464 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10465 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10466 s)))
10469 (defun org-fixup-message-id-for-http (s)
10470 "Replace special characters in a message id, so it can be used in an http query."
10471 (while (string-match "<" s)
10472 (setq s (replace-match "%3C" t t s)))
10473 (while (string-match ">" s)
10474 (setq s (replace-match "%3E" t t s)))
10475 (while (string-match "@" s)
10476 (setq s (replace-match "%40" t t s)))
10479 (defun org-insert-link (&optional complete-file)
10480 "Insert a link. At the prompt, enter the link.
10482 Completion can be used to select a link previously stored with
10483 `org-store-link'. When the empty string is entered (i.e. if you just
10484 press RET at the prompt), the link defaults to the most recently
10485 stored link. As SPC triggers completion in the minibuffer, you need to
10486 use M-SPC or C-q SPC to force the insertion of a space character.
10488 You will also be prompted for a description, and if one is given, it will
10489 be displayed in the buffer instead of the link.
10491 If there is already a link at point, this command will allow you to edit link
10492 and description parts.
10494 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10495 selected using completion. The path to the file will be relative to
10496 the current directory if the file is in the current directory or a
10497 subdirectory. Otherwise, the link will be the absolute path as
10498 completed in the minibuffer (i.e. normally ~/path/to/file).
10500 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10501 is in the current directory or below.
10502 With three \\[universal-argument] prefixes, negate the meaning of
10503 `org-keep-stored-link-after-insertion'."
10504 (interactive "P")
10505 (let (link desc entry remove file (pos (point)))
10506 (cond
10507 ((save-excursion
10508 (skip-chars-forward "^]\n\r")
10509 (and (re-search-backward "\\[\\[" nil t)
10510 (looking-at org-bracket-link-regexp)
10511 (<= (match-beginning 0) pos)
10512 (>= (match-end 0) pos)))
10513 ;; We do have a link at point, and we are going to edit it.
10514 (setq remove (list (match-beginning 0) (match-end 0)))
10515 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10516 (setq link (read-string "Link: "
10517 (org-link-unescape
10518 (org-match-string-no-properties 1)))))
10519 ((equal complete-file '(4))
10520 ;; Completing read for file names.
10521 (setq file (read-file-name "File: "))
10522 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10523 (pwd1 (file-name-as-directory (abbreviate-file-name
10524 (expand-file-name ".")))))
10525 (cond
10526 ((equal complete-file '(16))
10527 (setq link (org-make-link
10528 "file:"
10529 (abbreviate-file-name (expand-file-name file)))))
10530 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10531 (setq link (org-make-link "file:" (match-string 1 file))))
10532 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10533 (expand-file-name file))
10534 (setq link (org-make-link
10535 "file:" (match-string 1 (expand-file-name file)))))
10536 (t (setq link (org-make-link "file:" file))))))
10538 ;; Read link, with completion for stored links.
10539 (setq link (org-completing-read
10540 "Link: " org-stored-links nil nil nil
10541 org-insert-link-history
10542 (or (car (car org-stored-links)))))
10543 (setq entry (assoc link org-stored-links))
10544 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10545 (not org-keep-stored-link-after-insertion))
10546 (setq org-stored-links (delq (assoc link org-stored-links)
10547 org-stored-links)))
10548 (setq link (if entry (nth 1 entry) link)
10549 desc (or desc (nth 2 entry)))))
10551 (if (string-match org-plain-link-re link)
10552 ;; URL-like link, normalize the use of angular brackets.
10553 (setq link (org-make-link (org-remove-angle-brackets link))))
10555 ;; Check if we are linking to the current file with a search option
10556 ;; If yes, simplify the link by using only the search option.
10557 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10558 (let* ((path (match-string 1 link))
10559 (case-fold-search nil)
10560 (search (match-string 2 link)))
10561 (save-match-data
10562 (if (equal (file-truename buffer-file-name) (file-truename path))
10563 ;; We are linking to this same file, with a search option
10564 (setq link search)))))
10566 ;; Check if we can/should use a relative path. If yes, simplify the link
10567 (when (string-match "\\<file:\\(.*\\)" link)
10568 (let* ((path (match-string 1 link))
10569 (case-fold-search nil))
10570 (cond
10571 ((eq org-link-file-path-type 'absolute)
10572 (setq path (abbreviate-file-name (expand-file-name path))))
10573 ((eq org-link-file-path-type 'noabbrev)
10574 (setq path (expand-file-name path)))
10575 ((eq org-link-file-path-type 'relative)
10576 (setq path (file-relative-name path)))
10578 (save-match-data
10579 (if (string-match (concat "^" (regexp-quote
10580 (file-name-as-directory
10581 (expand-file-name "."))))
10582 (expand-file-name path))
10583 ;; We are linking a file with relative path name.
10584 (setq path (substring (expand-file-name path)
10585 (match-end 0)))))))
10586 (setq link (concat "file:" path))))
10588 (setq desc (read-string "Description: " desc))
10589 (unless (string-match "\\S-" desc) (setq desc nil))
10590 (if remove (apply 'delete-region remove))
10591 (insert (org-make-link-string link desc))))
10593 (defun org-completing-read (&rest args)
10594 (let ((minibuffer-local-completion-map
10595 (copy-keymap minibuffer-local-completion-map)))
10596 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10597 (apply 'completing-read args)))
10599 ;;; Hooks for remember.el
10601 (defvar org-finish-function nil)
10603 ;;;###autoload
10604 (defun org-remember-annotation ()
10605 "Return a link to the current location as an annotation for remember.el.
10606 If you are using Org-mode files as target for data storage with
10607 remember.el, then the annotations should include a link compatible with the
10608 conventions in Org-mode. This function returns such a link."
10609 (org-store-link nil))
10611 (defconst org-remember-help
10612 "Select a destination location for the note.
10613 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10614 RET at beg-of-buf -> Append to file as level 2 headline
10615 RET on headline -> Store as sublevel entry to current headline
10616 <left>/<right> -> before/after current headline, same headings level")
10618 ;;;###autoload
10619 (defun org-remember-apply-template ()
10620 "Initialize *remember* buffer with template, invoke `org-mode'.
10621 This function should be placed into `remember-mode-hook' and in fact requires
10622 to be run from that hook to fucntion properly."
10623 (if org-remember-templates
10625 (let* ((entry (if (= (length org-remember-templates) 1)
10626 (cdar org-remember-templates)
10627 (message "Select template: %s"
10628 (mapconcat
10629 (lambda (x) (char-to-string (car x)))
10630 org-remember-templates " "))
10631 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10632 (tpl (car entry))
10633 (file (if (consp (cdr entry)) (nth 1 entry)))
10634 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10635 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10636 (v-u (concat "[" (substring v-t 1 -1) "]"))
10637 (v-U (concat "[" (substring v-T 1 -1) "]"))
10638 (v-a annotation) ; defined in `remember-mode'
10639 (v-i initial) ; defined in `remember-mode'
10640 (v-n user-full-name)
10642 (unless tpl (setq tpl "") (message "No template") (ding))
10643 (insert tpl) (goto-char (point-min))
10644 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10645 (when (and initial (equal (match-string 0) "%i"))
10646 (save-match-data
10647 (let* ((lead (buffer-substring
10648 (point-at-bol) (match-beginning 0))))
10649 (setq v-i (mapconcat 'identity
10650 (org-split-string initial "\n")
10651 (concat "\n" lead))))))
10652 (replace-match
10653 (or (eval (intern (concat "v-" (match-string 1)))) "")
10654 t t))
10655 (let ((org-startup-folded nil)
10656 (org-startup-with-deadline-check nil))
10657 (org-mode))
10658 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10659 (org-set-local 'org-default-notes-file file))
10660 (goto-char (point-min))
10661 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10662 (let ((org-startup-folded nil)
10663 (org-startup-with-deadline-check nil))
10664 (org-mode)))
10665 (org-set-local 'org-finish-function 'remember-buffer))
10667 ;;;###autoload
10668 (defun org-remember-handler ()
10669 "Store stuff from remember.el into an org file.
10670 First prompts for an org file. If the user just presses return, the value
10671 of `org-default-notes-file' is used.
10672 Then the command offers the headings tree of the selected file in order to
10673 file the text at a specific location.
10674 You can either immediately press RET to get the note appended to the
10675 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10676 find a better place. Then press RET or <left> or <right> in insert the note.
10678 Key Cursor position Note gets inserted
10679 -----------------------------------------------------------------------------
10680 RET buffer-start as level 2 heading at end of file
10681 RET on headline as sublevel of the heading at cursor
10682 RET no heading at cursor position, level taken from context.
10683 Or use prefix arg to specify level manually.
10684 <left> on headline as same level, before current heading
10685 <right> on headline as same level, after current heading
10687 So the fastest way to store the note is to press RET RET to append it to
10688 the default file. This way your current train of thought is not
10689 interrupted, in accordance with the principles of remember.el. But with
10690 little extra effort, you can push it directly to the correct location.
10692 Before being stored away, the function ensures that the text has a
10693 headline, i.e. a first line that starts with a \"*\". If not, a headline
10694 is constructed from the current date and some additional data.
10696 If the variable `org-adapt-indentation' is non-nil, the entire text is
10697 also indented so that it starts in the same column as the headline
10698 \(i.e. after the stars).
10700 See also the variable `org-reverse-note-order'."
10701 (catch 'quit
10702 (let* ((txt (buffer-substring (point-min) (point-max)))
10703 (fastp current-prefix-arg)
10704 (file (if fastp org-default-notes-file (org-get-org-file)))
10705 (visiting (find-buffer-visiting file))
10706 (org-startup-with-deadline-check nil)
10707 (org-startup-folded nil)
10708 (org-startup-align-all-tables nil)
10709 spos level indent reversed)
10710 ;; Modify text so that it becomes a nice subtree which can be inserted
10711 ;; into an org tree.
10712 (let* ((lines (split-string txt "\n"))
10713 first)
10714 ;; remove empty lines at the beginning
10715 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10716 (setq lines (cdr lines)))
10717 (setq first (car lines) lines (cdr lines))
10718 (if (string-match "^\\*+" first)
10719 ;; Is already a headline
10720 (setq indent nil)
10721 ;; We need to add a headline: Use time and first buffer line
10722 (setq lines (cons first lines)
10723 first (concat "* " (current-time-string)
10724 " (" (remember-buffer-desc) ")")
10725 indent " "))
10726 (if (and org-adapt-indentation indent)
10727 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10728 (setq txt (concat first "\n"
10729 (mapconcat 'identity lines "\n"))))
10730 ;; Find the file
10731 (if (not visiting)
10732 (find-file-noselect file))
10733 (with-current-buffer (get-file-buffer file)
10734 (save-excursion (and (goto-char (point-min))
10735 (not (re-search-forward "^\\* " nil t))
10736 (insert "\n* Notes\n")))
10737 (setq reversed (org-notes-order-reversed-p))
10738 (save-excursion
10739 (save-restriction
10740 (widen)
10741 ;; Ask the User for a location
10742 (setq spos (if fastp 1 (org-get-location
10743 (current-buffer)
10744 org-remember-help)))
10745 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10746 ; not handle this note
10747 (goto-char spos)
10748 (cond ((bobp)
10749 ;; Put it at the start or end, as level 2
10750 (save-restriction
10751 (widen)
10752 (goto-char (if reversed (point-min) (point-max)))
10753 (if (not (bolp)) (newline))
10754 (org-paste-subtree 2 txt)))
10755 ((and (org-on-heading-p nil) (not current-prefix-arg))
10756 ;; Put it below this entry, at the beg/end of the subtree
10757 (org-back-to-heading)
10758 (setq level (funcall outline-level))
10759 (if reversed
10760 (outline-end-of-heading)
10761 (outline-end-of-subtree))
10762 (if (not (bolp)) (newline))
10763 (beginning-of-line 1)
10764 (org-paste-subtree (1+ level) txt))
10766 ;; Put it right there, with automatic level determined by
10767 ;; org-paste-subtree or from prefix arg
10768 (org-paste-subtree current-prefix-arg txt)))
10769 (when remember-save-after-remembering
10770 (save-buffer)
10771 (if (not visiting) (kill-buffer (current-buffer)))))))))
10772 t) ;; return t to indicate that we took care of this note.
10774 (defun org-get-org-file ()
10775 "Read a filename, with default directory `org-directory'."
10776 (let ((default (or org-default-notes-file remember-data-file)))
10777 (read-file-name (format "File name [%s]: " default)
10778 (file-name-as-directory org-directory)
10779 default)))
10781 (defun org-notes-order-reversed-p ()
10782 "Check if the current file should receive notes in reversed order."
10783 (cond
10784 ((not org-reverse-note-order) nil)
10785 ((eq t org-reverse-note-order) t)
10786 ((not (listp org-reverse-note-order)) nil)
10787 (t (catch 'exit
10788 (let ((all org-reverse-note-order)
10789 entry)
10790 (while (setq entry (pop all))
10791 (if (string-match (car entry) buffer-file-name)
10792 (throw 'exit (cdr entry))))
10793 nil)))))
10795 ;;; Tables
10797 ;; Watch out: Here we are talking about two different kind of tables.
10798 ;; Most of the code is for the tables created with the Org-mode table editor.
10799 ;; Sometimes, we talk about tables created and edited with the table.el
10800 ;; Emacs package. We call the former org-type tables, and the latter
10801 ;; table.el-type tables.
10804 (defun org-before-change-function (beg end)
10805 "Every change indicates that a table might need an update."
10806 (setq org-table-may-need-update t))
10808 (defconst org-table-line-regexp "^[ \t]*|"
10809 "Detects an org-type table line.")
10810 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10811 "Detects an org-type table line.")
10812 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10813 "Detects a table line marked for automatic recalculation.")
10814 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10815 "Detects a table line marked for automatic recalculation.")
10816 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10817 "Detects a table line marked for automatic recalculation.")
10818 (defconst org-table-hline-regexp "^[ \t]*|-"
10819 "Detects an org-type table hline.")
10820 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10821 "Detects a table-type table hline.")
10822 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10823 "Detects an org-type or table-type table.")
10824 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10825 "Searching from within a table (any type) this finds the first line
10826 outside the table.")
10827 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10828 "Searching from within a table (any type) this finds the first line
10829 outside the table.")
10831 (defun org-table-create-with-table.el ()
10832 "Use the table.el package to insert a new table.
10833 If there is already a table at point, convert between Org-mode tables
10834 and table.el tables."
10835 (interactive)
10836 (require 'table)
10837 (cond
10838 ((org-at-table.el-p)
10839 (if (y-or-n-p "Convert table to Org-mode table? ")
10840 (org-table-convert)))
10841 ((org-at-table-p)
10842 (if (y-or-n-p "Convert table to table.el table? ")
10843 (org-table-convert)))
10844 (t (call-interactively 'table-insert))))
10846 (defun org-table-create-or-convert-from-region (arg)
10847 "Convert region to table, or create an empty table.
10848 If there is an active region, convert it to a table. If there is no such
10849 region, create an empty table."
10850 (interactive "P")
10851 (if (org-region-active-p)
10852 (org-table-convert-region (region-beginning) (region-end) arg)
10853 (org-table-create arg)))
10855 (defun org-table-create (&optional size)
10856 "Query for a size and insert a table skeleton.
10857 SIZE is a string Columns x Rows like for example \"3x2\"."
10858 (interactive "P")
10859 (unless size
10860 (setq size (read-string
10861 (concat "Table size Columns x Rows [e.g. "
10862 org-table-default-size "]: ")
10863 "" nil org-table-default-size)))
10865 (let* ((pos (point))
10866 (indent (make-string (current-column) ?\ ))
10867 (split (org-split-string size " *x *"))
10868 (rows (string-to-number (nth 1 split)))
10869 (columns (string-to-number (car split)))
10870 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10871 "\n")))
10872 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10873 (point-at-bol) (point)))
10874 (beginning-of-line 1)
10875 (newline))
10876 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10877 (dotimes (i rows) (insert line))
10878 (goto-char pos)
10879 (if (> rows 1)
10880 ;; Insert a hline after the first row.
10881 (progn
10882 (end-of-line 1)
10883 (insert "\n|-")
10884 (goto-char pos)))
10885 (org-table-align)))
10887 (defun org-table-convert-region (beg0 end0 &optional nspace)
10888 "Convert region to a table.
10889 The region goes from BEG0 to END0, but these borders will be moved
10890 slightly, to make sure a beginning of line in the first line is included.
10891 When NSPACE is non-nil, it indicates the minimum number of spaces that
10892 separate columns (default: just one space)."
10893 (interactive "rP")
10894 (let* ((beg (min beg0 end0))
10895 (end (max beg0 end0))
10896 (tabsep t)
10898 (goto-char beg)
10899 (beginning-of-line 1)
10900 (setq beg (move-marker (make-marker) (point)))
10901 (goto-char end)
10902 (if (bolp) (backward-char 1) (end-of-line 1))
10903 (setq end (move-marker (make-marker) (point)))
10904 ;; Lets see if this is tab-separated material. If every nonempty line
10905 ;; contains a tab, we will assume that it is tab-separated material
10906 (if nspace
10907 (setq tabsep nil)
10908 (goto-char beg)
10909 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10910 (if nspace (setq tabsep nil))
10911 (if tabsep
10912 (setq re "^\\|\t")
10913 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10914 (max 1 (prefix-numeric-value nspace)))))
10915 (goto-char beg)
10916 (while (re-search-forward re end t)
10917 (replace-match "|" t t))
10918 (goto-char beg)
10919 (insert " ")
10920 (org-table-align)))
10922 (defun org-table-import (file arg)
10923 "Import FILE as a table.
10924 The file is assumed to be tab-separated. Such files can be produced by most
10925 spreadsheet and database applications. If no tabs (at least one per line)
10926 are found, lines will be split on whitespace into fields."
10927 (interactive "f\nP")
10928 (or (bolp) (newline))
10929 (let ((beg (point))
10930 (pm (point-max)))
10931 (insert-file-contents file)
10932 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10934 (defun org-table-export ()
10935 "Export table as a tab-separated file.
10936 Such a file can be imported into a spreadsheet program like Excel."
10937 (interactive)
10938 (let* ((beg (org-table-begin))
10939 (end (org-table-end))
10940 (table (buffer-substring beg end))
10941 (file (read-file-name "Export table to: "))
10942 buf)
10943 (unless (or (not (file-exists-p file))
10944 (y-or-n-p (format "Overwrite file %s? " file)))
10945 (error "Abort"))
10946 (with-current-buffer (find-file-noselect file)
10947 (setq buf (current-buffer))
10948 (erase-buffer)
10949 (fundamental-mode)
10950 (insert table)
10951 (goto-char (point-min))
10952 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10953 (replace-match "" t t)
10954 (end-of-line 1))
10955 (goto-char (point-min))
10956 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10957 (replace-match "" t t)
10958 (goto-char (min (1+ (point)) (point-max))))
10959 (goto-char (point-min))
10960 (while (re-search-forward "^-[-+]*$" nil t)
10961 (replace-match "")
10962 (if (looking-at "\n")
10963 (delete-char 1)))
10964 (goto-char (point-min))
10965 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10966 (replace-match "\t" t t))
10967 (save-buffer))
10968 (kill-buffer buf)))
10970 (defvar org-table-aligned-begin-marker (make-marker)
10971 "Marker at the beginning of the table last aligned.
10972 Used to check if cursor still is in that table, to minimize realignment.")
10973 (defvar org-table-aligned-end-marker (make-marker)
10974 "Marker at the end of the table last aligned.
10975 Used to check if cursor still is in that table, to minimize realignment.")
10976 (defvar org-table-last-alignment nil
10977 "List of flags for flushright alignment, from the last re-alignment.
10978 This is being used to correctly align a single field after TAB or RET.")
10979 (defvar org-table-last-column-widths nil
10980 "List of max width of fields in each column.
10981 This is being used to correctly align a single field after TAB or RET.")
10983 (defvar org-last-recalc-line nil)
10984 (defconst org-narrow-column-arrow "=>"
10985 "Used as display property in narrowed table columns.")
10987 (defun org-table-align ()
10988 "Align the table at point by aligning all vertical bars."
10989 (interactive)
10990 (let* (
10991 ;; Limits of table
10992 (beg (org-table-begin))
10993 (end (org-table-end))
10994 ;; Current cursor position
10995 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10996 (colpos (org-table-current-column))
10997 (winstart (window-start))
10998 lines (new "") lengths l typenums ty fields maxfields i
10999 column
11000 (indent "") cnt frac
11001 rfmt hfmt
11002 (spaces '(1 . 1))
11003 (sp1 (car spaces))
11004 (sp2 (cdr spaces))
11005 (rfmt1 (concat
11006 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
11007 (hfmt1 (concat
11008 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
11009 emptystrings links narrow fmax f1 len c e)
11010 (untabify beg end)
11011 (remove-text-properties beg end '(org-cwidth t display t))
11012 ;; Check if we have links
11013 (goto-char beg)
11014 (setq links (re-search-forward org-bracket-link-regexp end t))
11015 ;; Make sure the link properties are right
11016 (when links (goto-char beg) (while (org-activate-bracket-links end)))
11017 ;; Check if we are narrowing any columns
11018 (goto-char beg)
11019 (setq narrow (and org-format-transports-properties-p
11020 (re-search-forward "<[0-9]+>" end t)))
11021 ;; Get the rows
11022 (setq lines (org-split-string
11023 (buffer-substring beg end) "\n"))
11024 ;; Store the indentation of the first line
11025 (if (string-match "^ *" (car lines))
11026 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11027 ;; Mark the hlines by setting the corresponding element to nil
11028 ;; At the same time, we remove trailing space.
11029 (setq lines (mapcar (lambda (l)
11030 (if (string-match "^ *|-" l)
11032 (if (string-match "[ \t]+$" l)
11033 (substring l 0 (match-beginning 0))
11034 l)))
11035 lines))
11036 ;; Get the data fields by splitting the lines.
11037 (setq fields (mapcar
11038 (lambda (l)
11039 (org-split-string l " *| *"))
11040 (delq nil (copy-sequence lines))))
11041 ;; How many fields in the longest line?
11042 (condition-case nil
11043 (setq maxfields (apply 'max (mapcar 'length fields)))
11044 (error
11045 (kill-region beg end)
11046 (org-table-create org-table-default-size)
11047 (error "Empty table - created default table")))
11048 ;; A list of empty string to fill any short rows on output
11049 (setq emptystrings (make-list maxfields ""))
11050 ;; Check for special formatting.
11051 (setq i -1)
11052 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
11053 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
11054 ;; Check if there is an explicit width specified
11055 (when (and org-table-limit-column-width narrow)
11056 (setq c column fmax nil)
11057 (while c
11058 (setq e (pop c))
11059 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
11060 (setq fmax (string-to-number (match-string 1 e)) c nil)))
11061 ;; Find fields that are wider than fmax, and shorten them
11062 (when fmax
11063 (loop for xx in column do
11064 (when (and (stringp xx)
11065 (> (org-string-width xx) fmax))
11066 (org-add-props xx nil
11067 'help-echo
11068 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
11069 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
11070 (unless (> f1 1)
11071 (error "Cannot narrow field starting with wide link \"%s\""
11072 (match-string 0 xx)))
11073 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
11074 (add-text-properties (- f1 2) f1
11075 (list 'display org-narrow-column-arrow)
11076 xx)))))
11077 ;; Get the maximum width for each column
11078 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
11079 ;; Get the fraction of numbers, to decide about alignment of the column
11080 (setq cnt 0 frac 0.0)
11081 (loop for x in column do
11082 (if (equal x "")
11084 (setq frac ( / (+ (* frac cnt)
11085 (if (string-match org-table-number-regexp x) 1 0))
11086 (setq cnt (1+ cnt))))))
11087 (push (>= frac org-table-number-fraction) typenums))
11088 (setq lengths (nreverse lengths) typenums (nreverse typenums))
11090 ;; Store the alignment of this table, for later editing of single fields
11091 (setq org-table-last-alignment typenums
11092 org-table-last-column-widths lengths)
11094 ;; With invisible characters, `format' does not get the field width right
11095 ;; So we need to make these fields wide by hand.
11096 (when links
11097 (loop for i from 0 upto (1- maxfields) do
11098 (setq len (nth i lengths))
11099 (loop for j from 0 upto (1- (length fields)) do
11100 (setq c (nthcdr i (car (nthcdr j fields))))
11101 (if (and (stringp (car c))
11102 (string-match org-bracket-link-regexp (car c))
11103 (< (org-string-width (car c)) len))
11104 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
11106 ;; Compute the formats needed for output of the table
11107 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
11108 (while (setq l (pop lengths))
11109 (setq ty (if (pop typenums) "" "-")) ; number types flushright
11110 (setq rfmt (concat rfmt (format rfmt1 ty l))
11111 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
11112 (setq rfmt (concat rfmt "\n")
11113 hfmt (concat (substring hfmt 0 -1) "|\n"))
11115 (setq new (mapconcat
11116 (lambda (l)
11117 (if l (apply 'format rfmt
11118 (append (pop fields) emptystrings))
11119 hfmt))
11120 lines ""))
11121 ;; Replace the old one
11122 (delete-region beg end)
11123 (move-marker end nil)
11124 (move-marker org-table-aligned-begin-marker (point))
11125 (insert new)
11126 (move-marker org-table-aligned-end-marker (point))
11127 (when (and orgtbl-mode (not (org-mode-p)))
11128 (goto-char org-table-aligned-begin-marker)
11129 (while (org-hide-wide-columns org-table-aligned-end-marker)))
11130 ;; Try to move to the old location (approximately)
11131 (goto-line linepos)
11132 (set-window-start (selected-window) winstart 'noforce)
11133 (org-table-goto-column colpos)
11134 (setq org-table-may-need-update nil)
11137 (defun org-string-width (s)
11138 "Compute width of string, ignoring invisible characters.
11139 This ignores character with invisibility property `org-link', and also
11140 characters with property `org-cwidth', because these will become invisible
11141 upon the next fontification round."
11142 (let (b)
11143 (when (or (eq t buffer-invisibility-spec)
11144 (assq 'org-link buffer-invisibility-spec))
11145 (while (setq b (text-property-any 0 (length s)
11146 'invisible 'org-link s))
11147 (setq s (concat (substring s 0 b)
11148 (substring s (or (next-single-property-change
11149 b 'invisible s) (length s)))))))
11150 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
11151 (setq s (concat (substring s 0 b)
11152 (substring s (or (next-single-property-change
11153 b 'org-cwidth s) (length s))))))
11154 (string-width s)))
11156 (defun org-table-begin (&optional table-type)
11157 "Find the beginning of the table and return its position.
11158 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
11159 (save-excursion
11160 (if (not (re-search-backward
11161 (if table-type org-table-any-border-regexp
11162 org-table-border-regexp)
11163 nil t))
11164 (progn (goto-char (point-min)) (point))
11165 (goto-char (match-beginning 0))
11166 (beginning-of-line 2)
11167 (point))))
11169 (defun org-table-end (&optional table-type)
11170 "Find the end of the table and return its position.
11171 With argument TABLE-TYPE, go to the end of a table.el-type table."
11172 (save-excursion
11173 (if (not (re-search-forward
11174 (if table-type org-table-any-border-regexp
11175 org-table-border-regexp)
11176 nil t))
11177 (goto-char (point-max))
11178 (goto-char (match-beginning 0)))
11179 (point-marker)))
11181 (defun org-table-justify-field-maybe (&optional new)
11182 "Justify the current field, text to left, number to right.
11183 Optional argument NEW may specify text to replace the current field content."
11184 (cond
11185 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
11186 ((org-at-table-hline-p))
11187 ((and (not new)
11188 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
11189 (current-buffer)))
11190 (< (point) org-table-aligned-begin-marker)
11191 (>= (point) org-table-aligned-end-marker)))
11192 ;; This is not the same table, force a full re-align
11193 (setq org-table-may-need-update t))
11194 (t ;; realign the current field, based on previous full realign
11195 (let* ((pos (point)) s
11196 (col (org-table-current-column))
11197 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
11198 l f n o e)
11199 (when (> col 0)
11200 (skip-chars-backward "^|\n")
11201 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
11202 (progn
11203 (setq s (match-string 1)
11204 o (match-string 0)
11205 l (max 1 (- (match-end 0) (match-beginning 0) 3))
11206 e (not (= (match-beginning 2) (match-end 2))))
11207 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
11208 l (if e "|" (setq org-table-may-need-update t) ""))
11209 n (format f s))
11210 (if new
11211 (if (<= (length new) l) ;; FIXME: length -> str-width?
11212 (setq n (format f new))
11213 (setq n (concat new "|") org-table-may-need-update t)))
11214 (or (equal n o)
11215 (let (org-table-may-need-update)
11216 (replace-match n))))
11217 (setq org-table-may-need-update t))
11218 (goto-char pos))))))
11220 (defun org-table-next-field ()
11221 "Go to the next field in the current table, creating new lines as needed.
11222 Before doing so, re-align the table if necessary."
11223 (interactive)
11224 (org-table-maybe-eval-formula)
11225 (org-table-maybe-recalculate-line)
11226 (if (and org-table-automatic-realign
11227 org-table-may-need-update)
11228 (org-table-align))
11229 (let ((end (org-table-end)))
11230 (if (org-at-table-hline-p)
11231 (end-of-line 1))
11232 (condition-case nil
11233 (progn
11234 (re-search-forward "|" end)
11235 (if (looking-at "[ \t]*$")
11236 (re-search-forward "|" end))
11237 (if (and (looking-at "-")
11238 org-table-tab-jumps-over-hlines
11239 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
11240 (goto-char (match-beginning 1)))
11241 (if (looking-at "-")
11242 (progn
11243 (beginning-of-line 0)
11244 (org-table-insert-row 'below))
11245 (if (looking-at " ") (forward-char 1))))
11246 (error
11247 (org-table-insert-row 'below)))))
11249 (defun org-table-previous-field ()
11250 "Go to the previous field in the table.
11251 Before doing so, re-align the table if necessary."
11252 (interactive)
11253 (org-table-justify-field-maybe)
11254 (org-table-maybe-recalculate-line)
11255 (if (and org-table-automatic-realign
11256 org-table-may-need-update)
11257 (org-table-align))
11258 (if (org-at-table-hline-p)
11259 (end-of-line 1))
11260 (re-search-backward "|" (org-table-begin))
11261 (re-search-backward "|" (org-table-begin))
11262 (while (looking-at "|\\(-\\|[ \t]*$\\)")
11263 (re-search-backward "|" (org-table-begin)))
11264 (if (looking-at "| ?")
11265 (goto-char (match-end 0))))
11267 (defun org-table-next-row ()
11268 "Go to the next row (same column) in the current table.
11269 Before doing so, re-align the table if necessary."
11270 (interactive)
11271 (org-table-maybe-eval-formula)
11272 (org-table-maybe-recalculate-line)
11273 (if (or (looking-at "[ \t]*$")
11274 (save-excursion (skip-chars-backward " \t") (bolp)))
11275 (newline)
11276 (if (and org-table-automatic-realign
11277 org-table-may-need-update)
11278 (org-table-align))
11279 (let ((col (org-table-current-column)))
11280 (beginning-of-line 2)
11281 (if (or (not (org-at-table-p))
11282 (org-at-table-hline-p))
11283 (progn
11284 (beginning-of-line 0)
11285 (org-table-insert-row 'below)))
11286 (org-table-goto-column col)
11287 (skip-chars-backward "^|\n\r")
11288 (if (looking-at " ") (forward-char 1)))))
11290 (defun org-table-copy-down (n)
11291 "Copy a field down in the current column.
11292 If the field at the cursor is empty, copy into it the content of the nearest
11293 non-empty field above. With argument N, use the Nth non-empty field.
11294 If the current field is not empty, it is copied down to the next row, and
11295 the cursor is moved with it. Therefore, repeating this command causes the
11296 column to be filled row-by-row.
11297 If the variable `org-table-copy-increment' is non-nil and the field is an
11298 integer, it will be incremented while copying."
11299 (interactive "p")
11300 (let* ((colpos (org-table-current-column))
11301 (field (org-table-get-field))
11302 (non-empty (string-match "[^ \t]" field))
11303 (beg (org-table-begin))
11304 txt)
11305 (org-table-check-inside-data-field)
11306 (if non-empty
11307 (progn
11308 (setq txt (org-trim field))
11309 (org-table-next-row)
11310 (org-table-blank-field))
11311 (save-excursion
11312 (setq txt
11313 (catch 'exit
11314 (while (progn (beginning-of-line 1)
11315 (re-search-backward org-table-dataline-regexp
11316 beg t))
11317 (org-table-goto-column colpos t)
11318 (if (and (looking-at
11319 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11320 (= (setq n (1- n)) 0))
11321 (throw 'exit (match-string 1))))))))
11322 (if txt
11323 (progn
11324 (if (and org-table-copy-increment
11325 (string-match "^[0-9]+$" txt))
11326 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11327 (insert txt)
11328 (org-table-maybe-recalculate-line)
11329 (org-table-align))
11330 (error "No non-empty field found"))))
11332 (defun org-table-check-inside-data-field ()
11333 "Is point inside a table data field?
11334 I.e. not on a hline or before the first or after the last column?
11335 This actually throws an error, so it aborts the current command."
11336 (if (or (not (org-at-table-p))
11337 (= (org-table-current-column) 0)
11338 (org-at-table-hline-p)
11339 (looking-at "[ \t]*$"))
11340 (error "Not in table data field")))
11342 (defvar org-table-clip nil
11343 "Clipboard for table regions.")
11345 (defun org-table-blank-field ()
11346 "Blank the current table field or active region."
11347 (interactive)
11348 (org-table-check-inside-data-field)
11349 (if (and (interactive-p) (org-region-active-p))
11350 (let (org-table-clip)
11351 (org-table-cut-region (region-beginning) (region-end)))
11352 (skip-chars-backward "^|")
11353 (backward-char 1)
11354 (if (looking-at "|[^|\n]+")
11355 (let* ((pos (match-beginning 0))
11356 (match (match-string 0))
11357 (len (org-string-width match)))
11358 (replace-match (concat "|" (make-string (1- len) ?\ )))
11359 (goto-char (+ 2 pos))
11360 (substring match 1)))))
11362 (defun org-table-get-field (&optional n replace)
11363 "Return the value of the field in column N of current row.
11364 N defaults to current field.
11365 If REPLACE is a string, replace field with this value. The return value
11366 is always the old value."
11367 (and n (org-table-goto-column n))
11368 (skip-chars-backward "^|\n")
11369 (backward-char 1)
11370 (if (looking-at "|[^|\r\n]*")
11371 (let* ((pos (match-beginning 0))
11372 (val (buffer-substring (1+ pos) (match-end 0))))
11373 (if replace
11374 (replace-match (concat "|" replace)))
11375 (goto-char (min (point-at-eol) (+ 2 pos)))
11376 val)
11377 (forward-char 1) ""))
11379 (defun org-table-current-column ()
11380 "Find out which column we are in.
11381 When called interactively, column is also displayed in echo area."
11382 (interactive)
11383 (if (interactive-p) (org-table-check-inside-data-field))
11384 (save-excursion
11385 (let ((cnt 0) (pos (point)))
11386 (beginning-of-line 1)
11387 (while (search-forward "|" pos t)
11388 (setq cnt (1+ cnt)))
11389 (if (interactive-p) (message "This is table column %d" cnt))
11390 cnt)))
11392 (defun org-table-goto-column (n &optional on-delim force)
11393 "Move the cursor to the Nth column in the current table line.
11394 With optional argument ON-DELIM, stop with point before the left delimiter
11395 of the field.
11396 If there are less than N fields, just go to after the last delimiter.
11397 However, when FORCE is non-nil, create new columns if necessary."
11398 (interactive "p")
11399 (let ((pos (point-at-eol)))
11400 (beginning-of-line 1)
11401 (when (> n 0)
11402 (while (and (> (setq n (1- n)) -1)
11403 (or (search-forward "|" pos t)
11404 (and force
11405 (progn (end-of-line 1)
11406 (skip-chars-backward "^|")
11407 (insert " | "))))))
11408 ; (backward-char 2) t)))))
11409 (when (and force (not (looking-at ".*|")))
11410 (save-excursion (end-of-line 1) (insert " | ")))
11411 (if on-delim
11412 (backward-char 1)
11413 (if (looking-at " ") (forward-char 1))))))
11415 (defun org-at-table-p (&optional table-type)
11416 "Return t if the cursor is inside an org-type table.
11417 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11418 (if org-enable-table-editor
11419 (save-excursion
11420 (beginning-of-line 1)
11421 (looking-at (if table-type org-table-any-line-regexp
11422 org-table-line-regexp)))
11423 nil))
11425 (defun org-at-table.el-p ()
11426 "Return t if and only if we are at a table.el table."
11427 (and (org-at-table-p 'any)
11428 (save-excursion
11429 (goto-char (org-table-begin 'any))
11430 (looking-at org-table1-hline-regexp))))
11432 (defun org-table-recognize-table.el ()
11433 "If there is a table.el table nearby, recognize it and move into it."
11434 (if org-table-tab-recognizes-table.el
11435 (if (org-at-table.el-p)
11436 (progn
11437 (beginning-of-line 1)
11438 (if (looking-at org-table-dataline-regexp)
11440 (if (looking-at org-table1-hline-regexp)
11441 (progn
11442 (beginning-of-line 2)
11443 (if (looking-at org-table-any-border-regexp)
11444 (beginning-of-line -1)))))
11445 (if (re-search-forward "|" (org-table-end t) t)
11446 (progn
11447 (require 'table)
11448 (if (table--at-cell-p (point))
11450 (message "recognizing table.el table...")
11451 (table-recognize-table)
11452 (message "recognizing table.el table...done")))
11453 (error "This should not happen..."))
11455 nil)
11456 nil))
11458 (defun org-at-table-hline-p ()
11459 "Return t if the cursor is inside a hline in a table."
11460 (if org-enable-table-editor
11461 (save-excursion
11462 (beginning-of-line 1)
11463 (looking-at org-table-hline-regexp))
11464 nil))
11466 (defun org-table-insert-column ()
11467 "Insert a new column into the table."
11468 (interactive)
11469 (if (not (org-at-table-p))
11470 (error "Not at a table"))
11471 (org-table-find-dataline)
11472 (let* ((col (max 1 (org-table-current-column)))
11473 (beg (org-table-begin))
11474 (end (org-table-end))
11475 ;; Current cursor position
11476 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11477 (colpos col))
11478 (goto-char beg)
11479 (while (< (point) end)
11480 (if (org-at-table-hline-p)
11482 (org-table-goto-column col t)
11483 (insert "| "))
11484 (beginning-of-line 2))
11485 (move-marker end nil)
11486 (goto-line linepos)
11487 (org-table-goto-column colpos)
11488 (org-table-align)
11489 (org-table-modify-formulas 'insert col)))
11491 (defun org-table-find-dataline ()
11492 "Find a dataline in the current table, which is needed for column commands."
11493 (if (and (org-at-table-p)
11494 (not (org-at-table-hline-p)))
11496 (let ((col (current-column))
11497 (end (org-table-end)))
11498 (move-to-column col)
11499 (while (and (< (point) end)
11500 (or (not (= (current-column) col))
11501 (org-at-table-hline-p)))
11502 (beginning-of-line 2)
11503 (move-to-column col))
11504 (if (and (org-at-table-p)
11505 (not (org-at-table-hline-p)))
11507 (error
11508 "Please position cursor in a data line for column operations")))))
11510 (defun org-table-delete-column ()
11511 "Delete a column from the table."
11512 (interactive)
11513 (if (not (org-at-table-p))
11514 (error "Not at a table"))
11515 (org-table-find-dataline)
11516 (org-table-check-inside-data-field)
11517 (let* ((col (org-table-current-column))
11518 (beg (org-table-begin))
11519 (end (org-table-end))
11520 ;; Current cursor position
11521 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11522 (colpos col))
11523 (goto-char beg)
11524 (while (< (point) end)
11525 (if (org-at-table-hline-p)
11527 (org-table-goto-column col t)
11528 (and (looking-at "|[^|\n]+|")
11529 (replace-match "|")))
11530 (beginning-of-line 2))
11531 (move-marker end nil)
11532 (goto-line linepos)
11533 (org-table-goto-column colpos)
11534 (org-table-align)
11535 (org-table-modify-formulas 'remove col)))
11537 (defun org-table-move-column-right ()
11538 "Move column to the right."
11539 (interactive)
11540 (org-table-move-column nil))
11541 (defun org-table-move-column-left ()
11542 "Move column to the left."
11543 (interactive)
11544 (org-table-move-column 'left))
11546 (defun org-table-move-column (&optional left)
11547 "Move the current column to the right. With arg LEFT, move to the left."
11548 (interactive "P")
11549 (if (not (org-at-table-p))
11550 (error "Not at a table"))
11551 (org-table-find-dataline)
11552 (org-table-check-inside-data-field)
11553 (let* ((col (org-table-current-column))
11554 (col1 (if left (1- col) col))
11555 (beg (org-table-begin))
11556 (end (org-table-end))
11557 ;; Current cursor position
11558 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11559 (colpos (if left (1- col) (1+ col))))
11560 (if (and left (= col 1))
11561 (error "Cannot move column further left"))
11562 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11563 (error "Cannot move column further right"))
11564 (goto-char beg)
11565 (while (< (point) end)
11566 (if (org-at-table-hline-p)
11568 (org-table-goto-column col1 t)
11569 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11570 (replace-match "|\\2|\\1|")))
11571 (beginning-of-line 2))
11572 (move-marker end nil)
11573 (goto-line linepos)
11574 (org-table-goto-column colpos)
11575 (org-table-align)
11576 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11578 (defun org-table-move-row-down ()
11579 "Move table row down."
11580 (interactive)
11581 (org-table-move-row nil))
11582 (defun org-table-move-row-up ()
11583 "Move table row up."
11584 (interactive)
11585 (org-table-move-row 'up))
11587 (defun org-table-move-row (&optional up)
11588 "Move the current table line down. With arg UP, move it up."
11589 (interactive "P")
11590 (let ((col (current-column))
11591 (pos (point))
11592 (tonew (if up 0 2))
11593 txt)
11594 (beginning-of-line tonew)
11595 (if (not (org-at-table-p))
11596 (progn
11597 (goto-char pos)
11598 (error "Cannot move row further")))
11599 (goto-char pos)
11600 (beginning-of-line 1)
11601 (setq pos (point))
11602 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11603 (delete-region (point) (1+ (point-at-eol)))
11604 (beginning-of-line tonew)
11605 (insert txt)
11606 (beginning-of-line 0)
11607 (move-to-column col)))
11609 (defun org-table-insert-row (&optional arg)
11610 "Insert a new row above the current line into the table.
11611 With prefix ARG, insert below the current line."
11612 (interactive "P")
11613 (if (not (org-at-table-p))
11614 (error "Not at a table"))
11615 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11616 (new (org-table-clean-line line)))
11617 ;; Fix the first field if necessary
11618 (if (string-match "^[ \t]*| *[#$] *|" line)
11619 (setq new (replace-match (match-string 0 line) t t new)))
11620 (beginning-of-line (if arg 2 1))
11621 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11622 (beginning-of-line 0)
11623 (re-search-forward "| ?" (point-at-eol) t)
11624 (and org-table-may-need-update (org-table-align))))
11626 (defun org-table-insert-hline (&optional arg)
11627 "Insert a horizontal-line below the current line into the table.
11628 With prefix ARG, insert above the current line."
11629 (interactive "P")
11630 (if (not (org-at-table-p))
11631 (error "Not at a table"))
11632 (let ((line (org-table-clean-line
11633 (buffer-substring (point-at-bol) (point-at-eol))))
11634 (col (current-column)))
11635 (while (string-match "|\\( +\\)|" line)
11636 (setq line (replace-match
11637 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11638 ?-) "|") t t line)))
11639 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11640 (beginning-of-line (if arg 1 2))
11641 (insert line "\n")
11642 (beginning-of-line (if arg 1 -1))
11643 (move-to-column col)))
11645 (defun org-table-clean-line (s)
11646 "Convert a table line S into a string with only \"|\" and space.
11647 In particular, this does handle wide and invisible characters."
11648 (if (string-match "^[ \t]*|-" s)
11649 ;; It's a hline, just map the characters
11650 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11651 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11652 (setq s (replace-match
11653 (concat "|" (make-string (org-string-width (match-string 1 s))
11654 ?\ ) "|")
11655 t t s)))
11658 (defun org-table-kill-row ()
11659 "Delete the current row or horizontal line from the table."
11660 (interactive)
11661 (if (not (org-at-table-p))
11662 (error "Not at a table"))
11663 (let ((col (current-column)))
11664 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11665 (if (not (org-at-table-p)) (beginning-of-line 0))
11666 (move-to-column col)))
11668 (defun org-table-sort-lines (beg end numericp)
11669 "Sort table lines in region.
11670 Point and mark define the first and last line to include. Both point and
11671 mark should be in the column that is used for sorting. For example, to
11672 sort according to column 3, put the mark in the first line to sort, in
11673 table column 3. Put point into the last line to be included in the sorting,
11674 also in table column 3. The command will prompt for the sorting method
11675 \(n for numerical, a for alphanumeric)."
11676 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11677 (setq numericp (string-match "[nN]" numericp))
11678 (org-table-align) ;; Just to be safe
11679 (let* (bcol ecol cmp column lns)
11680 (goto-char beg)
11681 (org-table-check-inside-data-field)
11682 (setq column (org-table-current-column)
11683 beg (move-marker (make-marker) (point-at-bol)))
11684 (goto-char end)
11685 (org-table-check-inside-data-field)
11686 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11687 (untabify beg end)
11688 (goto-char beg)
11689 (org-table-goto-column column)
11690 (skip-chars-backward "^|")
11691 (setq bcol (current-column))
11692 (org-table-goto-column (1+ column))
11693 (skip-chars-backward "^|")
11694 (setq ecol (1- (current-column)))
11695 (setq cmp (if numericp
11696 (lambda (a b) (< (car a) (car b)))
11697 (lambda (a b) (string< (car a) (car b)))))
11698 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11699 (org-split-string (buffer-substring beg end) "\n")))
11700 (if numericp
11701 (setq lns (mapcar (lambda(x)
11702 (cons (string-to-number (car x)) (cdr x)))
11703 lns)))
11704 (delete-region beg end)
11705 (move-marker beg nil)
11706 (move-marker end nil)
11707 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11708 (message "%d lines sorted %s based on column %d"
11709 (length lns)
11710 (if numericp "numerically" "alphabetically") column)))
11712 (defun org-table-cut-region (beg end)
11713 "Copy region in table to the clipboard and blank all relevant fields."
11714 (interactive "r")
11715 (org-table-copy-region beg end 'cut))
11717 (defun org-table-copy-region (beg end &optional cut)
11718 "Copy rectangular region in table to clipboard.
11719 A special clipboard is used which can only be accessed
11720 with `org-table-paste-rectangle'."
11721 (interactive "rP")
11722 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11723 region cols
11724 (rpl (if cut " " nil)))
11725 (goto-char beg)
11726 (org-table-check-inside-data-field)
11727 (setq l01 (count-lines (point-min) (point))
11728 c01 (org-table-current-column))
11729 (goto-char end)
11730 (org-table-check-inside-data-field)
11731 (setq l02 (count-lines (point-min) (point))
11732 c02 (org-table-current-column))
11733 (setq l1 (min l01 l02) l2 (max l01 l02)
11734 c1 (min c01 c02) c2 (max c01 c02))
11735 (catch 'exit
11736 (while t
11737 (catch 'nextline
11738 (if (> l1 l2) (throw 'exit t))
11739 (goto-line l1)
11740 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11741 (setq cols nil ic1 c1 ic2 c2)
11742 (while (< ic1 (1+ ic2))
11743 (push (org-table-get-field ic1 rpl) cols)
11744 (setq ic1 (1+ ic1)))
11745 (push (nreverse cols) region)
11746 (setq l1 (1+ l1)))))
11747 (setq org-table-clip (nreverse region))
11748 (if cut (org-table-align))
11749 org-table-clip))
11751 (defun org-table-paste-rectangle ()
11752 "Paste a rectangular region into a table.
11753 The upper right corner ends up in the current field. All involved fields
11754 will be overwritten. If the rectangle does not fit into the present table,
11755 the table is enlarged as needed. The process ignores horizontal separator
11756 lines."
11757 (interactive)
11758 (unless (and org-table-clip (listp org-table-clip))
11759 (error "First cut/copy a region to paste!"))
11760 (org-table-check-inside-data-field)
11761 (let* ((clip org-table-clip)
11762 (line (count-lines (point-min) (point)))
11763 (col (org-table-current-column))
11764 (org-enable-table-editor t)
11765 (org-table-automatic-realign nil)
11766 c cols field)
11767 (while (setq cols (pop clip))
11768 (while (org-at-table-hline-p) (beginning-of-line 2))
11769 (if (not (org-at-table-p))
11770 (progn (end-of-line 0) (org-table-next-field)))
11771 (setq c col)
11772 (while (setq field (pop cols))
11773 (org-table-goto-column c nil 'force)
11774 (org-table-get-field nil field)
11775 (setq c (1+ c)))
11776 (beginning-of-line 2))
11777 (goto-line line)
11778 (org-table-goto-column col)
11779 (org-table-align)))
11781 (defun org-table-convert ()
11782 "Convert from `org-mode' table to table.el and back.
11783 Obviously, this only works within limits. When an Org-mode table is
11784 converted to table.el, all horizontal separator lines get lost, because
11785 table.el uses these as cell boundaries and has no notion of horizontal lines.
11786 A table.el table can be converted to an Org-mode table only if it does not
11787 do row or column spanning. Multiline cells will become multiple cells.
11788 Beware, Org-mode does not test if the table can be successfully converted - it
11789 blindly applies a recipe that works for simple tables."
11790 (interactive)
11791 (require 'table)
11792 (if (org-at-table.el-p)
11793 ;; convert to Org-mode table
11794 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11795 (end (move-marker (make-marker) (org-table-end t))))
11796 (table-unrecognize-region beg end)
11797 (goto-char beg)
11798 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11799 (replace-match ""))
11800 (goto-char beg))
11801 (if (org-at-table-p)
11802 ;; convert to table.el table
11803 (let ((beg (move-marker (make-marker) (org-table-begin)))
11804 (end (move-marker (make-marker) (org-table-end))))
11805 ;; first, get rid of all horizontal lines
11806 (goto-char beg)
11807 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11808 (replace-match ""))
11809 ;; insert a hline before first
11810 (goto-char beg)
11811 (org-table-insert-hline 'above)
11812 (beginning-of-line -1)
11813 ;; insert a hline after each line
11814 (while (progn (beginning-of-line 3) (< (point) end))
11815 (org-table-insert-hline))
11816 (goto-char beg)
11817 (setq end (move-marker end (org-table-end)))
11818 ;; replace "+" at beginning and ending of hlines
11819 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11820 (replace-match "\\1+-"))
11821 (goto-char beg)
11822 (while (re-search-forward "-|[ \t]*$" end t)
11823 (replace-match "-+"))
11824 (goto-char beg)))))
11826 (defun org-table-wrap-region (arg)
11827 "Wrap several fields in a column like a paragraph.
11828 This is useful if you'd like to spread the contents of a field over several
11829 lines, in order to keep the table compact.
11831 If there is an active region, and both point and mark are in the same column,
11832 the text in the column is wrapped to minimum width for the given number of
11833 lines. Generally, this makes the table more compact. A prefix ARG may be
11834 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11835 formats the selected text to two lines. If the region was longer than two
11836 lines, the remaining lines remain empty. A negative prefix argument reduces
11837 the current number of lines by that amount. The wrapped text is pasted back
11838 into the table. If you formatted it to more lines than it was before, fields
11839 further down in the table get overwritten - so you might need to make space in
11840 the table first.
11842 If there is no region, the current field is split at the cursor position and
11843 the text fragment to the right of the cursor is prepended to the field one
11844 line down.
11846 If there is no region, but you specify a prefix ARG, the current field gets
11847 blank, and the content is appended to the field above."
11848 (interactive "P")
11849 (org-table-check-inside-data-field)
11850 (if (org-region-active-p)
11851 ;; There is a region: fill as a paragraph
11852 (let ((beg (region-beginning))
11853 nlines)
11854 (org-table-cut-region (region-beginning) (region-end))
11855 (if (> (length (car org-table-clip)) 1)
11856 (error "Region must be limited to single column"))
11857 (setq nlines (if arg
11858 (if (< arg 1)
11859 (+ (length org-table-clip) arg)
11860 arg)
11861 (length org-table-clip)))
11862 (setq org-table-clip
11863 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11864 nil nlines)))
11865 (goto-char beg)
11866 (org-table-paste-rectangle))
11867 ;; No region, split the current field at point
11868 (if arg
11869 ;; combine with field above
11870 (let ((s (org-table-blank-field))
11871 (col (org-table-current-column)))
11872 (beginning-of-line 0)
11873 (while (org-at-table-hline-p) (beginning-of-line 0))
11874 (org-table-goto-column col)
11875 (skip-chars-forward "^|")
11876 (skip-chars-backward " ")
11877 (insert " " (org-trim s))
11878 (org-table-align))
11879 ;; split field
11880 (when (looking-at "\\([^|]+\\)+|")
11881 (let ((s (match-string 1)))
11882 (replace-match " |")
11883 (goto-char (match-beginning 0))
11884 (org-table-next-row)
11885 (insert (org-trim s) " ")
11886 (org-table-align))))))
11888 (defvar org-field-marker nil)
11890 (defun org-table-edit-field (arg)
11891 "Edit table field in a different window.
11892 This is mainly useful for fields that contain hidden parts.
11893 When called with a \\[universal-argument] prefix, just make the full field visible so that
11894 it can be edited in place."
11895 (interactive "P")
11896 (if arg
11897 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11898 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11899 (remove-text-properties b e '(org-cwidth t invisible t
11900 display t intangible t))
11901 (if (and (boundp 'font-lock-mode) font-lock-mode)
11902 (font-lock-fontify-block)))
11903 (let ((pos (move-marker (make-marker) (point)))
11904 (field (org-table-get-field))
11905 (cw (current-window-configuration))
11907 (switch-to-buffer-other-window "*Org tmp*")
11908 (erase-buffer)
11909 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11910 (org-mode)
11911 (goto-char (setq p (point-max)))
11912 (insert (org-trim field))
11913 (remove-text-properties p (point-max)
11914 '(invisible t org-cwidth t display t
11915 intangible t))
11916 (goto-char p)
11917 (org-set-local 'org-finish-function
11918 'org-table-finish-edit-field)
11919 (org-set-local 'org-window-configuration cw)
11920 (org-set-local 'org-field-marker pos)
11921 (message "Edit and finish with C-c C-c"))))
11923 (defun org-table-finish-edit-field ()
11924 "Finish editing a table data field.
11925 Remove all newline characters, insert the result into the table, realign
11926 the table and kill the editing buffer."
11927 (let ((pos org-field-marker)
11928 (cw org-window-configuration)
11929 (cb (current-buffer))
11930 text)
11931 (goto-char (point-min))
11932 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11933 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11934 (replace-match " "))
11935 (setq text (org-trim (buffer-string)))
11936 (set-window-configuration cw)
11937 (kill-buffer cb)
11938 (select-window (get-buffer-window (marker-buffer pos)))
11939 (goto-char pos)
11940 (move-marker pos nil)
11941 (org-table-check-inside-data-field)
11942 (org-table-get-field nil text)
11943 (org-table-align)
11944 (message "New field value inserted")))
11946 (defun org-trim (s)
11947 "Remove whitespace at beginning and end of string."
11948 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11949 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11952 (defun org-wrap (string &optional width lines)
11953 "Wrap string to either a number of lines, or a width in characters.
11954 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11955 that costs. If there is a word longer than WIDTH, the text is actually
11956 wrapped to the length of that word.
11957 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11958 many lines, whatever width that takes.
11959 The return value is a list of lines, without newlines at the end."
11960 (let* ((words (org-split-string string "[ \t\n]+"))
11961 (maxword (apply 'max (mapcar 'org-string-width words)))
11962 w ll)
11963 (cond (width
11964 (org-do-wrap words (max maxword width)))
11965 (lines
11966 (setq w maxword)
11967 (setq ll (org-do-wrap words maxword))
11968 (if (<= (length ll) lines)
11970 (setq ll words)
11971 (while (> (length ll) lines)
11972 (setq w (1+ w))
11973 (setq ll (org-do-wrap words w)))
11974 ll))
11975 (t (error "Cannot wrap this")))))
11978 (defun org-do-wrap (words width)
11979 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11980 (let (lines line)
11981 (while words
11982 (setq line (pop words))
11983 (while (and words (< (+ (length line) (length (car words))) width))
11984 (setq line (concat line " " (pop words))))
11985 (setq lines (push line lines)))
11986 (nreverse lines)))
11988 (defun org-split-string (string &optional separators)
11989 "Splits STRING into substrings at SEPARATORS.
11990 No empty strings are returned if there are matches at the beginning
11991 and end of string."
11992 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11993 (start 0)
11994 notfirst
11995 (list nil))
11996 (while (and (string-match rexp string
11997 (if (and notfirst
11998 (= start (match-beginning 0))
11999 (< start (length string)))
12000 (1+ start) start))
12001 (< (match-beginning 0) (length string)))
12002 (setq notfirst t)
12003 (or (eq (match-beginning 0) 0)
12004 (and (eq (match-beginning 0) (match-end 0))
12005 (eq (match-beginning 0) start))
12006 (setq list
12007 (cons (substring string start (match-beginning 0))
12008 list)))
12009 (setq start (match-end 0)))
12010 (or (eq start (length string))
12011 (setq list
12012 (cons (substring string start)
12013 list)))
12014 (nreverse list)))
12016 (defun org-table-map-tables (function)
12017 "Apply FUNCTION to the start of all tables in the buffer."
12018 (save-excursion
12019 (save-restriction
12020 (widen)
12021 (goto-char (point-min))
12022 (while (re-search-forward org-table-any-line-regexp nil t)
12023 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
12024 (beginning-of-line 1)
12025 (if (looking-at org-table-line-regexp)
12026 (save-excursion (funcall function)))
12027 (re-search-forward org-table-any-border-regexp nil 1))))
12028 (message "Mapping tables: done"))
12030 (defun org-table-sum (&optional beg end nlast)
12031 "Sum numbers in region of current table column.
12032 The result will be displayed in the echo area, and will be available
12033 as kill to be inserted with \\[yank].
12035 If there is an active region, it is interpreted as a rectangle and all
12036 numbers in that rectangle will be summed. If there is no active
12037 region and point is located in a table column, sum all numbers in that
12038 column.
12040 If at least one number looks like a time HH:MM or HH:MM:SS, all other
12041 numbers are assumed to be times as well (in decimal hours) and the
12042 numbers are added as such.
12044 If NLAST is a number, only the NLAST fields will actually be summed."
12045 (interactive)
12046 (save-excursion
12047 (let (col (timecnt 0) diff h m s org-table-clip)
12048 (cond
12049 ((and beg end)) ; beg and end given explicitly
12050 ((org-region-active-p)
12051 (setq beg (region-beginning) end (region-end)))
12053 (setq col (org-table-current-column))
12054 (goto-char (org-table-begin))
12055 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
12056 (error "No table data"))
12057 (org-table-goto-column col)
12058 ;not needed? (skip-chars-backward "^|")
12059 (setq beg (point))
12060 (goto-char (org-table-end))
12061 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
12062 (error "No table data"))
12063 (org-table-goto-column col)
12064 ;not needed? (skip-chars-forward "^|")
12065 (setq end (point))))
12066 (let* ((items (apply 'append (org-table-copy-region beg end)))
12067 (items1 (cond ((not nlast) items)
12068 ((>= nlast (length items)) items)
12069 (t (setq items (reverse items))
12070 (setcdr (nthcdr (1- nlast) items) nil)
12071 (nreverse items))))
12072 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
12073 items1)))
12074 (res (apply '+ numbers))
12075 (sres (if (= timecnt 0)
12076 (format "%g" res)
12077 (setq diff (* 3600 res)
12078 h (floor (/ diff 3600)) diff (mod diff 3600)
12079 m (floor (/ diff 60)) diff (mod diff 60)
12080 s diff)
12081 (format "%d:%02d:%02d" h m s))))
12082 (kill-new sres)
12083 (if (interactive-p)
12084 (message "%s"
12085 (substitute-command-keys
12086 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
12087 (length numbers) sres))))
12088 sres))))
12090 (defun org-table-get-number-for-summing (s)
12091 (let (n)
12092 (if (string-match "^ *|? *" s)
12093 (setq s (replace-match "" nil nil s)))
12094 (if (string-match " *|? *$" s)
12095 (setq s (replace-match "" nil nil s)))
12096 (setq n (string-to-number s))
12097 (cond
12098 ((and (string-match "0" s)
12099 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
12100 ((string-match "\\`[ \t]+\\'" s) nil)
12101 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
12102 (let ((h (string-to-number (or (match-string 1 s) "0")))
12103 (m (string-to-number (or (match-string 2 s) "0")))
12104 (s (string-to-number (or (match-string 4 s) "0"))))
12105 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
12106 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
12107 ((equal n 0) nil)
12108 (t n))))
12110 (defun org-table-get-vertical-vector (desc &optional tbeg col)
12111 "Get a calc vector from a column, accorting to descriptor DESC.
12112 Optional arguments TBEG and COL can give the beginning of the table and
12113 the current column, to avoid unnecessary parsing."
12114 (save-excursion
12115 (or tbeg (setq tbeg (org-table-begin)))
12116 (or col (setq col (org-table-current-column)))
12117 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
12118 (cond
12119 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
12120 (setq n1 (- (match-end 1) (match-beginning 1)))
12121 (if (match-beginning 3)
12122 (setq n2 (- (match-end 2) (match-beginning 3))))
12123 (setq n (if n2 (max n1 n2) n1))
12124 (setq n1 (if n2 (min n1 n2)))
12125 (setq nn n)
12126 (while (and (> nn 0)
12127 (re-search-backward org-table-hline-regexp tbeg t))
12128 (push (org-current-line) hline-list)
12129 (setq nn (1- nn)))
12130 (setq hline-list (nreverse hline-list))
12131 (goto-line (nth (1- n) hline-list))
12132 (when (re-search-forward org-table-dataline-regexp)
12133 (org-table-goto-column col)
12134 (setq beg (point)))
12135 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
12136 (when (re-search-backward org-table-dataline-regexp)
12137 (org-table-goto-column col)
12138 (setq end (point)))
12139 (setq l (apply 'append (org-table-copy-region beg end)))
12140 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
12141 (if (equal x "") "0" x))
12142 l ",") "]"))
12143 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
12144 (setq n1 (string-to-number (match-string 1 desc))
12145 n2 (string-to-number (match-string 2 desc)))
12146 (beginning-of-line 1)
12147 (save-excursion
12148 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
12149 (org-table-goto-column col)
12150 (setq beg (point))))
12151 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
12152 (org-table-goto-column col)
12153 (setq end (point)))
12154 (setq l (apply 'append (org-table-copy-region beg end)))
12155 (concat "[" (mapconcat
12156 (lambda (x) (setq x (org-trim x))
12157 (if (equal x "") "0" x))
12158 l ",") "]"))
12159 ((string-match "\\([0-9]+\\)" desc)
12160 (beginning-of-line 1)
12161 (when (re-search-backward org-table-dataline-regexp tbeg t
12162 (string-to-number (match-string 0 desc)))
12163 (org-table-goto-column col)
12164 (org-trim (org-table-get-field))))))))
12166 (defvar org-table-formula-history nil)
12168 (defvar org-table-column-names nil
12169 "Alist with column names, derived from the `!' line.")
12170 (defvar org-table-column-name-regexp nil
12171 "Regular expression matching the current column names.")
12172 (defvar org-table-local-parameters nil
12173 "Alist with parameter names, derived from the `$' line.")
12174 (defvar org-table-named-field-locations nil
12175 "Alist with locations of named fields.")
12177 (defun org-table-get-formula (&optional equation named)
12178 "Read a formula from the minibuffer, offer stored formula as default."
12179 (let* ((name (car (rassoc (list (org-current-line)
12180 (org-table-current-column))
12181 org-table-named-field-locations)))
12182 (scol (if named
12183 (if name name
12184 (error "Not in a named field"))
12185 (int-to-string (org-table-current-column))))
12186 (dummy (and name (not named)
12187 (not (y-or-n-p "Replace named-field formula with column equation? " ))
12188 (error "Abort")))
12189 (org-table-may-need-update nil)
12190 (stored-list (org-table-get-stored-formulas))
12191 (stored (cdr (assoc scol stored-list)))
12192 (eq (cond
12193 ((and stored equation (string-match "^ *=? *$" equation))
12194 stored)
12195 ((stringp equation)
12196 equation)
12197 (t (read-string
12198 (format "%s formula $%s=" (if named "Field" "Column") scol)
12199 (or stored "") 'org-table-formula-history
12200 ;stored
12201 ))))
12202 mustsave)
12203 (when (not (string-match "\\S-" eq))
12204 ;; remove formula
12205 (setq stored-list (delq (assoc scol stored-list) stored-list))
12206 (org-table-store-formulas stored-list)
12207 (error "Formula removed"))
12208 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
12209 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
12210 (if (and name (not named))
12211 ;; We set the column equation, delete the named one.
12212 (setq stored-list (delq (assoc name stored-list) stored-list)
12213 mustsave t))
12214 (if stored
12215 (setcdr (assoc scol stored-list) eq)
12216 (setq stored-list (cons (cons scol eq) stored-list)))
12217 (if (or mustsave (not (equal stored eq)))
12218 (org-table-store-formulas stored-list))
12219 eq))
12221 (defun org-table-store-formulas (alist)
12222 "Store the list of formulas below the current table."
12223 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
12224 (save-excursion
12225 (goto-char (org-table-end))
12226 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
12227 (delete-region (point) (match-end 0)))
12228 (insert "#+TBLFM: "
12229 (mapconcat (lambda (x)
12230 (concat "$" (car x) "=" (cdr x)))
12231 alist "::")
12232 "\n")))
12234 (defun org-table-get-stored-formulas ()
12235 "Return an alist with the stored formulas directly after current table."
12236 (interactive)
12237 (let (scol eq eq-alist strings string seen)
12238 (save-excursion
12239 (goto-char (org-table-end))
12240 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
12241 (setq strings (org-split-string (match-string 2) " *:: *"))
12242 (while (setq string (pop strings))
12243 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
12244 (setq scol (match-string 1 string)
12245 eq (match-string 2 string)
12246 eq-alist (cons (cons scol eq) eq-alist))
12247 (if (member scol seen)
12248 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
12249 (push scol seen))))))
12250 (nreverse eq-alist)))
12252 (defun org-table-modify-formulas (action &rest columns)
12253 "Modify the formulas stored below the current table.
12254 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
12255 expected, for the other actions only a single column number is needed."
12256 (let ((list (org-table-get-stored-formulas))
12257 (nmax (length (org-split-string
12258 (buffer-substring (point-at-bol) (point-at-eol))
12259 "|")))
12260 col col1 col2 scol si sc1 sc2)
12261 (cond
12262 ((null list)) ; No action needed if there are no stored formulas
12263 ((eq action 'remove)
12264 (setq col (car columns)
12265 scol (int-to-string col))
12266 (org-table-replace-in-formulas list scol "INVALID")
12267 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
12268 (loop for i from (1+ col) upto nmax by 1 do
12269 (setq si (int-to-string i))
12270 (org-table-replace-in-formulas list si (int-to-string (1- i)))
12271 (if (assoc si list) (setcar (assoc si list)
12272 (int-to-string (1- i))))))
12273 ((eq action 'insert)
12274 (setq col (car columns))
12275 (loop for i from nmax downto col by 1 do
12276 (setq si (int-to-string i))
12277 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
12278 (if (assoc si list) (setcar (assoc si list)
12279 (int-to-string (1+ i))))))
12280 ((eq action 'swap)
12281 (setq col1 (car columns) col2 (nth 1 columns)
12282 sc1 (int-to-string col1) sc2 (int-to-string col2))
12283 ;; Hopefully, ZqZtZ will never be a name in a table
12284 (org-table-replace-in-formulas list sc1 "ZqZtZ")
12285 (org-table-replace-in-formulas list sc2 sc1)
12286 (org-table-replace-in-formulas list "ZqZtZ" sc2)
12287 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
12288 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
12289 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
12290 (t (error "Invalid action in `org-table-modify-formulas'")))
12291 (if list (org-table-store-formulas list))))
12293 (defun org-table-replace-in-formulas (list s1 s2)
12294 (let (elt re s)
12295 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
12296 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
12297 re (concat (regexp-quote s1) "\\>"))
12298 (while (setq elt (pop list))
12299 (setq s (cdr elt))
12300 (while (string-match re s)
12301 (setq s (replace-match s2 t t s)))
12302 (setcdr elt s))))
12304 (defun org-table-get-specials ()
12305 "Get the column names and local parameters for this table."
12306 (save-excursion
12307 (let ((beg (org-table-begin)) (end (org-table-end))
12308 names name fields fields1 field cnt c v line col)
12309 (setq org-table-column-names nil
12310 org-table-local-parameters nil
12311 org-table-named-field-locations nil)
12312 (goto-char beg)
12313 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12314 (setq names (org-split-string (match-string 1) " *| *")
12315 cnt 1)
12316 (while (setq name (pop names))
12317 (setq cnt (1+ cnt))
12318 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12319 (push (cons name (int-to-string cnt)) org-table-column-names))))
12320 (setq org-table-column-names (nreverse org-table-column-names))
12321 (setq org-table-column-name-regexp
12322 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12323 (goto-char beg)
12324 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12325 (setq fields (org-split-string (match-string 1) " *| *"))
12326 (while (setq field (pop fields))
12327 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12328 (push (cons (match-string 1 field) (match-string 2 field))
12329 org-table-local-parameters))))
12330 (goto-char beg)
12331 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12332 (setq c (match-string 1)
12333 fields (org-split-string (match-string 2) " *| *"))
12334 (save-excursion
12335 (beginning-of-line (if (equal c "_") 2 0))
12336 (setq line (org-current-line) col 1)
12337 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12338 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12339 (while (and fields1 (setq field (pop fields)))
12340 (setq v (pop fields1) col (1+ col))
12341 (when (and (stringp field) (stringp v)
12342 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12343 (push (cons field v) org-table-local-parameters)
12344 (push (list field line col) org-table-named-field-locations)))))))
12346 (defun org-this-word ()
12347 ;; Get the current word
12348 (save-excursion
12349 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12350 (end (progn (skip-chars-forward "^ \t\n") (point))))
12351 (buffer-substring-no-properties beg end))))
12353 (defun org-table-maybe-eval-formula ()
12354 "Check if the current field starts with \"=\" or \":=\".
12355 If yes, store the formula and apply it."
12356 ;; We already know we are in a table. Get field will only return a formula
12357 ;; when appropriate. It might return a separator line, but no problem.
12358 (when org-table-formula-evaluate-inline
12359 (let* ((field (org-trim (or (org-table-get-field) "")))
12360 named eq)
12361 (when (string-match "^:?=\\(.*\\)" field)
12362 (setq named (equal (string-to-char field) ?:)
12363 eq (match-string 1 field))
12364 (if (fboundp 'calc-eval)
12365 (org-table-eval-formula (if named '(4) nil) eq))))))
12367 (defvar org-recalc-commands nil
12368 "List of commands triggering the recalculation of a line.
12369 Will be filled automatically during use.")
12371 (defvar org-recalc-marks
12372 '((" " . "Unmarked: no special line, no automatic recalculation")
12373 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12374 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12375 ("!" . "Column name definition line. Reference in formula as $name.")
12376 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12377 ("_" . "Names for values in row below this one.")
12378 ("^" . "Names for values in row above this one.")))
12380 (defun org-table-rotate-recalc-marks (&optional newchar)
12381 "Rotate the recalculation mark in the first column.
12382 If in any row, the first field is not consistent with a mark,
12383 insert a new column for the markers.
12384 When there is an active region, change all the lines in the region,
12385 after prompting for the marking character.
12386 After each change, a message will be displayed indicating the meaning
12387 of the new mark."
12388 (interactive)
12389 (unless (org-at-table-p) (error "Not at a table"))
12390 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12391 (beg (org-table-begin))
12392 (end (org-table-end))
12393 (l (org-current-line))
12394 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12395 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12396 (have-col
12397 (save-excursion
12398 (goto-char beg)
12399 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12400 (col (org-table-current-column))
12401 (forcenew (car (assoc newchar org-recalc-marks)))
12402 epos new)
12403 (when l1
12404 (message "Change region to what mark? Type # * ! $ or SPC: ")
12405 (setq newchar (char-to-string (read-char-exclusive))
12406 forcenew (car (assoc newchar org-recalc-marks))))
12407 (if (and newchar (not forcenew))
12408 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12409 newchar))
12410 (if l1 (goto-line l1))
12411 (save-excursion
12412 (beginning-of-line 1)
12413 (unless (looking-at org-table-dataline-regexp)
12414 (error "Not at a table data line")))
12415 (unless have-col
12416 (org-table-goto-column 1)
12417 (org-table-insert-column)
12418 (org-table-goto-column (1+ col)))
12419 (setq epos (point-at-eol))
12420 (save-excursion
12421 (beginning-of-line 1)
12422 (org-table-get-field
12423 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12424 (concat " "
12425 (setq new (or forcenew
12426 (cadr (member (match-string 1) marks))))
12427 " ")
12428 " # ")))
12429 (if (and l1 l2)
12430 (progn
12431 (goto-line l1)
12432 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12433 (and (looking-at org-table-dataline-regexp)
12434 (org-table-get-field 1 (concat " " new " "))))
12435 (goto-line l1)))
12436 (if (not (= epos (point-at-eol))) (org-table-align))
12437 (goto-line l)
12438 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12440 (defun org-table-maybe-recalculate-line ()
12441 "Recompute the current line if marked for it, and if we haven't just done it."
12442 (interactive)
12443 (and org-table-allow-automatic-line-recalculation
12444 (not (and (memq last-command org-recalc-commands)
12445 (equal org-last-recalc-line (org-current-line))))
12446 (save-excursion (beginning-of-line 1)
12447 (looking-at org-table-auto-recalculate-regexp))
12448 (fboundp 'calc-eval)
12449 (org-table-recalculate) t))
12451 (defvar org-table-formula-debug nil
12452 "Non-nil means, debug table formulas.
12453 When nil, simply write \"#ERROR\" in corrupted fields.")
12455 (defvar modes)
12456 (defsubst org-set-calc-mode (var &optional value)
12457 (if (stringp var)
12458 (setq var (assoc var '(("D" calc-angle-mode deg)
12459 ("R" calc-angle-mode rad)
12460 ("F" calc-prefer-frac t)
12461 ("S" calc-symbolic-mode t)))
12462 value (nth 2 var) var (nth 1 var)))
12463 (if (memq var modes)
12464 (setcar (cdr (memq var modes)) value)
12465 (cons var (cons value modes)))
12466 modes)
12468 (defun org-table-eval-formula (&optional arg equation
12469 suppress-align suppress-const
12470 suppress-store)
12471 "Replace the table field value at the cursor by the result of a calculation.
12473 This function makes use of Dave Gillespie's Calc package, in my view the
12474 most exciting program ever written for GNU Emacs. So you need to have Calc
12475 installed in order to use this function.
12477 In a table, this command replaces the value in the current field with the
12478 result of a formula. It also installs the formula as the \"current\" column
12479 formula, by storing it in a special line below the table. When called
12480 with a `C-u' prefix, the current field must ba a named field, and the
12481 formula is installed as valid in only this specific field.
12483 When called, the command first prompts for a formula, which is read in
12484 the minibuffer. Previously entered formulas are available through the
12485 history list, and the last used formula is offered as a default.
12486 These stored formulas are adapted correctly when moving, inserting, or
12487 deleting columns with the corresponding commands.
12489 The formula can be any algebraic expression understood by the Calc package.
12490 For details, see the Org-mode manual.
12492 This function can also be called from Lisp programs and offers
12493 additional arguments: EQUATION can be the formula to apply. If this
12494 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12495 used to speed-up recursive calls by by-passing unnecessary aligns.
12496 SUPPRESS-CONST suppresses the interpretation of constants in the
12497 formula, assuming that this has been done already outside the function.
12498 SUPPRESS-STORE means the formula should not be stored, either because
12499 it is already stored, or because it is a modified equation that should
12500 not overwrite the stored one."
12501 (interactive "P")
12502 (require 'calc)
12503 (org-table-check-inside-data-field)
12504 (org-table-get-specials)
12505 (let* (fields
12506 (ndown (if (integerp arg) arg 1))
12507 (org-table-automatic-realign nil)
12508 (case-fold-search nil)
12509 (down (> ndown 1))
12510 (formula (if (and equation suppress-store)
12511 equation
12512 (org-table-get-formula equation (equal arg '(4)))))
12513 (n0 (org-table-current-column))
12514 (modes (copy-sequence org-calc-default-modes))
12515 n form fmt x ev orig c lispp)
12516 ;; Parse the format string. Since we have a lot of modes, this is
12517 ;; a lot of work. However, I think calc still uses most of the time.
12518 (if (string-match ";" formula)
12519 (let ((tmp (org-split-string formula ";")))
12520 (setq formula (car tmp)
12521 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12522 (nth 1 tmp)))
12523 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
12524 (setq c (string-to-char (match-string 1 fmt))
12525 n (string-to-number (match-string 2 fmt)))
12526 (if (= c ?p)
12527 (setq modes (org-set-calc-mode 'calc-internal-prec n))
12528 (setq modes (org-set-calc-mode
12529 'calc-float-format
12530 (list (cdr (assoc c '((?n . float) (?f . fix)
12531 (?s . sci) (?e . eng))))
12532 n))))
12533 (setq fmt (replace-match "" t t fmt)))
12534 (while (string-match "[DRFS]" fmt)
12535 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12536 (setq fmt (replace-match "" t t fmt)))
12537 (unless (string-match "\\S-" fmt)
12538 (setq fmt nil))))
12539 (if (and (not suppress-const) org-table-formula-use-constants)
12540 (setq formula (org-table-formula-substitute-names formula)))
12541 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12542 (while (> ndown 0)
12543 (setq fields (org-split-string
12544 (buffer-substring
12545 (point-at-bol) (point-at-eol)) " *| *"))
12546 (if org-table-formula-numbers-only
12547 (setq fields (mapcar
12548 (lambda (x) (number-to-string (string-to-number x)))
12549 fields)))
12550 (setq ndown (1- ndown))
12551 (setq form (copy-sequence formula)
12552 lispp (equal (substring form 0 2) "'("))
12553 ;; Insert the references to fields in same row
12554 (while (string-match "\\$\\([0-9]+\\)?" form)
12555 (setq n (if (match-beginning 1)
12556 (string-to-number (match-string 1 form))
12558 x (nth (1- n) fields))
12559 (unless x (error "Invalid field specifier \"%s\""
12560 (match-string 0 form)))
12561 (if (equal x "") (setq x "0"))
12562 (setq form (replace-match
12563 (if lispp x (concat "(" x ")"))
12564 t t form)))
12565 ;; Insert ranges in current column
12566 (while (string-match "\\&[-I0-9]+" form)
12567 (setq form (replace-match
12568 (save-match-data
12569 (org-table-get-vertical-vector (match-string 0 form)
12570 nil n0))
12571 t t form)))
12572 (if lispp
12573 (setq ev (eval (eval (read form)))
12574 ev (if (numberp ev) (number-to-string ev) ev))
12575 (setq ev (calc-eval (cons form modes)
12576 (if org-table-formula-numbers-only 'num))))
12578 (when org-table-formula-debug
12579 (with-output-to-temp-buffer "*Help*"
12580 (princ (format "Substitution history of formula
12581 Orig: %s
12582 $xyz-> %s
12583 $1-> %s\n" orig formula form))
12584 (if (listp ev)
12585 (princ (format " %s^\nError: %s"
12586 (make-string (car ev) ?\-) (nth 1 ev)))
12587 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12588 ev (or fmt "NONE")
12589 (if fmt (format fmt (string-to-number ev)) ev)))))
12590 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12591 (unless (and (interactive-p) (not ndown))
12592 (unless (let (inhibit-redisplay)
12593 (y-or-n-p "Debugging Formula. Continue to next? "))
12594 (org-table-align)
12595 (error "Abort"))
12596 (delete-window (get-buffer-window "*Help*"))
12597 (message "")))
12598 (if (listp ev) (setq fmt nil ev "#ERROR"))
12599 (org-table-justify-field-maybe
12600 (if fmt (format fmt (string-to-number ev)) ev))
12601 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12602 (call-interactively 'org-return)
12603 (setq ndown 0)))
12604 (and down (org-table-maybe-recalculate-line))
12605 (or suppress-align (and org-table-may-need-update
12606 (org-table-align)))))
12608 (defun org-table-recalculate (&optional all noalign)
12609 "Recalculate the current table line by applying all stored formulas.
12610 With prefix arg ALL, do this for all lines in the table."
12611 (interactive "P")
12612 (or (memq this-command org-recalc-commands)
12613 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12614 (unless (org-at-table-p) (error "Not at a table"))
12615 (org-table-get-specials)
12616 (let* ((eqlist (sort (org-table-get-stored-formulas)
12617 (lambda (a b) (string< (car a) (car b)))))
12618 (inhibit-redisplay t)
12619 (line-re org-table-dataline-regexp)
12620 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12621 (thiscol (org-table-current-column))
12622 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12623 ;; Insert constants in all formulas
12624 (setq eqlist
12625 (mapcar (lambda (x)
12626 (setcdr x (org-table-formula-substitute-names (cdr x)))
12628 eqlist))
12629 ;; Split the equation list
12630 (while (setq eq (pop eqlist))
12631 (if (<= (string-to-char (car eq)) ?9)
12632 (push eq eqlnum)
12633 (push eq eqlname)))
12634 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12635 (if all
12636 (progn
12637 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12638 (goto-char (setq beg (org-table-begin)))
12639 (if (re-search-forward org-table-calculate-mark-regexp end t)
12640 ;; This is a table with marked lines, only compute selected lines
12641 (setq line-re org-table-recalculate-regexp)
12642 ;; Move forward to the first non-header line
12643 (if (and (re-search-forward org-table-dataline-regexp end t)
12644 (re-search-forward org-table-hline-regexp end t)
12645 (re-search-forward org-table-dataline-regexp end t))
12646 (setq beg (match-beginning 0))
12647 nil))) ;; just leave beg where it is
12648 (setq beg (point-at-bol)
12649 end (move-marker (make-marker) (1+ (point-at-eol)))))
12650 (goto-char beg)
12651 (and all (message "Re-applying formulas to full table..."))
12652 (while (re-search-forward line-re end t)
12653 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12654 ;; Unprotected line, recalculate
12655 (and all (message "Re-applying formulas to full table...(line %d)"
12656 (setq cnt (1+ cnt))))
12657 (setq org-last-recalc-line (org-current-line))
12658 (setq eql eqlnum)
12659 (while (setq entry (pop eql))
12660 (goto-line org-last-recalc-line)
12661 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12662 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12663 (goto-line thisline)
12664 (org-table-goto-column thiscol)
12665 (or noalign (and org-table-may-need-update (org-table-align))
12666 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12667 ;; Now do the names fields
12668 (while (setq eq (pop eqlname))
12669 (setq name (car eq)
12670 a (assoc name org-table-named-field-locations))
12671 (when a
12672 (message "Re-applying formula to named field: %s" name)
12673 (goto-line (nth 1 a))
12674 (org-table-goto-column (nth 2 a))
12675 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12676 ;; back to initial position
12677 (goto-line thisline)
12678 (org-table-goto-column thiscol)
12679 (or noalign (and org-table-may-need-update (org-table-align))
12680 (and all (message "Re-applying formulas...done")))))
12682 (defun org-table-formula-substitute-names (f)
12683 "Replace $const with values in string F."
12684 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12685 ;; First, check for column names
12686 (while (setq start (string-match org-table-column-name-regexp f start))
12687 (setq start (1+ start))
12688 (setq a (assoc (match-string 1 f) org-table-column-names))
12689 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12690 ;; Expand ranges to vectors
12691 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12692 (setq n1 (string-to-number (match-string 1 f))
12693 n2 (string-to-number (match-string 2 f))
12694 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12695 s (concat "[($" (number-to-string (1- nn1)) ")"))
12696 (loop for i from nn1 upto nn2 do
12697 (setq s (concat s ",($" (int-to-string i) ")")))
12698 (setq s (concat s "]"))
12699 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12700 (setq f (replace-match s t t f)))
12701 ;; Parameters and constants
12702 (setq start 0)
12703 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12704 (setq start (1+ start))
12705 (if (setq a (save-match-data
12706 (org-table-get-constant (match-string 1 f))))
12707 (setq f (replace-match (concat "(" a ")") t t f))))
12708 (if org-table-formula-debug
12709 (put-text-property 0 (length f) :orig-formula f1 f))
12712 (defun org-table-get-constant (const)
12713 "Find the value for a parameter or constant in a formula.
12714 Parameters get priority."
12715 (or (cdr (assoc const org-table-local-parameters))
12716 (cdr (assoc const org-table-formula-constants))
12717 (and (fboundp 'constants-get) (constants-get const))
12718 "#UNDEFINED_NAME"))
12720 (defvar org-edit-formulas-map (make-sparse-keymap))
12721 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12722 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12723 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12725 (defvar org-pos)
12727 (defun org-table-edit-formulas ()
12728 "Edit the formulas of the current table in a separate buffer."
12729 (interactive)
12730 (unless (org-at-table-p)
12731 (error "Not at a table"))
12732 (org-table-get-specials)
12733 (let ((eql (org-table-get-stored-formulas))
12734 (pos (move-marker (make-marker) (point)))
12735 (wc (current-window-configuration))
12736 entry loc s)
12737 (switch-to-buffer-other-window "*Edit Formulas*")
12738 (erase-buffer)
12739 (fundamental-mode)
12740 (org-set-local 'org-pos pos)
12741 (org-set-local 'org-window-configuration wc)
12742 (use-local-map org-edit-formulas-map)
12743 (setq s "# Edit formulas and finish with `C-c C-c'.
12744 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12745 # Use `C-c ?' to get information about $name at point.
12746 # To cancel editing, press `C-c C-q'.\n")
12747 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12748 (insert s)
12749 (while (setq entry (pop eql))
12750 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12751 (setq s (format "# Named formula, referring to column %d in line %d\n"
12752 (nth 2 loc) (nth 1 loc)))
12753 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12754 (insert s))
12755 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12756 (remove-text-properties 0 (length s) '(face nil) s)
12757 (insert s))
12758 (goto-char (point-min))
12759 (message "Edit formulas and finish with `C-c C-c'.")))
12761 (defun org-show-variable ()
12762 "Show the location/value of the $ expression at point."
12763 (interactive)
12764 (let (var (pos org-pos) (win (selected-window)) e)
12765 (save-excursion
12766 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12767 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12768 (setq var (match-string 1))
12769 (error "No variable at point")))
12770 (cond
12771 ((setq e (assoc var org-table-named-field-locations))
12772 (switch-to-buffer-other-window (marker-buffer pos))
12773 (goto-line (nth 1 e))
12774 (org-table-goto-column (nth 2 e))
12775 (select-window win)
12776 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12777 ((setq e (assoc var org-table-column-names))
12778 (switch-to-buffer-other-window (marker-buffer pos))
12779 (goto-char pos)
12780 (goto-char (org-table-begin))
12781 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12782 (org-table-end) t)
12783 (progn
12784 (goto-char (match-beginning 1))
12785 (message "Named column (column %s)" (cdr e)))
12786 (error "Column name not found"))
12787 (select-window win))
12788 ((string-match "^[0-9]$" var)
12789 ;; column number
12790 (switch-to-buffer-other-window (marker-buffer pos))
12791 (goto-char pos)
12792 (goto-char (org-table-begin))
12793 (recenter 1)
12794 (if (re-search-forward org-table-dataline-regexp
12795 (org-table-end) t)
12796 (progn
12797 (goto-char (match-beginning 0))
12798 (org-table-goto-column (string-to-number var))
12799 (message "Column %s" var))
12800 (error "Column name not found"))
12801 (select-window win))
12802 ((setq e (assoc var org-table-local-parameters))
12803 (switch-to-buffer-other-window (marker-buffer pos))
12804 (goto-char pos)
12805 (goto-char (org-table-begin))
12806 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12807 (progn
12808 (goto-char (match-beginning 1))
12809 (message "Local parameter."))
12810 (error "Parameter not found"))
12811 (select-window win))
12813 (cond
12814 ((setq e (assoc var org-table-formula-constants))
12815 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12816 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12817 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12818 (t (error "Undefined name $%s" var)))))))
12820 (defun org-finish-edit-formulas (&optional arg)
12821 "Parse the buffer for formula definitions and install them.
12822 With prefix ARG, apply the new formulas to the table."
12823 (interactive "P")
12824 (let ((pos org-pos) eql)
12825 (goto-char (point-min))
12826 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12827 (push (cons (match-string 1) (match-string 2)) eql))
12828 (set-window-configuration org-window-configuration)
12829 (select-window (get-buffer-window (marker-buffer pos)))
12830 (goto-char pos)
12831 (unless (org-at-table-p)
12832 (error "Lost table position - cannot install formulae"))
12833 (org-table-store-formulas eql)
12834 (move-marker pos nil)
12835 (kill-buffer "*Edit Formulas*")
12836 (if arg
12837 (org-table-recalculate 'all)
12838 (message "New formulas installed - press C-u C-c C-c to apply."))))
12840 (defun org-abort-edit-formulas ()
12841 "Abort editing formulas, without installing the changes."
12842 (interactive)
12843 (let ((pos org-pos))
12844 (set-window-configuration org-window-configuration)
12845 (select-window (get-buffer-window (marker-buffer pos)))
12846 (goto-char pos)
12847 (message "Formula editing aborted without installing changes")))
12849 ;;; The orgtbl minor mode
12851 ;; Define a minor mode which can be used in other modes in order to
12852 ;; integrate the org-mode table editor.
12854 ;; This is really a hack, because the org-mode table editor uses several
12855 ;; keys which normally belong to the major mode, for example the TAB and
12856 ;; RET keys. Here is how it works: The minor mode defines all the keys
12857 ;; necessary to operate the table editor, but wraps the commands into a
12858 ;; function which tests if the cursor is currently inside a table. If that
12859 ;; is the case, the table editor command is executed. However, when any of
12860 ;; those keys is used outside a table, the function uses `key-binding' to
12861 ;; look up if the key has an associated command in another currently active
12862 ;; keymap (minor modes, major mode, global), and executes that command.
12863 ;; There might be problems if any of the keys used by the table editor is
12864 ;; otherwise used as a prefix key.
12866 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12867 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12868 ;; addresses this by checking explicitly for both bindings.
12870 ;; The optimized version (see variable `orgtbl-optimized') takes over
12871 ;; all keys which are bound to `self-insert-command' in the *global map*.
12872 ;; Some modes bind other commands to simple characters, for example
12873 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12874 ;; active, this binding is ignored inside tables and replaced with a
12875 ;; modified self-insert.
12877 (defvar orgtbl-mode nil
12878 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12879 table editor in arbitrary modes.")
12880 (make-variable-buffer-local 'orgtbl-mode)
12882 (defvar orgtbl-mode-map (make-keymap)
12883 "Keymap for `orgtbl-mode'.")
12885 ;;;###autoload
12886 (defun turn-on-orgtbl ()
12887 "Unconditionally turn on `orgtbl-mode'."
12888 (orgtbl-mode 1))
12890 ;;;###autoload
12891 (defun orgtbl-mode (&optional arg)
12892 "The `org-mode' table editor as a minor mode for use in other modes."
12893 (interactive)
12894 (if (org-mode-p)
12895 ;; Exit without error, in case some hook functions calls this
12896 ;; by accident in org-mode.
12897 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12898 (setq orgtbl-mode
12899 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12900 (if orgtbl-mode
12901 (progn
12902 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12903 ;; Make sure we are first in minor-mode-map-alist
12904 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12905 (and c (setq minor-mode-map-alist
12906 (cons c (delq c minor-mode-map-alist)))))
12907 (org-set-local (quote org-table-may-need-update) t)
12908 (org-add-hook 'before-change-functions 'org-before-change-function
12909 nil 'local)
12910 (org-set-local 'org-old-auto-fill-inhibit-regexp
12911 auto-fill-inhibit-regexp)
12912 (org-set-local 'auto-fill-inhibit-regexp
12913 (if auto-fill-inhibit-regexp
12914 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12915 "[ \t]*|"))
12916 (org-add-to-invisibility-spec '(org-cwidth))
12917 (easy-menu-add orgtbl-mode-menu)
12918 (run-hooks 'orgtbl-mode-hook))
12919 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12920 (org-cleanup-narrow-column-properties)
12921 (org-remove-from-invisibility-spec '(org-cwidth))
12922 (remove-hook 'before-change-functions 'org-before-change-function t)
12923 (easy-menu-remove orgtbl-mode-menu)
12924 (force-mode-line-update 'all))))
12926 (defun org-cleanup-narrow-column-properties ()
12927 "Remove all properties related to narrow-column invisibility."
12928 (let ((s 1))
12929 (while (setq s (text-property-any s (point-max)
12930 'display org-narrow-column-arrow))
12931 (remove-text-properties s (1+ s) '(display t)))
12932 (setq s 1)
12933 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12934 (remove-text-properties s (1+ s) '(org-cwidth t)))
12935 (setq s 1)
12936 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12937 (remove-text-properties s (1+ s) '(invisible t)))))
12939 ;; Install it as a minor mode.
12940 (put 'orgtbl-mode :included t)
12941 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12942 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12944 (defun orgtbl-make-binding (fun n &rest keys)
12945 "Create a function for binding in the table minor mode.
12946 FUN is the command to call inside a table. N is used to create a unique
12947 command name. KEYS are keys that should be checked in for a command
12948 to execute outside of tables."
12949 (eval
12950 (list 'defun
12951 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12952 '(arg)
12953 (concat "In tables, run `" (symbol-name fun) "'.\n"
12954 "Outside of tables, run the binding of `"
12955 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12956 "'.")
12957 '(interactive "p")
12958 (list 'if
12959 '(org-at-table-p)
12960 (list 'call-interactively (list 'quote fun))
12961 (list 'let '(orgtbl-mode)
12962 (list 'call-interactively
12963 (append '(or)
12964 (mapcar (lambda (k)
12965 (list 'key-binding k))
12966 keys)
12967 '('orgtbl-error))))))))
12969 (defun orgtbl-error ()
12970 "Error when there is no default binding for a table key."
12971 (interactive)
12972 (error "This key is has no function outside tables"))
12974 (defun orgtbl-setup ()
12975 "Setup orgtbl keymaps."
12976 (let ((nfunc 0)
12977 (bindings
12978 (list
12979 '([(meta shift left)] org-table-delete-column)
12980 '([(meta left)] org-table-move-column-left)
12981 '([(meta right)] org-table-move-column-right)
12982 '([(meta shift right)] org-table-insert-column)
12983 '([(meta shift up)] org-table-kill-row)
12984 '([(meta shift down)] org-table-insert-row)
12985 '([(meta up)] org-table-move-row-up)
12986 '([(meta down)] org-table-move-row-down)
12987 '("\C-c\C-w" org-table-cut-region)
12988 '("\C-c\M-w" org-table-copy-region)
12989 '("\C-c\C-y" org-table-paste-rectangle)
12990 '("\C-c-" org-table-insert-hline)
12991 ; '([(shift tab)] org-table-previous-field)
12992 '("\C-m" org-table-next-row)
12993 (list (org-key 'S-return) 'org-table-copy-down)
12994 '([(meta return)] org-table-wrap-region)
12995 '("\C-c\C-q" org-table-wrap-region)
12996 '("\C-c?" org-table-current-column)
12997 '("\C-c " org-table-blank-field)
12998 '("\C-c+" org-table-sum)
12999 '("\C-c=" org-table-eval-formula)
13000 '("\C-c'" org-table-edit-formulas)
13001 '("\C-c`" org-table-edit-field)
13002 '("\C-c*" org-table-recalculate)
13003 '("\C-c|" org-table-create-or-convert-from-region)
13004 '("\C-c^" org-table-sort-lines)
13005 '([(control ?#)] org-table-rotate-recalc-marks)))
13006 elt key fun cmd)
13007 (while (setq elt (pop bindings))
13008 (setq nfunc (1+ nfunc))
13009 (setq key (car elt)
13010 fun (nth 1 elt)
13011 cmd (orgtbl-make-binding fun nfunc key))
13012 (define-key orgtbl-mode-map key cmd))
13013 ;; Special treatment needed for TAB and RET
13014 (define-key orgtbl-mode-map [(return)]
13015 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
13016 (define-key orgtbl-mode-map "\C-m"
13017 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
13018 (define-key orgtbl-mode-map [(tab)]
13019 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
13020 (define-key orgtbl-mode-map "\C-i"
13021 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
13022 (define-key orgtbl-mode-map "\C-i"
13023 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
13024 (define-key orgtbl-mode-map "\C-c\C-c"
13025 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
13026 (when orgtbl-optimized
13027 ;; If the user wants maximum table support, we need to hijack
13028 ;; some standard editing functions
13029 (org-remap orgtbl-mode-map
13030 'self-insert-command 'orgtbl-self-insert-command
13031 'delete-char 'org-delete-char
13032 'delete-backward-char 'org-delete-backward-char)
13033 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
13034 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
13035 '("OrgTbl"
13036 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
13037 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
13038 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
13039 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
13040 "--"
13041 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
13042 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
13043 ["Copy Field from Above"
13044 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
13045 "--"
13046 ("Column"
13047 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
13048 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
13049 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
13050 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
13051 "--"
13052 ["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])
13053 ("Row"
13054 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
13055 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
13056 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
13057 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
13058 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
13059 "--"
13060 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
13061 ("Rectangle"
13062 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
13063 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
13064 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
13065 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
13066 "--"
13067 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
13068 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13069 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
13070 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
13071 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
13072 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
13073 ["Sum Column/Rectangle" org-table-sum
13074 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
13075 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
13076 ["Debug Formulas"
13077 (setq org-table-formula-debug (not org-table-formula-debug))
13078 :style toggle :selected org-table-formula-debug]
13082 (defun orgtbl-tab (arg)
13083 "Justification and field motion for `orgtbl-mode'."
13084 (interactive "P")
13085 (if arg (org-table-edit-field t)
13086 (org-table-justify-field-maybe)
13087 (org-table-next-field)))
13089 (defun orgtbl-ret ()
13090 "Justification and field motion for `orgtbl-mode'."
13091 (interactive)
13092 (org-table-justify-field-maybe)
13093 (org-table-next-row))
13095 (defun orgtbl-self-insert-command (N)
13096 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13097 If the cursor is in a table looking at whitespace, the whitespace is
13098 overwritten, and the table is not marked as requiring realignment."
13099 (interactive "p")
13100 (if (and (org-at-table-p)
13102 (and org-table-auto-blank-field
13103 (member last-command
13104 '(orgtbl-hijacker-command-100
13105 orgtbl-hijacker-command-101
13106 orgtbl-hijacker-command-102
13107 orgtbl-hijacker-command-103
13108 orgtbl-hijacker-command-104
13109 orgtbl-hijacker-command-105))
13110 (org-table-blank-field))
13112 (eq N 1)
13113 (looking-at "[^|\n]* +|"))
13114 (let (org-table-may-need-update)
13115 (goto-char (1- (match-end 0)))
13116 (delete-backward-char 1)
13117 (goto-char (match-beginning 0))
13118 (self-insert-command N))
13119 (setq org-table-may-need-update t)
13120 (let (orgtbl-mode)
13121 (call-interactively (key-binding (vector last-input-event))))))
13123 (defun org-force-self-insert (N)
13124 "Needed to enforce self-insert under remapping."
13125 (interactive "p")
13126 (self-insert-command N))
13128 ;;; Exporting
13130 (defconst org-level-max 20)
13132 (defvar org-export-html-preamble nil
13133 "Preamble, to be inserted just after <body>. Set by publishing functions.")
13134 (defvar org-export-html-postamble nil
13135 "Preamble, to be inserted just before </body>. Set by publishing functions.")
13136 (defvar org-export-html-auto-preamble t
13137 "Should default preamble be inserted? Set by publishing functions.")
13138 (defvar org-export-html-auto-postamble t
13139 "Should default postamble be inserted? Set by publishing functions.")
13141 (defconst org-export-plist-vars
13142 '((:language . org-export-default-language)
13143 (:headline-levels . org-export-headline-levels)
13144 (:section-numbers . org-export-with-section-numbers)
13145 (:table-of-contents . org-export-with-toc)
13146 (:archived-trees . org-export-with-archived-trees)
13147 (:emphasize . org-export-with-emphasize)
13148 (:sub-superscript . org-export-with-sub-superscripts)
13149 (:TeX-macros . org-export-with-TeX-macros)
13150 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
13151 (:fixed-width . org-export-with-fixed-width)
13152 (:timestamps . org-export-with-timestamps)
13153 (:tables . org-export-with-tables)
13154 (:table-auto-headline . org-export-highlight-first-table-line)
13155 (:style . org-export-html-style)
13156 (:convert-org-links . org-export-html-link-org-files-as-html)
13157 (:inline-images . org-export-html-inline-images)
13158 (:expand-quoted-html . org-export-html-expand)
13159 (:timestamp . org-export-html-with-timestamp)
13160 (:publishing-directory . org-export-publishing-directory)
13161 (:preamble . org-export-html-preamble)
13162 (:postamble . org-export-html-postamble)
13163 (:auto-preamble . org-export-html-auto-preamble)
13164 (:auto-postamble . org-export-html-auto-postamble)
13165 (:author . user-full-name)
13166 (:email . user-mail-address)))
13168 (defun org-default-export-plist ()
13169 "Return the property list with default settings for the export variables."
13170 (let ((l org-export-plist-vars) rtn e)
13171 (while (setq e (pop l))
13172 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
13173 rtn))
13175 (defun org-infile-export-plist ()
13176 "Return the property list with file-local settings for export."
13177 (save-excursion
13178 (goto-char 0)
13179 (let ((re (org-make-options-regexp
13180 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
13181 p key val text options)
13182 (while (re-search-forward re nil t)
13183 (setq key (org-match-string-no-properties 1)
13184 val (org-match-string-no-properties 2))
13185 (cond
13186 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
13187 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
13188 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
13189 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
13190 ((string-equal key "TEXT")
13191 (setq text (if text (concat text "\n" val) val)))
13192 ((string-equal key "OPTIONS") (setq options val))))
13193 (setq p (plist-put p :text text))
13194 (when options
13195 (let ((op '(("H" . :headline-levels)
13196 ("num" . :section-numbers)
13197 ("toc" . :table-of-contents)
13198 ("\\n" . :preserve-breaks)
13199 ("@" . :expand-quoted-html)
13200 (":" . :fixed-width)
13201 ("|" . :tables)
13202 ("^" . :sub-superscript)
13203 ("*" . :emphasize)
13204 ("TeX" . :TeX-macros)
13205 ("LaTeX" . :LaTeX-fragments)))
13207 (while (setq o (pop op))
13208 (if (string-match (concat (regexp-quote (car o))
13209 ":\\([^ \t\n\r;,.]*\\)")
13210 options)
13211 (setq p (plist-put p (cdr o)
13212 (car (read-from-string
13213 (match-string 1 options)))))))))
13214 p)))
13216 (defun org-combine-plists (&rest plists)
13217 "Create a single property list from all plists in PLISTS.
13218 The process starts by copying the last list, and then setting properties
13219 from the other lists. Settings in the first list are the most significant
13220 ones and overrule settings in the other lists."
13221 (let ((rtn (copy-sequence (pop plists)))
13222 p v ls)
13223 (while plists
13224 (setq ls (pop plists))
13225 (while ls
13226 (setq p (pop ls) v (pop ls))
13227 (setq rtn (plist-put rtn p v))))
13228 rtn))
13230 (defun org-export-directory (type plist)
13231 (let* ((val (plist-get plist :publishing-directory))
13232 (dir (if (listp val)
13233 (or (cdr (assoc type val)) ".")
13234 val)))
13235 dir))
13237 (defun org-export-find-first-heading-line (list)
13238 "Remove all lines from LIST which are before the first headline."
13239 (let ((orig-list list)
13240 (re (concat "^" outline-regexp)))
13241 (while (and list
13242 (not (string-match re (car list))))
13243 (pop list))
13244 (or list orig-list)))
13246 (defun org-skip-comments (lines)
13247 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
13248 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
13249 (re2 "^\\(\\*+\\)[ \t\n\r]")
13250 rtn line level)
13251 (while (setq line (pop lines))
13252 (cond
13253 ((and (string-match re1 line)
13254 (setq level (- (match-end 1) (match-beginning 1))))
13255 ;; Beginning of a COMMENT subtree. Skip it.
13256 (while (and (setq line (pop lines))
13257 (or (not (string-match re2 line))
13258 (> (- (match-end 1) (match-beginning 1)) level))))
13259 (setq lines (cons line lines)))
13260 ((string-match "^#" line)
13261 ;; an ordinary comment line
13263 ((and org-export-table-remove-special-lines
13264 (string-match "^[ \t]*|" line)
13265 (or (string-match "^[ \t]*| *[!_^] *|" line)
13266 (and (string-match "| *<[0-9]+> *|" line)
13267 (not (string-match "| *[^ <|]" line)))))
13268 ;; a special table line that should be removed
13270 (t (setq rtn (cons line rtn)))))
13271 (nreverse rtn)))
13273 (defun org-export (&optional arg)
13274 (interactive)
13275 (let ((help "[t] insert the export option template
13276 \[v] limit export to visible part of outline tree
13278 \[a] export as ASCII
13279 \[h] export as HTML
13280 \[b] export as HTML and browse immediately
13281 \[x] export as XOXO
13283 \[i] export current file as iCalendar file
13284 \[I] export all agenda files as iCalendar files
13285 \[c] export agenda files into combined iCalendar file
13287 \[F] publish current file
13288 \[P] publish current project
13289 \[X] publish... (project will be prompted for)
13290 \[A] publish all projects")
13291 (cmds
13292 '((?t . org-insert-export-options-template)
13293 (?v . org-export-visible)
13294 (?a . org-export-as-ascii)
13295 (?h . org-export-as-html)
13296 (?b . org-export-as-html-and-open)
13297 (?x . org-export-as-xoxo)
13298 (?i . org-export-icalendar-this-file)
13299 (?I . org-export-icalendar-all-agenda-files)
13300 (?c . org-export-icalendar-combine-agenda-files)
13301 (?F . org-publish-current-file)
13302 (?P . org-publish-current-project)
13303 (?X . org-publish)
13304 (?A . org-publish-all)))
13305 r1 r2 ass)
13306 (save-window-excursion
13307 (delete-other-windows)
13308 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
13309 (princ help))
13310 (message "Select command: ")
13311 (setq r1 (read-char-exclusive)))
13312 (setq r2 (if (< r1 27) (+ r1 96) r1))
13313 (if (setq ass (assq r2 cmds))
13314 (call-interactively (cdr ass))
13315 (error "No command associated with key %c" r1))))
13317 ;; ASCII
13319 (defconst org-html-entities
13320 '(("nbsp")
13321 ("iexcl")
13322 ("cent")
13323 ("pound")
13324 ("curren")
13325 ("yen")
13326 ("brvbar")
13327 ("sect")
13328 ("uml")
13329 ("copy")
13330 ("ordf")
13331 ("laquo")
13332 ("not")
13333 ("shy")
13334 ("reg")
13335 ("macr")
13336 ("deg")
13337 ("plusmn")
13338 ("sup2")
13339 ("sup3")
13340 ("acute")
13341 ("micro")
13342 ("para")
13343 ("middot")
13344 ("odot"."o")
13345 ("star"."*")
13346 ("cedil")
13347 ("sup1")
13348 ("ordm")
13349 ("raquo")
13350 ("frac14")
13351 ("frac12")
13352 ("frac34")
13353 ("iquest")
13354 ("Agrave")
13355 ("Aacute")
13356 ("Acirc")
13357 ("Atilde")
13358 ("Auml")
13359 ("Aring") ("AA"."&Aring;")
13360 ("AElig")
13361 ("Ccedil")
13362 ("Egrave")
13363 ("Eacute")
13364 ("Ecirc")
13365 ("Euml")
13366 ("Igrave")
13367 ("Iacute")
13368 ("Icirc")
13369 ("Iuml")
13370 ("ETH")
13371 ("Ntilde")
13372 ("Ograve")
13373 ("Oacute")
13374 ("Ocirc")
13375 ("Otilde")
13376 ("Ouml")
13377 ("times")
13378 ("Oslash")
13379 ("Ugrave")
13380 ("Uacute")
13381 ("Ucirc")
13382 ("Uuml")
13383 ("Yacute")
13384 ("THORN")
13385 ("szlig")
13386 ("agrave")
13387 ("aacute")
13388 ("acirc")
13389 ("atilde")
13390 ("auml")
13391 ("aring")
13392 ("aelig")
13393 ("ccedil")
13394 ("egrave")
13395 ("eacute")
13396 ("ecirc")
13397 ("euml")
13398 ("igrave")
13399 ("iacute")
13400 ("icirc")
13401 ("iuml")
13402 ("eth")
13403 ("ntilde")
13404 ("ograve")
13405 ("oacute")
13406 ("ocirc")
13407 ("otilde")
13408 ("ouml")
13409 ("divide")
13410 ("oslash")
13411 ("ugrave")
13412 ("uacute")
13413 ("ucirc")
13414 ("uuml")
13415 ("yacute")
13416 ("thorn")
13417 ("yuml")
13418 ("fnof")
13419 ("Alpha")
13420 ("Beta")
13421 ("Gamma")
13422 ("Delta")
13423 ("Epsilon")
13424 ("Zeta")
13425 ("Eta")
13426 ("Theta")
13427 ("Iota")
13428 ("Kappa")
13429 ("Lambda")
13430 ("Mu")
13431 ("Nu")
13432 ("Xi")
13433 ("Omicron")
13434 ("Pi")
13435 ("Rho")
13436 ("Sigma")
13437 ("Tau")
13438 ("Upsilon")
13439 ("Phi")
13440 ("Chi")
13441 ("Psi")
13442 ("Omega")
13443 ("alpha")
13444 ("beta")
13445 ("gamma")
13446 ("delta")
13447 ("epsilon")
13448 ("varepsilon"."&epsilon;")
13449 ("zeta")
13450 ("eta")
13451 ("theta")
13452 ("iota")
13453 ("kappa")
13454 ("lambda")
13455 ("mu")
13456 ("nu")
13457 ("xi")
13458 ("omicron")
13459 ("pi")
13460 ("rho")
13461 ("sigmaf") ("varsigma"."&sigmaf;")
13462 ("sigma")
13463 ("tau")
13464 ("upsilon")
13465 ("phi")
13466 ("chi")
13467 ("psi")
13468 ("omega")
13469 ("thetasym") ("vartheta"."&thetasym;")
13470 ("upsih")
13471 ("piv")
13472 ("bull") ("bullet"."&bull;")
13473 ("hellip") ("dots"."&hellip;")
13474 ("prime")
13475 ("Prime")
13476 ("oline")
13477 ("frasl")
13478 ("weierp")
13479 ("image")
13480 ("real")
13481 ("trade")
13482 ("alefsym")
13483 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13484 ("uarr") ("uparrow"."&uarr;")
13485 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13486 ("darr")("downarrow"."&darr;")
13487 ("harr") ("leftrightarrow"."&harr;")
13488 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13489 ("lArr") ("Leftarrow"."&lArr;")
13490 ("uArr") ("Uparrow"."&uArr;")
13491 ("rArr") ("Rightarrow"."&rArr;")
13492 ("dArr") ("Downarrow"."&dArr;")
13493 ("hArr") ("Leftrightarrow"."&hArr;")
13494 ("forall")
13495 ("part") ("partial"."&part;")
13496 ("exist") ("exists"."&exist;")
13497 ("empty") ("emptyset"."&empty;")
13498 ("nabla")
13499 ("isin") ("in"."&isin;")
13500 ("notin")
13501 ("ni")
13502 ("prod")
13503 ("sum")
13504 ("minus")
13505 ("lowast") ("ast"."&lowast;")
13506 ("radic")
13507 ("prop") ("proptp"."&prop;")
13508 ("infin") ("infty"."&infin;")
13509 ("ang") ("angle"."&ang;")
13510 ("and") ("vee"."&and;")
13511 ("or") ("wedge"."&or;")
13512 ("cap")
13513 ("cup")
13514 ("int")
13515 ("there4")
13516 ("sim")
13517 ("cong") ("simeq"."&cong;")
13518 ("asymp")("approx"."&asymp;")
13519 ("ne") ("neq"."&ne;")
13520 ("equiv")
13521 ("le")
13522 ("ge")
13523 ("sub") ("subset"."&sub;")
13524 ("sup") ("supset"."&sup;")
13525 ("nsub")
13526 ("sube")
13527 ("supe")
13528 ("oplus")
13529 ("otimes")
13530 ("perp")
13531 ("sdot") ("cdot"."&sdot;")
13532 ("lceil")
13533 ("rceil")
13534 ("lfloor")
13535 ("rfloor")
13536 ("lang")
13537 ("rang")
13538 ("loz") ("Diamond"."&loz;")
13539 ("spades") ("spadesuit"."&spades;")
13540 ("clubs") ("clubsuit"."&clubs;")
13541 ("hearts") ("diamondsuit"."&hearts;")
13542 ("diams") ("diamondsuit"."&diams;")
13543 ("quot")
13544 ("amp")
13545 ("lt")
13546 ("gt")
13547 ("OElig")
13548 ("oelig")
13549 ("Scaron")
13550 ("scaron")
13551 ("Yuml")
13552 ("circ")
13553 ("tilde")
13554 ("ensp")
13555 ("emsp")
13556 ("thinsp")
13557 ("zwnj")
13558 ("zwj")
13559 ("lrm")
13560 ("rlm")
13561 ("ndash")
13562 ("mdash")
13563 ("lsquo")
13564 ("rsquo")
13565 ("sbquo")
13566 ("ldquo")
13567 ("rdquo")
13568 ("bdquo")
13569 ("dagger")
13570 ("Dagger")
13571 ("permil")
13572 ("lsaquo")
13573 ("rsaquo")
13574 ("euro")
13576 ("arccos"."arccos")
13577 ("arcsin"."arcsin")
13578 ("arctan"."arctan")
13579 ("arg"."arg")
13580 ("cos"."cos")
13581 ("cosh"."cosh")
13582 ("cot"."cot")
13583 ("coth"."coth")
13584 ("csc"."csc")
13585 ("deg"."deg")
13586 ("det"."det")
13587 ("dim"."dim")
13588 ("exp"."exp")
13589 ("gcd"."gcd")
13590 ("hom"."hom")
13591 ("inf"."inf")
13592 ("ker"."ker")
13593 ("lg"."lg")
13594 ("lim"."lim")
13595 ("liminf"."liminf")
13596 ("limsup"."limsup")
13597 ("ln"."ln")
13598 ("log"."log")
13599 ("max"."max")
13600 ("min"."min")
13601 ("Pr"."Pr")
13602 ("sec"."sec")
13603 ("sin"."sin")
13604 ("sinh"."sinh")
13605 ("sup"."sup")
13606 ("tan"."tan")
13607 ("tanh"."tanh")
13609 "Entities for TeX->HTML translation.
13610 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13611 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13612 In that case, \"\\ent\" will be translated to \"&other;\".
13613 The list contains HTML entities for Latin-1, Greek and other symbols.
13614 It is supplemented by a number of commonly used TeX macros with appropriate
13615 translations. There is currently no way for users to extend this.")
13617 (defun org-cleaned-string-for-export (string &rest parameters)
13618 "Cleanup a buffer substring so that links can be created safely."
13619 (interactive)
13620 (let* ((re-radio (and org-target-link-regexp
13621 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13622 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13623 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13624 (re-archive (concat ":" org-archive-tag ":"))
13625 rtn)
13626 (save-excursion
13627 (set-buffer (get-buffer-create " org-mode-tmp"))
13628 (erase-buffer)
13629 (insert string)
13630 (let ((org-inhibit-startup t)) (org-mode))
13632 ;; Get rid of archived trees
13633 (when (not (eq org-export-with-archived-trees t))
13634 (goto-char (point-min))
13635 (while (re-search-forward re-archive nil t)
13636 (if (not (org-on-heading-p))
13637 (org-end-of-subtree t)
13638 (beginning-of-line 1)
13639 (delete-region
13640 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13641 (org-end-of-subtree)))))
13643 ;; Find targets in comments and move them out of comments,
13644 ;; but mark them as targets that should be invisible
13645 (goto-char (point-min))
13646 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13647 (replace-match "\\1(INVISIBLE)"))
13649 ;; Find matches for radio targets and turn them into internal links
13650 (goto-char (point-min))
13651 (when re-radio
13652 (while (re-search-forward re-radio nil t)
13653 (replace-match "\\1[[\\2]]")))
13655 ;; Find all links that contain a newline and put them into a single line
13656 (goto-char (point-min))
13657 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13658 (replace-match "\\1 \\3")
13659 (goto-char (match-beginning 0)))
13661 ;; Convert LaTeX fragments to images
13662 (when (memq :LaTeX-fragments parameters)
13663 (org-format-latex
13664 (concat "ltxpng/" (file-name-sans-extension
13665 (file-name-nondirectory
13666 org-current-export-file)))
13667 org-current-export-dir nil "Creating LaTeX image %s"))
13668 (message "Exporting...")
13670 ;; Normalize links: Convert angle and plain links into bracket links
13671 (goto-char (point-min))
13672 (while (re-search-forward re-plain-link nil t)
13673 (replace-match
13674 (concat
13675 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13676 t t))
13677 (goto-char (point-min))
13678 (while (re-search-forward re-angle-link nil t)
13679 (replace-match
13680 (concat
13681 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13682 t t))
13684 ;; Find multiline emphasis and put them into single line
13685 (when (memq :emph-multiline parameters)
13686 (goto-char (point-min))
13687 (while (re-search-forward org-emph-re nil t)
13688 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13689 (goto-char (1- (match-end 0)))))
13691 ;; Remove comments
13692 (goto-char (point-min))
13693 (while (re-search-forward "^#.*\n?" nil t)
13694 (replace-match ""))
13695 (setq rtn (buffer-string)))
13696 (kill-buffer " org-mode-tmp")
13697 rtn))
13699 (defun org-solidify-link-text (s &optional alist)
13700 "Take link text and make a safe target out of it."
13701 (save-match-data
13702 (let* ((rtn
13703 (mapconcat
13704 'identity
13705 (org-split-string s "[ \t\r\n]+") "--"))
13706 (a (assoc rtn alist)))
13707 (or (cdr a) rtn))))
13709 (defun org-convert-to-odd-levels ()
13710 "Convert an org-mode file with all levels allowed to one with odd levels.
13711 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13712 level 5 etc."
13713 (interactive)
13714 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13715 (let ((org-odd-levels-only nil) n)
13716 (save-excursion
13717 (goto-char (point-min))
13718 (while (re-search-forward "^\\*\\*+" nil t)
13719 (setq n (1- (length (match-string 0))))
13720 (while (>= (setq n (1- n)) 0)
13721 (org-demote))
13722 (end-of-line 1))))))
13725 (defun org-convert-to-oddeven-levels ()
13726 "Convert an org-mode file with only odd levels to one with odd and even levels.
13727 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13728 section with an even level, conversion would destroy the structure of the file. An error
13729 is signaled in this case."
13730 (interactive)
13731 (goto-char (point-min))
13732 ;; First check if there are no even levels
13733 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13734 (org-show-hierarchy-above)
13735 (error "Not all levels are odd in this file. Conversion not possible."))
13736 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13737 (let ((org-odd-levels-only nil) n)
13738 (save-excursion
13739 (goto-char (point-min))
13740 (while (re-search-forward "^\\*\\*+" nil t)
13741 (setq n (/ (length (match-string 0)) 2))
13742 (while (>= (setq n (1- n)) 0)
13743 (org-promote))
13744 (end-of-line 1))))))
13746 (defun org-tr-level (n)
13747 "Make N odd if required."
13748 (if org-odd-levels-only (1+ (/ n 2)) n))
13750 (defvar org-last-level nil) ; dynamically scoped variable
13751 (defvar org-ascii-current-indentation nil) ; For communication
13753 (defun org-export-as-ascii (arg)
13754 "Export the outline as a pretty ASCII file.
13755 If there is an active region, export only the region.
13756 The prefix ARG specifies how many levels of the outline should become
13757 underlined headlines. The default is 3."
13758 (interactive "P")
13759 (setq-default org-todo-line-regexp org-todo-line-regexp)
13760 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13761 (org-infile-export-plist)))
13762 (region
13763 (buffer-substring
13764 (if (org-region-active-p) (region-beginning) (point-min))
13765 (if (org-region-active-p) (region-end) (point-max))))
13766 (lines (org-export-find-first-heading-line
13767 (org-skip-comments
13768 (org-split-string
13769 (org-cleaned-string-for-export region)
13770 "[\r\n]"))))
13771 (org-ascii-current-indentation '(0 . 0))
13772 (org-startup-with-deadline-check nil)
13773 (level 0) line txt
13774 (umax nil)
13775 (case-fold-search nil)
13776 (filename (concat (file-name-as-directory
13777 (org-export-directory :ascii opt-plist))
13778 (file-name-sans-extension
13779 (file-name-nondirectory buffer-file-name))
13780 ".txt"))
13781 (buffer (find-file-noselect filename))
13782 (levels-open (make-vector org-level-max nil))
13783 (odd org-odd-levels-only)
13784 (date (format-time-string "%Y/%m/%d" (current-time)))
13785 (time (format-time-string "%X" (org-current-time)))
13786 (author (plist-get opt-plist :author))
13787 (title (or (plist-get opt-plist :title)
13788 (file-name-sans-extension
13789 (file-name-nondirectory buffer-file-name))))
13790 (email (plist-get opt-plist :email))
13791 (language (plist-get opt-plist :language))
13792 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13793 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13794 (text nil)
13795 (todo nil)
13796 (lang-words nil))
13798 (setq org-last-level 1)
13799 (org-init-section-numbers)
13801 (find-file-noselect filename)
13803 (setq lang-words (or (assoc language org-export-language-setup)
13804 (assoc "en" org-export-language-setup)))
13805 (if org-export-ascii-show-new-buffer
13806 (switch-to-buffer-other-window buffer)
13807 (set-buffer buffer))
13808 (erase-buffer)
13809 (fundamental-mode)
13810 ;; create local variables for all options, to make sure all called
13811 ;; functions get the correct information
13812 (mapcar (lambda (x)
13813 (set (make-local-variable (cdr x))
13814 (plist-get opt-plist (car x))))
13815 org-export-plist-vars)
13816 (org-set-local 'org-odd-levels-only odd)
13817 (setq umax (if arg (prefix-numeric-value arg)
13818 org-export-headline-levels))
13820 ;; File header
13821 (if title (org-insert-centered title ?=))
13822 (insert "\n")
13823 (if (or author email)
13824 (insert (concat (nth 1 lang-words) ": " (or author "")
13825 (if email (concat " <" email ">") "")
13826 "\n")))
13827 (if (and date time)
13828 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13829 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13831 (insert "\n\n")
13833 (if org-export-with-toc
13834 (progn
13835 (insert (nth 3 lang-words) "\n"
13836 (make-string (length (nth 3 lang-words)) ?=) "\n")
13837 (mapcar '(lambda (line)
13838 (if (string-match org-todo-line-regexp
13839 line)
13840 ;; This is a headline
13841 (progn
13842 (setq level (- (match-end 1) (match-beginning 1))
13843 level (org-tr-level level)
13844 txt (match-string 3 line)
13845 todo
13846 (or (and org-export-mark-todo-in-toc
13847 (match-beginning 2)
13848 (not (equal (match-string 2 line)
13849 org-done-string)))
13850 ; TODO, not DONE
13851 (and org-export-mark-todo-in-toc
13852 (= level umax)
13853 (org-search-todo-below
13854 line lines level))))
13855 (setq txt (org-html-expand-for-ascii txt))
13857 (if (and (memq org-export-with-tags '(not-in-toc nil))
13858 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
13859 (setq txt (replace-match "" t t txt)))
13860 (if (string-match quote-re0 txt)
13861 (setq txt (replace-match "" t t txt)))
13863 (if org-export-with-section-numbers
13864 (setq txt (concat (org-section-number level)
13865 " " txt)))
13866 (if (<= level umax)
13867 (progn
13868 (insert
13869 (make-string (* (1- level) 4) ?\ )
13870 (format (if todo "%s (*)\n" "%s\n") txt))
13871 (setq org-last-level level))
13872 ))))
13873 lines)))
13875 (org-init-section-numbers)
13876 (while (setq line (pop lines))
13877 ;; Remove the quoted HTML tags.
13878 (setq line (org-html-expand-for-ascii line))
13879 ;; Remove targets
13880 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13881 (setq line (replace-match "" t t line)))
13882 ;; Replace internal links
13883 (while (string-match org-bracket-link-regexp line)
13884 (setq line (replace-match
13885 (if (match-end 3) "[\\3]" "[\\1]")
13886 t nil line)))
13887 (cond
13888 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13889 ;; a Headline
13890 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13891 txt (match-string 2 line))
13892 (org-ascii-level-start level txt umax lines))
13894 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13895 (normal-mode)
13896 (save-buffer)
13897 ;; remove display and invisible chars
13898 (let (beg end)
13899 (goto-char (point-min))
13900 (while (setq beg (next-single-property-change (point) 'display))
13901 (setq end (next-single-property-change beg 'display))
13902 (delete-region beg end)
13903 (goto-char beg)
13904 (insert "=>"))
13905 (goto-char (point-min))
13906 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13907 (setq end (next-single-property-change beg 'org-cwidth))
13908 (delete-region beg end)
13909 (goto-char beg)))
13910 (goto-char (point-min))))
13912 (defun org-search-todo-below (line lines level)
13913 "Search the subtree below LINE for any TODO entries."
13914 (let ((rest (cdr (memq line lines)))
13915 (re org-todo-line-regexp)
13916 line lv todo)
13917 (catch 'exit
13918 (while (setq line (pop rest))
13919 (if (string-match re line)
13920 (progn
13921 (setq lv (- (match-end 1) (match-beginning 1))
13922 todo (and (match-beginning 2)
13923 (not (equal (match-string 2 line)
13924 org-done-string))))
13925 ; TODO, not DONE
13926 (if (<= lv level) (throw 'exit nil))
13927 (if todo (throw 'exit t))))))))
13929 (defun org-html-expand-for-ascii (line)
13930 "Handle quoted HTML for ASCII export."
13931 (if org-export-html-expand
13932 (while (string-match "@<[^<>\n]*>" line)
13933 ;; We just remove the tags for now.
13934 (setq line (replace-match "" nil nil line))))
13935 line)
13937 (defun org-insert-centered (s &optional underline)
13938 "Insert the string S centered and underline it with character UNDERLINE."
13939 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13940 (insert (make-string ind ?\ ) s "\n")
13941 (if underline
13942 (insert (make-string ind ?\ )
13943 (make-string (string-width s) underline)
13944 "\n"))))
13946 (defun org-ascii-level-start (level title umax &optional lines)
13947 "Insert a new level in ASCII export."
13948 (let (char (n (- level umax 1)) (ind 0))
13949 (if (> level umax)
13950 (progn
13951 (insert (make-string (* 2 n) ?\ )
13952 (char-to-string (nth (% n (length org-export-ascii-bullets))
13953 org-export-ascii-bullets))
13954 " " title "\n")
13955 ;; find the indentation of the next non-empty line
13956 (catch 'stop
13957 (while lines
13958 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13959 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13960 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13961 (pop lines)))
13962 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13963 (if (or (not (equal (char-before) ?\n))
13964 (not (equal (char-before (1- (point))) ?\n)))
13965 (insert "\n"))
13966 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13967 (unless org-export-with-tags
13968 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
13969 (setq title (replace-match "" t t title))))
13970 (if org-export-with-section-numbers
13971 (setq title (concat (org-section-number level) " " title)))
13972 (insert title "\n" (make-string (string-width title) char) "\n")
13973 (setq org-ascii-current-indentation '(0 . 0)))))
13975 (defun org-export-visible (type arg)
13976 "Create a copy of the visible part of the current buffer, and export it.
13977 The copy is created in a temporary buffer and removed after use.
13978 TYPE is the final key (as a string) that also select the export command in
13979 the `C-c C-e' export dispatcher.
13980 As a special case, if the you type SPC at the prompt, the temporary
13981 org-mode file will not be removed but presented to you so that you can
13982 continue to use it. The prefix arg ARG is passed through to the exporting
13983 command."
13984 (interactive
13985 (list (progn
13986 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13987 (read-char-exclusive))
13988 current-prefix-arg))
13989 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13990 (error "Invalid export key"))
13991 (let* ((binding (cdr (assoc type
13992 '((?a . org-export-as-ascii)
13993 (?\C-a . org-export-as-ascii)
13994 (?b . org-export-as-html-and-open)
13995 (?\C-b . org-export-as-html-and-open)
13996 (?h . org-export-as-html)
13997 (?x . org-export-as-xoxo)))))
13998 (keepp (equal type ?\ ))
13999 (file buffer-file-name)
14000 (buffer (get-buffer-create "*Org Export Visible*"))
14001 s e)
14002 (with-current-buffer buffer (erase-buffer))
14003 (save-excursion
14004 (setq s (goto-char (point-min)))
14005 (while (not (= (point) (point-max)))
14006 (goto-char (org-find-invisible))
14007 (append-to-buffer buffer s (point))
14008 (setq s (goto-char (org-find-visible))))
14009 (goto-char (point-min))
14010 (unless keepp
14011 ;; Copy all comment lines to the end, to make sure #+ settings are
14012 ;; still available for the second export step. Kind of a hack, but
14013 ;; does do the trick.
14014 (if (looking-at "#[^\r\n]*")
14015 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
14016 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
14017 (append-to-buffer buffer (1+ (match-beginning 0))
14018 (min (point-max) (1+ (match-end 0))))))
14019 (set-buffer buffer)
14020 (let ((buffer-file-name file)
14021 (org-inhibit-startup t))
14022 (org-mode)
14023 (show-all)
14024 (unless keepp (funcall binding arg))))
14025 (if (not keepp)
14026 (kill-buffer buffer)
14027 (switch-to-buffer-other-window buffer)
14028 (goto-char (point-min)))))
14030 (defun org-find-visible ()
14031 (let ((s (point)))
14032 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14033 (get-char-property s 'invisible)))
14035 (defun org-find-invisible ()
14036 (let ((s (point)))
14037 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14038 (not (get-char-property s 'invisible))))
14041 ;; HTML
14043 (defun org-get-current-options ()
14044 "Return a string with current options as keyword options.
14045 Does include HTML export options as well as TODO and CATEGORY stuff."
14046 (format
14047 "#+TITLE: %s
14048 #+AUTHOR: %s
14049 #+EMAIL: %s
14050 #+LANGUAGE: %s
14051 #+TEXT: Some descriptive text to be emitted. Several lines OK.
14052 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
14053 #+CATEGORY: %s
14054 #+SEQ_TODO: %s
14055 #+TYP_TODO: %s
14056 #+STARTUP: %s %s %s %s %s %s
14057 #+TAGS: %s
14058 #+ARCHIVE: %s
14060 (buffer-name) (user-full-name) user-mail-address org-export-default-language
14061 org-export-headline-levels
14062 org-export-with-section-numbers
14063 org-export-with-toc
14064 org-export-preserve-breaks
14065 org-export-html-expand
14066 org-export-with-fixed-width
14067 org-export-with-tables
14068 org-export-with-sub-superscripts
14069 org-export-with-emphasize
14070 org-export-with-TeX-macros
14071 org-export-with-LaTeX-fragments
14072 (file-name-nondirectory buffer-file-name)
14073 (if (equal org-todo-interpretation 'sequence)
14074 (mapconcat 'identity org-todo-keywords " ")
14075 "TODO FEEDBACK VERIFY DONE")
14076 (if (equal org-todo-interpretation 'type)
14077 (mapconcat 'identity org-todo-keywords " ")
14078 "Me Jason Marie DONE")
14079 (cdr (assoc org-startup-folded
14080 '((nil . "showall") (t . "overview") (content . "content"))))
14081 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
14082 (if org-odd-levels-only "odd" "oddeven")
14083 (if org-hide-leading-stars "hidestars" "showstars")
14084 (if org-startup-align-all-tables "align" "noalign")
14085 (if org-log-done "logging" "nologging")
14086 (or (mapconcat (lambda (x)
14087 (cond
14088 ((equal '(:startgroup) x) "{")
14089 ((equal '(:endgroup) x) "}")
14090 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
14091 (t (car x))))
14092 (or org-tag-alist (org-get-buffer-tags)) " ") "")
14093 org-archive-location
14096 (defun org-insert-export-options-template ()
14097 "Insert into the buffer a template with information for exporting."
14098 (interactive)
14099 (if (not (bolp)) (newline))
14100 (let ((s (org-get-current-options)))
14101 (and (string-match "#\\+CATEGORY" s)
14102 (setq s (substring s 0 (match-beginning 0))))
14103 (insert s)))
14105 (defun org-toggle-fixed-width-section (arg)
14106 "Toggle the fixed-width export.
14107 If there is no active region, the QUOTE keyword at the current headline is
14108 inserted or removed. When present, it causes the text between this headline
14109 and the next to be exported as fixed-width text, and unmodified.
14110 If there is an active region, this command adds or removes a colon as the
14111 first character of this line. If the first character of a line is a colon,
14112 this line is also exported in fixed-width font."
14113 (interactive "P")
14114 (let* ((cc 0)
14115 (regionp (org-region-active-p))
14116 (beg (if regionp (region-beginning) (point)))
14117 (end (if regionp (region-end)))
14118 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14119 (re "[ \t]*\\(:\\)")
14120 off)
14121 (if regionp
14122 (save-excursion
14123 (goto-char beg)
14124 (setq cc (current-column))
14125 (beginning-of-line 1)
14126 (setq off (looking-at re))
14127 (while (> nlines 0)
14128 (setq nlines (1- nlines))
14129 (beginning-of-line 1)
14130 (cond
14131 (arg
14132 (move-to-column cc t)
14133 (insert ":\n")
14134 (forward-line -1))
14135 ((and off (looking-at re))
14136 (replace-match "" t t nil 1))
14137 ((not off) (move-to-column cc t) (insert ":")))
14138 (forward-line 1)))
14139 (save-excursion
14140 (org-back-to-heading)
14141 (if (looking-at (concat outline-regexp
14142 "\\( +\\<" org-quote-string "\\>\\)"))
14143 (replace-match "" t t nil 1)
14144 (if (looking-at outline-regexp)
14145 (progn
14146 (goto-char (match-end 0))
14147 (insert " " org-quote-string))))))))
14149 (defun org-export-as-html-and-open (arg)
14150 "Export the outline as HTML and immediately open it with a browser.
14151 If there is an active region, export only the region.
14152 The prefix ARG specifies how many levels of the outline should become
14153 headlines. The default is 3. Lower levels will become bulleted lists."
14154 (interactive "P")
14155 (org-export-as-html arg 'hidden)
14156 (org-open-file buffer-file-name))
14158 (defun org-export-as-html-batch ()
14159 "Call `org-export-as-html', may be used in batch processing as
14160 emacs --batch
14161 --load=$HOME/lib/emacs/org.el
14162 --eval \"(setq org-export-headline-levels 2)\"
14163 --visit=MyFile --funcall org-export-as-html-batch"
14164 (org-export-as-html org-export-headline-levels 'hidden))
14166 (defun org-export-as-html (arg &optional hidden ext-plist)
14167 "Export the outline as a pretty HTML file.
14168 If there is an active region, export only the region.
14169 The prefix ARG specifies how many levels of the outline should become
14170 headlines. The default is 3. Lower levels will become bulleted lists.
14171 When HIDDEN is non-nil, don't display the HTML buffer.
14172 EXT-PLIST is a property list with external parameters overriding
14173 org-mode's default settings, but still inferior to file-local settings."
14174 (interactive "P")
14175 (message "Exporting...")
14176 (setq-default org-todo-line-regexp org-todo-line-regexp)
14177 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
14178 (setq-default org-done-string org-done-string)
14179 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14180 ext-plist
14181 (org-infile-export-plist)))
14183 (style (plist-get opt-plist :style))
14184 (link-validate (plist-get opt-plist :link-validation-function))
14185 valid
14186 (odd org-odd-levels-only)
14187 (region-p (org-region-active-p))
14188 (region
14189 (buffer-substring
14190 (if region-p (region-beginning) (point-min))
14191 (if region-p (region-end) (point-max))))
14192 ;; The following two are dynamically scoped into other
14193 ;; routines below.
14194 (org-current-export-dir (org-export-directory :html opt-plist))
14195 (org-current-export-file buffer-file-name)
14196 (all_lines
14197 (org-skip-comments (org-split-string
14198 (org-cleaned-string-for-export
14199 region :emph-multiline
14200 (if (plist-get opt-plist :LaTeX-fragments)
14201 :LaTeX-fragments))
14202 "[\r\n]")))
14203 (lines (org-export-find-first-heading-line all_lines))
14204 (level 0) (line "") (origline "") txt todo
14205 (umax nil)
14206 (filename (concat (file-name-as-directory
14207 (org-export-directory :html opt-plist))
14208 (file-name-sans-extension
14209 (file-name-nondirectory buffer-file-name))
14210 ".html"))
14211 (current-dir (file-name-directory buffer-file-name))
14212 (buffer (find-file-noselect filename))
14213 (levels-open (make-vector org-level-max nil))
14214 (date (format-time-string "%Y/%m/%d" (current-time)))
14215 (time (format-time-string "%X" (org-current-time)))
14216 (author (plist-get opt-plist :author))
14217 (title (or (plist-get opt-plist :title)
14218 (file-name-sans-extension
14219 (file-name-nondirectory buffer-file-name))))
14220 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14221 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14222 (inquote nil)
14223 (infixed nil)
14224 (in-local-list nil)
14225 (local-list-num nil)
14226 (local-list-indent nil)
14227 (llt org-plain-list-ordered-item-terminator)
14228 (email (plist-get opt-plist :email))
14229 (language (plist-get opt-plist :language))
14230 (text (plist-get opt-plist :text))
14231 (lang-words nil)
14232 (target-alist nil) tg
14233 (head-count 0) cnt
14234 (start 0)
14235 (coding-system (and (boundp 'buffer-file-coding-system)
14236 buffer-file-coding-system))
14237 (coding-system-for-write coding-system)
14238 (save-buffer-coding-system coding-system)
14239 (charset (and coding-system
14240 (fboundp 'coding-system-get)
14241 (coding-system-get coding-system 'mime-charset)))
14242 table-open type
14243 table-buffer table-orig-buffer
14244 ind start-is-num starter
14245 rpl path desc descp desc1 desc2 link
14247 (message "Exporting...")
14249 (setq org-last-level 1)
14250 (org-init-section-numbers)
14252 ;; Get the language-dependent settings
14253 (setq lang-words (or (assoc language org-export-language-setup)
14254 (assoc "en" org-export-language-setup)))
14256 ;; Switch to the output buffer
14257 (if (or hidden (not org-export-html-show-new-buffer))
14258 (set-buffer buffer)
14259 (switch-to-buffer-other-window buffer))
14260 (erase-buffer)
14261 (fundamental-mode)
14262 (let ((case-fold-search nil)
14263 (org-odd-levels-only odd))
14264 ;; create local variables for all options, to make sure all called
14265 ;; functions get the correct information
14266 (mapcar (lambda (x)
14267 (set (make-local-variable (cdr x))
14268 (plist-get opt-plist (car x))))
14269 org-export-plist-vars)
14270 (setq umax (if arg (prefix-numeric-value arg)
14271 org-export-headline-levels))
14273 ;; File header
14274 (insert (format
14275 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
14276 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
14277 <html xmlns=\"http://www.w3.org/1999/xhtml\"
14278 lang=\"%s\" xml:lang=\"%s\">
14279 <head>
14280 <title>%s</title>
14281 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
14282 <meta name=\"generator\" content=\"Org-mode\"/>
14283 <meta name=\"generated\" content=\"%s %s\"/>
14284 <meta name=\"author\" content=\"%s\"/>
14286 </head><body>
14288 language language (org-html-expand title) (or charset "iso-8859-1")
14289 date time author style))
14292 (insert (or (plist-get opt-plist :preamble) ""))
14294 (when (plist-get opt-plist :auto-preamble)
14295 (if title (insert (format org-export-html-title-format
14296 (org-html-expand title))))
14297 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
14299 (if org-export-with-toc
14300 (progn
14301 (insert (format "<h%d>%s</h%d>\n"
14302 org-export-html-toplevel-hlevel
14303 (nth 3 lang-words)
14304 org-export-html-toplevel-hlevel))
14305 (insert "<ul>\n<li>")
14306 (setq lines
14307 (mapcar '(lambda (line)
14308 (if (string-match org-todo-line-regexp line)
14309 ;; This is a headline
14310 (progn
14311 (setq level (- (match-end 1) (match-beginning 1))
14312 level (org-tr-level level)
14313 txt (save-match-data
14314 (org-html-expand
14315 (org-export-cleanup-toc-line
14316 (match-string 3 line))))
14317 todo
14318 (or (and org-export-mark-todo-in-toc
14319 (match-beginning 2)
14320 (not (equal (match-string 2 line)
14321 org-done-string)))
14322 ; TODO, not DONE
14323 (and org-export-mark-todo-in-toc
14324 (= level umax)
14325 (org-search-todo-below
14326 line lines level))))
14327 (if (and (memq org-export-with-tags '(not-in-toc nil))
14328 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14329 (setq txt (replace-match "" t t txt)))
14330 (if (string-match quote-re0 txt)
14331 (setq txt (replace-match "" t t txt)))
14332 (if org-export-with-section-numbers
14333 (setq txt (concat (org-section-number level)
14334 " " txt)))
14335 (if (<= level umax)
14336 (progn
14337 (setq head-count (+ head-count 1))
14338 (if (> level org-last-level)
14339 (progn
14340 (setq cnt (- level org-last-level))
14341 (while (>= (setq cnt (1- cnt)) 0)
14342 (insert "\n<ul>\n<li>"))
14343 (insert "\n")))
14344 (if (< level org-last-level)
14345 (progn
14346 (setq cnt (- org-last-level level))
14347 (while (>= (setq cnt (1- cnt)) 0)
14348 (insert "</li>\n</ul>"))
14349 (insert "\n")))
14350 ;; Check for targets
14351 (while (string-match org-target-regexp line)
14352 (setq tg (match-string 1 line)
14353 line (replace-match
14354 (concat "@<span class=\"target\">" tg "@</span> ")
14355 t t line))
14356 (push (cons (org-solidify-link-text tg)
14357 (format "sec-%d" head-count))
14358 target-alist))
14359 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14360 (setq txt (replace-match "" t t txt)))
14361 (insert
14362 (format
14363 (if todo
14364 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14365 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14366 head-count txt))
14368 (setq org-last-level level))
14370 line)
14371 lines))
14372 (while (> org-last-level 0)
14373 (setq org-last-level (1- org-last-level))
14374 (insert "</li>\n</ul>\n"))
14376 (setq head-count 0)
14377 (org-init-section-numbers)
14379 (while (setq line (pop lines) origline line)
14380 (catch 'nextline
14382 ;; end of quote section?
14383 (when (and inquote (string-match "^\\*+" line))
14384 (insert "</pre>\n")
14385 (setq inquote nil))
14386 ;; inside a quote section?
14387 (when inquote
14388 (insert (org-html-protect line) "\n")
14389 (throw 'nextline nil))
14391 ;; verbatim lines
14392 (when (and org-export-with-fixed-width
14393 (string-match "^[ \t]*:\\(.*\\)" line))
14394 (when (not infixed)
14395 (setq infixed t)
14396 (insert "<pre>\n"))
14397 (insert (org-html-protect (match-string 1 line)) "\n")
14398 (when (and lines
14399 (not (string-match "^[ \t]*\\(:.*\\)"
14400 (car lines))))
14401 (setq infixed nil)
14402 (insert "</pre>\n"))
14403 (throw 'nextline nil))
14406 ;; make targets to anchors
14407 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14408 (cond
14409 ((match-end 2)
14410 (setq line (replace-match
14411 (concat "@<a name=\""
14412 (org-solidify-link-text (match-string 1 line))
14413 "\">\\nbsp@</a>")
14414 t t line)))
14415 ((and org-export-with-toc (equal (string-to-char line) ?*))
14416 (setq line (replace-match
14417 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14418 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14419 t t line)))
14421 (setq line (replace-match
14422 (concat "@<a name=\""
14423 (org-solidify-link-text (match-string 1 line))
14424 "\" class=\"target\">" (match-string 1 line) "@</a> ")
14425 t t line)))))
14427 (setq line (org-html-handle-time-stamps line))
14429 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
14430 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
14431 ;; Also handle sub_superscripts and checkboxes
14432 (setq line (org-html-expand line))
14434 ;; Format the links
14435 (setq start 0)
14436 (while (string-match org-bracket-link-analytic-regexp line start)
14437 (setq start (match-beginning 0))
14438 (setq type (if (match-end 2) (match-string 2 line) "internal"))
14439 (setq path (match-string 3 line))
14440 (setq desc1 (if (match-end 5) (match-string 5 line))
14441 desc2 (if (match-end 2) (concat type ":" path) path)
14442 descp (and desc1 (not (equal desc1 desc2)))
14443 desc (or desc1 desc2))
14444 ;; FIXME: do we need to unescape here somewhere?
14445 (cond
14446 ((equal type "internal")
14447 (setq rpl
14448 (concat
14449 "<a href=\"#"
14450 (org-solidify-link-text path target-alist)
14451 "\">" desc "</a>")))
14452 ((member type '("http" "https" "ftp" "mailto" "news"))
14453 ;; standard URL
14454 (setq link (concat type ":" path))
14455 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14456 ((string= type "file")
14457 ;; FILE link
14458 (let* ((filename path)
14459 (abs-p (file-name-absolute-p filename))
14460 thefile file-is-image-p search)
14461 (save-match-data
14462 (if (string-match "::\\(.*\\)" filename)
14463 (setq search (match-string 1 filename)
14464 filename (replace-match "" t nil filename)))
14465 (setq valid
14466 (if (functionp link-validate)
14467 (funcall link-validate filename current-dir)
14468 t))
14469 (setq file-is-image-p
14470 (string-match (org-image-file-name-regexp) filename))
14471 (setq thefile (if abs-p (expand-file-name filename) filename))
14472 (when (and org-export-html-link-org-files-as-html
14473 (string-match "\\.org$" thefile))
14474 (setq thefile (concat (substring thefile 0
14475 (match-beginning 0))
14476 ".html"))
14477 (if (and search
14478 ;; make sure this is can be used as target search
14479 (not (string-match "^[0-9]*$" search))
14480 (not (string-match "^\\*" search))
14481 (not (string-match "^/.*/$" search)))
14482 (setq thefile (concat thefile "#"
14483 (org-solidify-link-text
14484 (org-link-unescape search)))))
14485 (when (string-match "^file:" desc)
14486 (setq desc (replace-match "" t t desc))
14487 (if (string-match "\\.org$" desc)
14488 (setq desc (replace-match "" t t desc))))))
14489 (setq rpl (if (and file-is-image-p
14490 (or (eq t org-export-html-inline-images)
14491 (and org-export-html-inline-images
14492 (not descp))))
14493 (concat "<img src=\"" thefile "\"/>")
14494 (concat "<a href=\"" thefile "\">" desc "</a>")))
14495 (if (not valid) (setq rpl desc))))
14496 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14497 (setq rpl (concat "<i>&lt;" type ":"
14498 (save-match-data (org-link-unescape path))
14499 "&gt;</i>"))))
14500 (setq line (replace-match rpl t t line)
14501 start (+ start (length rpl))))
14502 ;; TODO items
14503 (if (and (string-match org-todo-line-regexp line)
14504 (match-beginning 2))
14505 (if (equal (match-string 2 line) org-done-string)
14506 (setq line (replace-match
14507 "<span class=\"done\">\\2</span>"
14508 t nil line 2))
14509 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14510 t nil line 2))))
14512 (cond
14513 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14514 ;; This is a headline
14515 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14516 txt (match-string 2 line))
14517 (if (string-match quote-re0 txt)
14518 (setq txt (replace-match "" t t txt)))
14519 (if (<= level umax) (setq head-count (+ head-count 1)))
14520 (when in-local-list
14521 ;; Close any local lists before inserting a new header line
14522 (while local-list-num
14523 (org-close-li)
14524 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14525 (pop local-list-num))
14526 (setq local-list-indent nil
14527 in-local-list nil))
14528 (org-html-level-start level txt umax
14529 (and org-export-with-toc (<= level umax))
14530 head-count)
14531 ;; QUOTES
14532 (when (string-match quote-re line)
14533 (insert "<pre>")
14534 (setq inquote t)))
14536 ((and org-export-with-tables
14537 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14538 (if (not table-open)
14539 ;; New table starts
14540 (setq table-open t table-buffer nil table-orig-buffer nil))
14541 ;; Accumulate lines
14542 (setq table-buffer (cons line table-buffer)
14543 table-orig-buffer (cons origline table-orig-buffer))
14544 (when (or (not lines)
14545 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14546 (car lines))))
14547 (setq table-open nil
14548 table-buffer (nreverse table-buffer)
14549 table-orig-buffer (nreverse table-orig-buffer))
14550 (org-close-par-maybe)
14551 (insert (org-format-table-html table-buffer table-orig-buffer))))
14553 ;; Normal lines
14554 (when (string-match
14555 (cond
14556 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14557 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14558 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14559 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14560 line)
14561 (setq ind (org-get-string-indentation line)
14562 start-is-num (match-beginning 4)
14563 starter (if (match-beginning 2)
14564 (substring (match-string 2 line) 0 -1))
14565 line (substring line (match-beginning 5)))
14566 (unless (string-match "[^ \t]" line)
14567 ;; empty line. Pretend indentation is large.
14568 (setq ind (1+ (or (car local-list-indent) 1))))
14569 (while (and in-local-list
14570 (or (and (= ind (car local-list-indent))
14571 (not starter))
14572 (< ind (car local-list-indent))))
14573 (org-close-li)
14574 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14575 (pop local-list-num) (pop local-list-indent)
14576 (setq in-local-list local-list-indent))
14577 (cond
14578 ((and starter
14579 (or (not in-local-list)
14580 (> ind (car local-list-indent))))
14581 ;; Start new (level of ) list
14582 (org-close-par-maybe)
14583 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14584 (push start-is-num local-list-num)
14585 (push ind local-list-indent)
14586 (setq in-local-list t))
14587 (starter
14588 ;; continue current list
14589 (org-close-li)
14590 (insert "<li>\n")))
14591 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14592 (setq line
14593 (replace-match
14594 (if (equal (match-string 1 line) "X")
14595 "<b>[X]</b>"
14596 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14597 t t line))))
14599 ;; Empty lines start a new paragraph. If hand-formatted lists
14600 ;; are not fully interpreted, lines starting with "-", "+", "*"
14601 ;; also start a new paragraph.
14602 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14604 ;; Check if the line break needs to be conserved
14605 (cond
14606 ((string-match "\\\\\\\\[ \t]*$" line)
14607 (setq line (replace-match "<br/>" t t line)))
14608 (org-export-preserve-breaks
14609 (setq line (concat line "<br/>"))))
14611 (insert line "\n")))))
14613 ;; Properly close all local lists and other lists
14614 (when inquote (insert "</pre>\n"))
14615 (when in-local-list
14616 ;; Close any local lists before inserting a new header line
14617 (while local-list-num
14618 (org-close-li)
14619 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14620 (pop local-list-num))
14621 (setq local-list-indent nil
14622 in-local-list nil))
14623 (org-html-level-start 1 nil umax
14624 (and org-export-with-toc (<= level umax))
14625 head-count)
14627 (when (plist-get opt-plist :auto-postamble)
14628 (when author
14629 (insert "<p class=\"author\"> "
14630 (nth 1 lang-words) ": " author "\n")
14631 (when email
14632 (insert "<a href=\"mailto:" email "\">&lt;"
14633 email "&gt;</a>\n"))
14634 (insert "</p>\n"))
14635 (when (and date time)
14636 (insert "<p class=\"date\"> "
14637 (nth 2 lang-words) ": "
14638 date " " time "</p>\n")))
14640 (if org-export-html-with-timestamp
14641 (insert org-export-html-html-helper-timestamp))
14642 (insert (or (plist-get opt-plist :postamble) ""))
14643 (insert "</body>\n</html>\n")
14644 (normal-mode)
14645 ;; remove empty paragraphs and lists
14646 (goto-char (point-min))
14647 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14648 (replace-match ""))
14649 (goto-char (point-min))
14650 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14651 (replace-match ""))
14652 (save-buffer)
14653 (goto-char (point-min))
14654 (message "Exporting... done"))))
14657 (defun org-format-table-html (lines olines)
14658 "Find out which HTML converter to use and return the HTML code."
14659 (if (string-match "^[ \t]*|" (car lines))
14660 ;; A normal org table
14661 (org-format-org-table-html lines)
14662 ;; Table made by table.el - test for spanning
14663 (let* ((hlines (delq nil (mapcar
14664 (lambda (x)
14665 (if (string-match "^[ \t]*\\+-" x) x
14666 nil))
14667 lines)))
14668 (first (car hlines))
14669 (ll (and (string-match "\\S-+" first)
14670 (match-string 0 first)))
14671 (re (concat "^[ \t]*" (regexp-quote ll)))
14672 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14673 hlines))))
14674 (if (and (not spanning)
14675 (not org-export-prefer-native-exporter-for-tables))
14676 ;; We can use my own converter with HTML conversions
14677 (org-format-table-table-html lines)
14678 ;; Need to use the code generator in table.el, with the original text.
14679 (org-format-table-table-html-using-table-generate-source olines)))))
14681 (defun org-format-org-table-html (lines)
14682 "Format a table into HTML."
14683 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14684 (setq lines (nreverse lines))
14685 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14686 (setq lines (nreverse lines))
14687 (when org-export-table-remove-special-lines
14688 ;; Check if the table has a marking column. If yes remove the
14689 ;; column and the special lines
14690 (let* ((special
14691 (not
14692 (memq nil
14693 (mapcar
14694 (lambda (x)
14695 (or (string-match "^[ \t]*|-" x)
14696 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14697 lines)))))
14698 (if special
14699 (setq lines
14700 (delq nil
14701 (mapcar
14702 (lambda (x)
14703 (if (string-match "^[ \t]*| *[!_^] *|" x)
14704 nil ; ignore this line
14705 (and (or (string-match "^[ \t]*|-+\\+" x)
14706 (string-match "^[ \t]*|[^|]*|" x))
14707 (replace-match "|" t t x))))
14708 lines))))))
14710 (let ((head (and org-export-highlight-first-table-line
14711 (delq nil (mapcar
14712 (lambda (x) (string-match "^[ \t]*|-" x))
14713 (cdr lines)))))
14714 line fields html)
14715 (setq html (concat org-export-html-table-tag "\n"))
14716 (while (setq line (pop lines))
14717 (catch 'next-line
14718 (if (string-match "^[ \t]*|-" line)
14719 (progn
14720 (setq head nil) ;; head ends here, first time around
14721 ;; ignore this line
14722 (throw 'next-line t)))
14723 ;; Break the line into fields
14724 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14725 (setq html (concat
14726 html
14727 "<tr>"
14728 (mapconcat (lambda (x)
14729 (if head
14730 (concat "<th>" x "</th>")
14731 (concat "<td>" x "</td>")))
14732 fields "")
14733 "</tr>\n"))))
14734 (setq html (concat html "</table>\n"))
14735 html))
14737 (defun org-fake-empty-table-line (line)
14738 "Replace everything except \"|\" with spaces."
14739 (let ((i (length line))
14740 (newstr (copy-sequence line)))
14741 (while (> i 0)
14742 (setq i (1- i))
14743 (if (not (eq (aref newstr i) ?|))
14744 (aset newstr i ?\ )))
14745 newstr))
14747 (defun org-format-table-table-html (lines)
14748 "Format a table generated by table.el into HTML.
14749 This conversion does *not* use `table-generate-source' from table.el.
14750 This has the advantage that Org-mode's HTML conversions can be used.
14751 But it has the disadvantage, that no cell- or row-spanning is allowed."
14752 (let (line field-buffer
14753 (head org-export-highlight-first-table-line)
14754 fields html empty)
14755 (setq html (concat org-export-html-table-tag "\n"))
14756 (while (setq line (pop lines))
14757 (setq empty "&nbsp;")
14758 (catch 'next-line
14759 (if (string-match "^[ \t]*\\+-" line)
14760 (progn
14761 (if field-buffer
14762 (progn
14763 (setq html (concat
14764 html
14765 "<tr>"
14766 (mapconcat
14767 (lambda (x)
14768 (if (equal x "") (setq x empty))
14769 (if head
14770 (concat "<th>" x "</th>\n")
14771 (concat "<td>" x "</td>\n")))
14772 field-buffer "\n")
14773 "</tr>\n"))
14774 (setq head nil)
14775 (setq field-buffer nil)))
14776 ;; Ignore this line
14777 (throw 'next-line t)))
14778 ;; Break the line into fields and store the fields
14779 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14780 (if field-buffer
14781 (setq field-buffer (mapcar
14782 (lambda (x)
14783 (concat x "<br/>" (pop fields)))
14784 field-buffer))
14785 (setq field-buffer fields))))
14786 (setq html (concat html "</table>\n"))
14787 html))
14789 (defun org-format-table-table-html-using-table-generate-source (lines)
14790 "Format a table into html, using `table-generate-source' from table.el.
14791 This has the advantage that cell- or row-spanning is allowed.
14792 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14793 (require 'table)
14794 (with-current-buffer (get-buffer-create " org-tmp1 ")
14795 (erase-buffer)
14796 (insert (mapconcat 'identity lines "\n"))
14797 (goto-char (point-min))
14798 (if (not (re-search-forward "|[^+]" nil t))
14799 (error "Error processing table"))
14800 (table-recognize-table)
14801 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14802 (table-generate-source 'html " org-tmp2 ")
14803 (set-buffer " org-tmp2 ")
14804 (buffer-substring (point-min) (point-max))))
14806 (defun org-html-handle-time-stamps (s)
14807 "Format time stamps in string S, or remove them."
14808 (catch 'exit
14809 (let (r b)
14810 (while (string-match org-maybe-keyword-time-regexp s)
14811 ;; FIXME: is it good to never export CLOCK, or do we need control?
14812 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14813 (throw 'exit ""))
14814 (or b (setq b (substring s 0 (match-beginning 0))))
14815 (if (not org-export-with-timestamps)
14816 (setq r (concat r (substring s 0 (match-beginning 0)))
14817 s (substring s (match-end 0)))
14818 (setq r (concat
14819 r (substring s 0 (match-beginning 0))
14820 (if (match-end 1)
14821 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14822 (match-string 1 s)))
14823 (format " @<span class=\"timestamp\">%s@</span>"
14824 (substring (match-string 3 s) 1 -1)))
14825 s (substring s (match-end 0)))))
14826 ;; Line break if line started and ended with time stamp stuff
14827 (if (not r)
14829 (setq r (concat r s))
14830 (unless (string-match "\\S-" (concat b s))
14831 (setq r (concat r "@<br/>")))
14832 r))))
14834 (defun org-html-protect (s)
14835 ;; convert & to &amp;, < to &lt; and > to &gt;
14836 (let ((start 0))
14837 (while (string-match "&" s start)
14838 (setq s (replace-match "&amp;" t t s)
14839 start (1+ (match-beginning 0))))
14840 (while (string-match "<" s)
14841 (setq s (replace-match "&lt;" t t s)))
14842 (while (string-match ">" s)
14843 (setq s (replace-match "&gt;" t t s))))
14846 (defun org-export-cleanup-toc-line (s)
14847 "Remove tags and time staps from lines going into the toc."
14848 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14849 (setq s (replace-match "" t t s)))
14850 (when org-export-remove-timestamps-from-toc
14851 (while (string-match org-maybe-keyword-time-regexp s)
14852 (setq s (replace-match "" t t s))))
14855 (defun org-html-expand (string)
14856 "Prepare STRING for HTML export. Applies all active conversions.
14857 If there are links in the string, don't modify these."
14858 (let* (m s l res)
14859 (while (setq m (string-match org-bracket-link-regexp string))
14860 (setq s (substring string 0 m)
14861 l (match-string 0 string)
14862 string (substring string (match-end 0)))
14863 (push (org-html-do-expand s) res)
14864 (push l res))
14865 (push (org-html-do-expand string) res)
14866 (apply 'concat (nreverse res))))
14868 (defun org-html-do-expand (s)
14869 "Apply all active conversions to translate special ASCII to HTML."
14870 (setq s (org-html-protect s))
14871 (if org-export-html-expand
14872 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14873 (setq s (replace-match "<\\1>" t nil s))))
14874 (if org-export-with-emphasize
14875 (setq s (org-export-html-convert-emphasize s)))
14876 (if org-export-with-sub-superscripts
14877 (setq s (org-export-html-convert-sub-super s)))
14878 (if org-export-with-TeX-macros
14879 (let ((start 0) wd ass)
14880 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14881 (setq wd (match-string 1 s))
14882 (if (setq ass (assoc wd org-html-entities))
14883 (setq s (replace-match (or (cdr ass)
14884 (concat "&" (car ass) ";"))
14885 t t s))
14886 (setq start (+ start (length wd)))))))
14889 (defun org-create-multibrace-regexp (left right n)
14890 "Create a regular expression which will match a balanced sexp.
14891 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14892 as single character strings.
14893 The regexp returned will match the entire expression including the
14894 delimiters. It will also define a single group which contains the
14895 match except for the outermost delimiters. The maximum depth of
14896 stacked delimiters is N. Escaping delimiters is not possible."
14897 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14898 (or "\\|")
14899 (re nothing)
14900 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14901 (while (> n 1)
14902 (setq n (1- n)
14903 re (concat re or next)
14904 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14905 (concat left "\\(" re "\\)" right)))
14907 (defvar org-match-substring-regexp
14908 (concat
14909 "\\([^\\]\\)\\([_^]\\)\\("
14910 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14911 "\\|"
14912 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14913 "\\|"
14914 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14915 "The regular expression matching a sub- or superscript.")
14917 (defun org-export-html-convert-sub-super (string)
14918 "Convert sub- and superscripts in STRING to HTML."
14919 (let (key c)
14920 (while (string-match org-match-substring-regexp string)
14921 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14922 (setq c (or (match-string 8 string)
14923 (match-string 6 string)
14924 (match-string 5 string)))
14925 (setq string (replace-match
14926 (concat (match-string 1 string)
14927 "<" key ">" c "</" key ">")
14928 t t string)))
14929 (while (string-match "\\\\\\([_^]\\)" string)
14930 (setq string (replace-match (match-string 1 string) t t string))))
14931 string)
14933 (defun org-export-html-convert-emphasize (string)
14934 "Apply emphasis."
14935 (while (string-match org-emph-re string)
14936 (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)))
14937 string)
14939 (defvar org-par-open nil)
14940 (defun org-open-par ()
14941 "Insert <p>, but first close previous paragraph if any."
14942 (org-close-par-maybe)
14943 (insert "\n<p>")
14944 (setq org-par-open t))
14945 (defun org-close-par-maybe ()
14946 "Close paragraph if there is one open."
14947 (when org-par-open
14948 (insert "</p>")
14949 (setq org-par-open nil)))
14950 (defun org-close-li ()
14951 "Close <li> if necessary."
14952 (org-close-par-maybe)
14953 (insert "</li>\n"))
14954 ; (when (save-excursion
14955 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14956 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14957 ; (insert "</li>"))))
14959 (defun org-html-level-start (level title umax with-toc head-count)
14960 "Insert a new level in HTML export.
14961 When TITLE is nil, just close all open levels."
14962 (org-close-par-maybe)
14963 (let ((l (1+ (max level umax))))
14964 (while (<= l org-level-max)
14965 (if (aref levels-open (1- l))
14966 (progn
14967 (org-html-level-close l)
14968 (aset levels-open (1- l) nil)))
14969 (setq l (1+ l)))
14970 (when title
14971 ;; If title is nil, this means this function is called to close
14972 ;; all levels, so the rest is done only if title is given
14973 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14974 (setq title (replace-match
14975 (if org-export-with-tags
14976 (save-match-data
14977 (concat
14978 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14979 (mapconcat 'identity (org-split-string
14980 (match-string 1 title) ":")
14981 "&nbsp;")
14982 "</span>"))
14984 t t title)))
14985 (if (> level umax)
14986 (progn
14987 (if (aref levels-open (1- level))
14988 (progn
14989 (org-close-li)
14990 (insert "<li>" title "<br/>\n"))
14991 (aset levels-open (1- level) t)
14992 (org-close-par-maybe)
14993 (insert "<ul>\n<li>" title "<br/>\n")))
14994 (if org-export-with-section-numbers
14995 (setq title (concat (org-section-number level) " " title)))
14996 (setq level (+ level org-export-html-toplevel-hlevel -1))
14997 (if with-toc
14998 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14999 level head-count title level))
15000 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
15001 (org-open-par)))))
15003 (defun org-html-level-close (&rest args)
15004 "Terminate one level in HTML export."
15005 (org-close-li)
15006 (insert "</ul>"))
15008 ;; Variable holding the vector with section numbers
15009 (defvar org-section-numbers (make-vector org-level-max 0))
15011 (defun org-init-section-numbers ()
15012 "Initialize the vector for the section numbers."
15013 (let* ((level -1)
15014 (numbers (nreverse (org-split-string "" "\\.")))
15015 (depth (1- (length org-section-numbers)))
15016 (i depth) number-string)
15017 (while (>= i 0)
15018 (if (> i level)
15019 (aset org-section-numbers i 0)
15020 (setq number-string (or (car numbers) "0"))
15021 (if (string-match "\\`[A-Z]\\'" number-string)
15022 (aset org-section-numbers i
15023 (- (string-to-char number-string) ?A -1))
15024 (aset org-section-numbers i (string-to-number number-string)))
15025 (pop numbers))
15026 (setq i (1- i)))))
15028 (defun org-section-number (&optional level)
15029 "Return a string with the current section number.
15030 When LEVEL is non-nil, increase section numbers on that level."
15031 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
15032 (when level
15033 (when (> level -1)
15034 (aset org-section-numbers
15035 level (1+ (aref org-section-numbers level))))
15036 (setq idx (1+ level))
15037 (while (<= idx depth)
15038 (if (not (= idx 1))
15039 (aset org-section-numbers idx 0))
15040 (setq idx (1+ idx))))
15041 (setq idx 0)
15042 (while (<= idx depth)
15043 (setq n (aref org-section-numbers idx))
15044 (setq string (concat string (if (not (string= string "")) "." "")
15045 (int-to-string n)))
15046 (setq idx (1+ idx)))
15047 (save-match-data
15048 (if (string-match "\\`\\([@0]\\.\\)+" string)
15049 (setq string (replace-match "" t nil string)))
15050 (if (string-match "\\(\\.0\\)+\\'" string)
15051 (setq string (replace-match "" t nil string))))
15052 string))
15055 ;;;###autoload
15056 (defun org-export-icalendar-this-file ()
15057 "Export current file as an iCalendar file.
15058 The iCalendar file will be located in the same directory as the Org-mode
15059 file, but with extension `.ics'."
15060 (interactive)
15061 (org-export-icalendar nil buffer-file-name))
15063 (defun org-export-as-xoxo-insert-into (buffer &rest output)
15064 (with-current-buffer buffer
15065 (apply 'insert output)))
15066 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
15068 (defun org-export-as-xoxo (&optional buffer)
15069 "Export the org buffer as XOXO.
15070 The XOXO buffer is named *xoxo-<source buffer name>*"
15071 (interactive (list (current-buffer)))
15072 ;; A quickie abstraction
15074 ;; Output everything as XOXO
15075 (with-current-buffer (get-buffer buffer)
15076 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
15077 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15078 (org-infile-export-plist)))
15079 (filename (concat (file-name-as-directory
15080 (org-export-directory :xoxo opt-plist))
15081 (file-name-sans-extension
15082 (file-name-nondirectory buffer-file-name))
15083 ".html"))
15084 (out (find-file-noselect filename))
15085 (last-level 1)
15086 (hanging-li nil))
15087 ;; Check the output buffer is empty.
15088 (with-current-buffer out (erase-buffer))
15089 ;; Kick off the output
15090 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
15091 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
15092 (let* ((hd (match-string-no-properties 1))
15093 (level (length hd))
15094 (text (concat
15095 (match-string-no-properties 2)
15096 (save-excursion
15097 (goto-char (match-end 0))
15098 (let ((str ""))
15099 (catch 'loop
15100 (while 't
15101 (forward-line)
15102 (if (looking-at "^[ \t]\\(.*\\)")
15103 (setq str (concat str (match-string-no-properties 1)))
15104 (throw 'loop str)))))))))
15106 ;; Handle level rendering
15107 (cond
15108 ((> level last-level)
15109 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
15111 ((< level last-level)
15112 (dotimes (- (- last-level level) 1)
15113 (if hanging-li
15114 (org-export-as-xoxo-insert-into out "</li>\n"))
15115 (org-export-as-xoxo-insert-into out "</ol>\n"))
15116 (when hanging-li
15117 (org-export-as-xoxo-insert-into out "</li>\n")
15118 (setq hanging-li nil)))
15120 ((equal level last-level)
15121 (if hanging-li
15122 (org-export-as-xoxo-insert-into out "</li>\n")))
15125 (setq last-level level)
15127 ;; And output the new li
15128 (setq hanging-li 't)
15129 (if (equal ?+ (elt text 0))
15130 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
15131 (org-export-as-xoxo-insert-into out "<li>" text))))
15133 ;; Finally finish off the ol
15134 (dotimes (- last-level 1)
15135 (if hanging-li
15136 (org-export-as-xoxo-insert-into out "</li>\n"))
15137 (org-export-as-xoxo-insert-into out "</ol>\n"))
15139 ;; Finish the buffer off and clean it up.
15140 (switch-to-buffer-other-window out)
15141 (indent-region (point-min) (point-max) nil)
15142 (save-buffer)
15143 (goto-char (point-min))
15146 ;;;###autoload
15147 (defun org-export-icalendar-all-agenda-files ()
15148 "Export all files in `org-agenda-files' to iCalendar .ics files.
15149 Each iCalendar file will be located in the same directory as the Org-mode
15150 file, but with extension `.ics'."
15151 (interactive)
15152 (apply 'org-export-icalendar nil (org-agenda-files t)))
15154 ;;;###autoload
15155 (defun org-export-icalendar-combine-agenda-files ()
15156 "Export all files in `org-agenda-files' to a single combined iCalendar file.
15157 The file is stored under the name `org-combined-agenda-icalendar-file'."
15158 (interactive)
15159 (apply 'org-export-icalendar t (org-agenda-files t)))
15161 (defun org-export-icalendar (combine &rest files)
15162 "Create iCalendar files for all elements of FILES.
15163 If COMBINE is non-nil, combine all calendar entries into a single large
15164 file and store it under the name `org-combined-agenda-icalendar-file'."
15165 (save-excursion
15166 (let* ((dir (org-export-directory
15167 :ical (list :publishing-directory
15168 org-export-publishing-directory)))
15169 file ical-file ical-buffer category started org-agenda-new-buffers)
15171 (when combine
15172 (setq ical-file
15173 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
15174 org-combined-agenda-icalendar-file
15175 (expand-file-name org-combined-agenda-icalendar-file dir))
15176 ical-buffer (org-get-agenda-file-buffer ical-file))
15177 (set-buffer ical-buffer) (erase-buffer))
15178 (while (setq file (pop files))
15179 (catch 'nextfile
15180 (org-check-agenda-file file)
15181 (set-buffer (org-get-agenda-file-buffer file))
15182 (unless combine
15183 (setq ical-file (concat (file-name-as-directory dir)
15184 (file-name-sans-extension
15185 (file-name-nondirectory buffer-file-name))
15186 ".ics"))
15187 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
15188 (with-current-buffer ical-buffer (erase-buffer)))
15189 (setq category (or org-category
15190 (file-name-sans-extension
15191 (file-name-nondirectory buffer-file-name))))
15192 (if (symbolp category) (setq category (symbol-name category)))
15193 (let ((standard-output ical-buffer))
15194 (if combine
15195 (and (not started) (setq started t)
15196 (org-start-icalendar-file org-icalendar-combined-name))
15197 (org-start-icalendar-file category))
15198 (org-print-icalendar-entries combine category)
15199 (when (or (and combine (not files)) (not combine))
15200 (org-finish-icalendar-file)
15201 (set-buffer ical-buffer)
15202 (save-buffer)
15203 (run-hooks 'org-after-save-iCalendar-file-hook)))))
15204 (org-release-buffers org-agenda-new-buffers))))
15206 (defvar org-after-save-iCalendar-file-hook nil
15207 "Hook run after an iCalendar file has been saved.
15208 The iCalendar buffer is still current when this hook is run.
15209 A good way to use this is to tell a desktop calenndar application to re-read
15210 the iCalendar file.")
15212 (defun org-print-icalendar-entries (&optional combine category)
15213 "Print iCalendar entries for the current Org-mode file to `standard-output'.
15214 When COMBINE is non nil, add the category to each line."
15215 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
15216 (dts (org-ical-ts-to-string
15217 (format-time-string (cdr org-time-stamp-formats) (current-time))
15218 "DTSTART"))
15219 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
15220 (save-excursion
15221 (goto-char (point-min))
15222 (while (re-search-forward org-ts-regexp nil t)
15223 (setq pos (match-beginning 0)
15224 ts (match-string 0)
15225 inc t
15226 hd (org-get-heading))
15227 (if (looking-at re2)
15228 (progn
15229 (goto-char (match-end 0))
15230 (setq ts2 (match-string 1) inc nil))
15231 (setq ts2 ts
15232 tmp (buffer-substring (max (point-min)
15233 (- pos org-ds-keyword-length))
15234 pos)
15235 deadlinep (string-match org-deadline-regexp tmp)
15236 scheduledp (string-match org-scheduled-regexp tmp)
15237 ;; donep (org-entry-is-done-p)
15239 (if (or (string-match org-tr-regexp hd)
15240 (string-match org-ts-regexp hd))
15241 (setq hd (replace-match "" t t hd)))
15242 (if combine
15243 (setq hd (concat hd " (category " category ")")))
15244 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
15245 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
15246 (princ (format "BEGIN:VEVENT
15249 SUMMARY:%s
15250 END:VEVENT\n"
15251 (org-ical-ts-to-string ts "DTSTART")
15252 (org-ical-ts-to-string ts2 "DTEND" inc)
15253 hd)))
15254 (when org-icalendar-include-todo
15255 (goto-char (point-min))
15256 (while (re-search-forward org-todo-line-regexp nil t)
15257 (setq state (match-string 1))
15258 (unless (equal state org-done-string)
15259 (setq hd (match-string 3))
15260 (if (string-match org-priority-regexp hd)
15261 (setq pri (string-to-char (match-string 2 hd))
15262 hd (concat (substring hd 0 (match-beginning 1))
15263 (substring hd (- (match-end 1)))))
15264 (setq pri org-default-priority))
15265 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
15266 (- org-lowest-priority ?A))))))
15268 (princ (format "BEGIN:VTODO
15270 SUMMARY:%s
15271 SEQUENCE:1
15272 PRIORITY:%d
15273 END:VTODO\n"
15274 dts hd pri))))))))
15276 (defun org-start-icalendar-file (name)
15277 "Start an iCalendar file by inserting the header."
15278 (let ((user user-full-name)
15279 (name (or name "unknown"))
15280 (timezone (cadr (current-time-zone))))
15281 (princ
15282 (format "BEGIN:VCALENDAR
15283 VERSION:2.0
15284 X-WR-CALNAME:%s
15285 PRODID:-//%s//Emacs with Org-mode//EN
15286 X-WR-TIMEZONE:%s
15287 CALSCALE:GREGORIAN\n" name user timezone))))
15289 (defun org-finish-icalendar-file ()
15290 "Finish an iCalendar file by inserting the END statement."
15291 (princ "END:VCALENDAR\n"))
15293 (defun org-ical-ts-to-string (s keyword &optional inc)
15294 "Take a time string S and convert it to iCalendar format.
15295 KEYWORD is added in front, to make a complete line like DTSTART....
15296 When INC is non-nil, increase the hour by two (if time string contains
15297 a time), or the day by one (if it does not contain a time)."
15298 (let ((t1 (org-parse-time-string s 'nodefault))
15299 t2 fmt have-time time)
15300 (if (and (car t1) (nth 1 t1) (nth 2 t1))
15301 (setq t2 t1 have-time t)
15302 (setq t2 (org-parse-time-string s)))
15303 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
15304 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
15305 (when inc
15306 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
15307 (setq time (encode-time s mi h d m y)))
15308 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
15309 (concat keyword (format-time-string fmt time))))
15311 ;;; LaTeX stuff
15313 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15314 "Keymap for the minor `org-cdlatex-mode'.")
15316 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15317 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15318 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15319 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15320 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15322 (defvar org-cdlatex-texmathp-advice-is-done nil
15323 "Flag remembering if we have applied the advice to texmathp already.")
15325 (define-minor-mode org-cdlatex-mode
15326 "Toggle the minor `org-cdlatex-mode'.
15327 This mode supports entering LaTeX environment and math in LaTeX fragments
15328 in Org-mode.
15329 \\{org-cdlatex-mode-map}"
15330 nil " OCDL" nil
15331 (when org-cdlatex-mode (require 'cdlatex))
15332 (unless org-cdlatex-texmathp-advice-is-done
15333 (setq org-cdlatex-texmathp-advice-is-done t)
15334 (defadvice texmathp (around org-math-always-on activate)
15335 "Always return t in org-mode buffers.
15336 This is because we want to insert math symbols without dollars even outside
15337 the LaTeX math segments. If Orgmode thinks that point is actually inside
15338 en embedded LaTeX fragement, let texmathp do its job.
15339 \\[org-cdlatex-mode-map]"
15340 (interactive)
15341 (let (p)
15342 (cond
15343 ((not (org-mode-p)) ad-do-it)
15344 ((eq this-command 'cdlatex-math-symbol)
15345 (setq ad-return-value t
15346 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15348 (let ((p (org-inside-LaTeX-fragment-p)))
15349 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15350 (setq ad-return-value t
15351 texmathp-why '("Org-mode embedded math" . 0))
15352 (if p ad-do-it)))))))))
15354 (defun turn-on-org-cdlatex ()
15355 "Unconditionally turn on `org-cdlatex-mode'."
15356 (org-cdlatex-mode 1))
15358 (defun org-inside-LaTeX-fragment-p ()
15359 "Test if point is inside a LaTeX fragment.
15360 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15361 sequence appearing also before point.
15362 Even though the matchers for math are configurable, this function assumes
15363 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15364 delimiters are skipped when they have been removed by customization.
15365 The return value is nil, or a cons cell with the delimiter and
15366 and the position of this delimiter.
15368 This function does a reasonably good job, but can locally be fooled by
15369 for example currency specifications. For example it will assume being in
15370 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15371 fragments that are properly closed, but during editing, we have to live
15372 with the uncertainty caused by missing closing delimiters. This function
15373 looks only before point, not after."
15374 (catch 'exit
15375 (let ((pos (point))
15376 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15377 (lim (progn
15378 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15379 (point)))
15380 dd-on str (start 0) m re)
15381 (goto-char pos)
15382 (when dodollar
15383 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15384 re (nth 1 (assoc "$" org-latex-regexps)))
15385 (while (string-match re str start)
15386 (cond
15387 ((= (match-end 0) (length str))
15388 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15389 ((= (match-end 0) (- (length str) 5))
15390 (throw 'exit nil))
15391 (t (setq start (match-end 0))))))
15392 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15393 (goto-char pos)
15394 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15395 (and (match-beginning 2) (throw 'exit nil))
15396 ;; count $$
15397 (while (re-search-backward "\\$\\$" lim t)
15398 (setq dd-on (not dd-on)))
15399 (goto-char pos)
15400 (if dd-on (cons "$$" m))))))
15403 (defun org-try-cdlatex-tab ()
15404 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15405 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15406 - inside a LaTeX fragment, or
15407 - after the first word in a line, where an abbreviation expansion could
15408 insert a LaTeX environment."
15409 ;; FIXME: This may still need refinement.
15410 (when org-cdlatex-mode
15411 (cond
15412 ((save-excursion
15413 (skip-chars-backward "a-zA-Z0-9*")
15414 (skip-chars-backward " \t")
15415 (bolp))
15416 (cdlatex-tab) t)
15417 ((org-inside-LaTeX-fragment-p)
15418 (cdlatex-tab) t)
15419 (t nil))))
15421 (defun org-cdlatex-underscore-caret (&optional arg)
15422 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15423 Revert to the normal definition outside of these fragments."
15424 (interactive "P")
15425 (if (org-inside-LaTeX-fragment-p)
15426 (call-interactively 'cdlatex-sub-superscript)
15427 (let (org-cdlatex-mode)
15428 (call-interactively (key-binding (vector last-input-event))))))
15430 (defun org-cdlatex-math-modify (&optional arg)
15431 "Execute `cdlatex-math-modify' in LaTeX fragments.
15432 Revert to the normal definition outside of these fragments."
15433 (interactive "P")
15434 (if (org-inside-LaTeX-fragment-p)
15435 (call-interactively 'cdlatex-math-modify)
15436 (let (org-cdlatex-mode)
15437 (call-interactively (key-binding (vector last-input-event))))))
15439 (defvar org-latex-fragment-image-overlays nil
15440 "List of overlays carrying the images of latex fragments.")
15441 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15443 (defun org-remove-latex-fragment-image-overlays ()
15444 "Remove all overlays with LaTeX fragment images in current buffer."
15445 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15446 (setq org-latex-fragment-image-overlays nil))
15448 (defun org-preview-latex-fragment (&optional subtree)
15449 "Preview the LaTeX fragment at point, or all locally or globally.
15450 If the cursor is in a LaTeX fragment, create the image and overlay
15451 it over the source code. If there is no fragment at point, display
15452 all fragments in the current text, from one headline to the next. With
15453 prefix SUBTREE, display all fragments in the current subtree. With a
15454 double prefix `C-u C-u', or when the cursor is before the first headline,
15455 display all fragments in the buffer.
15456 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15457 (interactive "P")
15458 (org-remove-latex-fragment-image-overlays)
15459 (save-excursion
15460 (save-restriction
15461 (let (beg end at msg)
15462 (cond
15463 ((or (equal subtree '(16))
15464 (not (save-excursion
15465 (re-search-backward (concat "^" outline-regexp) nil t))))
15466 (setq beg (point-min) end (point-max)
15467 msg "Creating images for buffer...%s"))
15468 ((equal subtree '(4))
15469 (org-back-to-heading)
15470 (setq beg (point) end (org-end-of-subtree)
15471 msg "Creating images for subtree...%s"))
15473 (if (setq at (org-inside-LaTeX-fragment-p))
15474 (goto-char (max (point-min) (- (cdr at) 2)))
15475 (org-back-to-heading))
15476 (setq beg (point) end (progn (outline-next-heading) (point))
15477 msg (if at "Creating image...%s"
15478 "Creating images for entry...%s"))))
15479 (message msg "")
15480 (narrow-to-region beg end)
15481 (org-format-latex
15482 (concat "ltxpng/" (file-name-sans-extension
15483 (file-name-nondirectory
15484 buffer-file-name)))
15485 default-directory 'overlays msg at)
15486 (message msg "done. Use `C-c C-c' to remove images.")))))
15488 (defvar org-latex-regexps
15489 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15490 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15491 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15492 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15493 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15494 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15495 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15496 "Regular expressions for matching embedded LaTeX.")
15498 (defun org-format-latex (prefix &optional dir overlays msg at)
15499 "Replace LaTeX fragments with links to an image, and produce images."
15500 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15501 (let* ((prefixnodir (file-name-nondirectory prefix))
15502 (absprefix (expand-file-name prefix dir))
15503 (todir (file-name-directory absprefix))
15504 (opt org-format-latex-options)
15505 (matchers (plist-get opt :matchers))
15506 (re-list org-latex-regexps)
15507 (cnt 0) txt link beg end re e oldfiles
15508 m n block linkfile movefile ov)
15509 ;; Make sure the directory exists
15510 (or (file-directory-p todir) (make-directory todir))
15511 ;; Check if there are old images files with this prefix, and remove them
15512 (setq oldfiles (directory-files
15513 todir 'full
15514 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15515 (while oldfiles (delete-file (pop oldfiles)))
15516 ;; Check the different regular expressions
15517 (while (setq e (pop re-list))
15518 (setq m (car e) re (nth 1 e) n (nth 2 e)
15519 block (if (nth 3 e) "\n\n" ""))
15520 (when (member m matchers)
15521 (goto-char (point-min))
15522 (while (re-search-forward re nil t)
15523 (when (or (not at) (equal (cdr at) (match-beginning n)))
15524 (setq txt (match-string n)
15525 beg (match-beginning n) end (match-end n)
15526 cnt (1+ cnt)
15527 linkfile (format "%s_%04d.png" prefix cnt)
15528 movefile (format "%s_%04d.png" absprefix cnt)
15529 link (concat block "[[file:" linkfile "]]" block))
15530 (if msg (message msg cnt))
15531 (goto-char beg)
15532 (org-create-formula-image
15533 txt movefile opt)
15534 (if overlays
15535 (progn
15536 (setq ov (org-make-overlay beg end))
15537 (if (featurep 'xemacs)
15538 (progn
15539 (org-overlay-put ov 'invisible t)
15540 (org-overlay-put
15541 ov 'end-glyph
15542 (make-glyph (vector 'png :file movefile))))
15543 (org-overlay-put
15544 ov 'display
15545 (list 'image :type 'png :file movefile :ascent 'center)))
15546 (push ov org-latex-fragment-image-overlays)
15547 (goto-char end))
15548 (delete-region beg end)
15549 (insert link))))))))
15551 ;; This function borrows from Ganesh Swami's latex2png.el
15552 (defun org-create-formula-image (string tofile options)
15553 (let* ((tmpdir (if (featurep 'xemacs)
15554 (temp-directory)
15555 temporary-file-directory))
15556 (texfilebase (make-temp-name
15557 (expand-file-name "orgtex" tmpdir)))
15559 ;(texfilebase (make-temp-file "orgtex"))
15560 ; (dummy (delete-file texfilebase))
15561 (texfile (concat texfilebase ".tex"))
15562 (dvifile (concat texfilebase ".dvi"))
15563 (pngfile (concat texfilebase ".png"))
15564 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15565 (fg (or (plist-get options :foreground) "Black"))
15566 (bg (or (plist-get options :background) "Transparent")))
15567 (with-temp-file texfile
15568 (insert "\\documentclass{article}
15569 \\usepackage{fullpage}
15570 \\usepackage{amssymb}
15571 \\usepackage[usenames]{color}
15572 \\usepackage{amsmath}
15573 \\usepackage{latexsym}
15574 \\usepackage[mathscr]{eucal}
15575 \\pagestyle{empty}
15576 \\begin{document}\n" string "\n\\end{document}\n"))
15577 (let ((dir default-directory))
15578 (condition-case nil
15579 (progn
15580 (cd tmpdir)
15581 (call-process "latex" nil nil nil texfile))
15582 (error nil))
15583 (cd dir))
15584 (if (not (file-exists-p dvifile))
15585 (progn (message "Failed to create dvi file from %s" texfile) nil)
15586 (call-process "dvipng" nil nil nil
15587 "-E" "-fg" fg "-bg" bg
15588 "-x" scale "-y" scale "-T" "tight"
15589 "-o" pngfile
15590 dvifile)
15591 (if (not (file-exists-p pngfile))
15592 (progn (message "Failed to create png file from %s" texfile) nil)
15593 ;; Use the requested file name and clean up
15594 (copy-file pngfile tofile 'replace)
15595 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15596 (delete-file (concat texfilebase e)))
15597 pngfile))))
15599 ;;; Key bindings
15601 ;; - Bindings in Org-mode map are currently
15602 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15603 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15604 ;; e (?) useful from outline-mode
15605 ;; i k @ expendable from outline-mode
15606 ;; 0123456789 % & ()_{} " ` free
15608 ;; Make `C-c C-x' a prefix key
15609 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15611 ;; TAB key with modifiers
15612 (define-key org-mode-map "\C-i" 'org-cycle)
15613 (define-key org-mode-map [(tab)] 'org-cycle)
15614 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
15615 (define-key org-mode-map [(meta tab)] 'org-complete)
15616 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15617 ;; The following line is necessary under Suse GNU/Linux
15618 (unless (featurep 'xemacs)
15619 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15620 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15622 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15623 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15624 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15625 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15626 (define-key org-mode-map [(meta return)] 'org-meta-return)
15627 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15628 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15630 ;; Cursor keys with modifiers
15631 (define-key org-mode-map [(meta left)] 'org-metaleft)
15632 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15633 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15634 (define-key org-mode-map [(meta right)] 'org-metaright)
15635 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15636 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15637 (define-key org-mode-map [(meta up)] 'org-metaup)
15638 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15639 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15640 (define-key org-mode-map [(meta down)] 'org-metadown)
15641 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15642 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15644 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15645 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15646 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15647 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15648 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15649 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15650 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15651 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15652 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15653 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15654 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15655 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15656 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15657 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15658 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15659 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15661 ;; All the other keys
15663 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15664 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15665 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15666 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15667 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15668 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15669 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15670 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15671 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15672 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15673 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15674 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15675 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15676 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15677 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15678 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15679 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15680 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15681 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15682 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15683 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15684 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15685 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15686 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15687 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15688 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15689 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15690 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15691 (define-key org-mode-map "\C-c]" 'org-remove-file)
15692 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15693 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15694 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15695 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
15696 (define-key org-mode-map "\C-m" 'org-return)
15697 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15698 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15699 (define-key org-mode-map "\C-c+" 'org-table-sum)
15700 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15701 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15702 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15703 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15704 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15705 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15706 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15707 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15708 (define-key org-mode-map "\C-c\C-e" 'org-export)
15709 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15711 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15712 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15713 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15714 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15716 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15717 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15718 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15719 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15720 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15721 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15722 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15723 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15725 (when (featurep 'xemacs)
15726 (define-key org-mode-map 'button3 'popup-mode-menu))
15728 (defsubst org-table-p () (org-at-table-p))
15730 (defun org-self-insert-command (N)
15731 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15732 If the cursor is in a table looking at whitespace, the whitespace is
15733 overwritten, and the table is not marked as requiring realignment."
15734 (interactive "p")
15735 (if (and (org-table-p)
15736 (progn
15737 ;; check if we blank the field, and if that triggers align
15738 (and org-table-auto-blank-field
15739 (member last-command
15740 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15741 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15742 ;; got extra space, this field does not determine column width
15743 (let (org-table-may-need-update) (org-table-blank-field))
15744 ;; no extra space, this field may determine column width
15745 (org-table-blank-field)))
15747 (eq N 1)
15748 (looking-at "[^|\n]* |"))
15749 (let (org-table-may-need-update)
15750 (goto-char (1- (match-end 0)))
15751 (delete-backward-char 1)
15752 (goto-char (match-beginning 0))
15753 (self-insert-command N))
15754 (setq org-table-may-need-update t)
15755 (self-insert-command N)))
15757 (defun org-delete-backward-char (N)
15758 "Like `delete-backward-char', insert whitespace at field end in tables.
15759 When deleting backwards, in tables this function will insert whitespace in
15760 front of the next \"|\" separator, to keep the table aligned. The table will
15761 still be marked for re-alignment if the field did fill the entire column,
15762 because, in this case the deletion might narrow the column."
15763 (interactive "p")
15764 (if (and (org-table-p)
15765 (eq N 1)
15766 (string-match "|" (buffer-substring (point-at-bol) (point)))
15767 (looking-at ".*?|"))
15768 (let ((pos (point))
15769 (noalign (looking-at "[^|\n\r]* |"))
15770 (c org-table-may-need-update))
15771 (backward-delete-char N)
15772 (skip-chars-forward "^|")
15773 (insert " ")
15774 (goto-char (1- pos))
15775 ;; noalign: if there were two spaces at the end, this field
15776 ;; does not determine the width of the column.
15777 (if noalign (setq org-table-may-need-update c)))
15778 (backward-delete-char N)))
15780 (defun org-delete-char (N)
15781 "Like `delete-char', but insert whitespace at field end in tables.
15782 When deleting characters, in tables this function will insert whitespace in
15783 front of the next \"|\" separator, to keep the table aligned. The table will
15784 still be marked for re-alignment if the field did fill the entire column,
15785 because, in this case the deletion might narrow the column."
15786 (interactive "p")
15787 (if (and (org-table-p)
15788 (not (bolp))
15789 (not (= (char-after) ?|))
15790 (eq N 1))
15791 (if (looking-at ".*?|")
15792 (let ((pos (point))
15793 (noalign (looking-at "[^|\n\r]* |"))
15794 (c org-table-may-need-update))
15795 (replace-match (concat
15796 (substring (match-string 0) 1 -1)
15797 " |"))
15798 (goto-char pos)
15799 ;; noalign: if there were two spaces at the end, this field
15800 ;; does not determine the width of the column.
15801 (if noalign (setq org-table-may-need-update c)))
15802 (delete-char N))
15803 (delete-char N)))
15805 ;; How to do this: Measure non-white length of current string
15806 ;; If equal to column width, we should realign.
15808 (defun org-remap (map &rest commands)
15809 "In MAP, remap the functions given in COMMANDS.
15810 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15811 (let (new old)
15812 (while commands
15813 (setq old (pop commands) new (pop commands))
15814 (if (fboundp 'command-remapping)
15815 (define-key map (vector 'remap old) new)
15816 (substitute-key-definition old new map global-map)))))
15818 (when (eq org-enable-table-editor 'optimized)
15819 ;; If the user wants maximum table support, we need to hijack
15820 ;; some standard editing functions
15821 (org-remap org-mode-map
15822 'self-insert-command 'org-self-insert-command
15823 'delete-char 'org-delete-char
15824 'delete-backward-char 'org-delete-backward-char)
15825 (define-key org-mode-map "|" 'org-force-self-insert))
15827 (defun org-shiftcursor-error ()
15828 "Throw an error because Shift-Cursor command was applied in wrong context."
15829 (error "This command is active in special context like tables, headlines or timestamps"))
15831 (defun org-shifttab (&optional arg)
15832 "Global visibility cycling or move to previous table field.
15833 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15834 on context.
15835 See the individual commands for more information."
15836 (interactive "P")
15837 (cond
15838 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15839 (t (call-interactively 'org-global-cycle))))
15841 (defun org-shiftmetaleft ()
15842 "Promote subtree or delete table column.
15843 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15844 See the individual commands for more information."
15845 (interactive)
15846 (cond
15847 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15848 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15849 ((org-at-item-p) (call-interactively 'org-outdent-item))
15850 (t (org-shiftcursor-error))))
15852 (defun org-shiftmetaright ()
15853 "Demote subtree or insert table column.
15854 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15855 See the individual commands for more information."
15856 (interactive)
15857 (cond
15858 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15859 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15860 ((org-at-item-p) (call-interactively 'org-indent-item))
15861 (t (org-shiftcursor-error))))
15863 (defun org-shiftmetaup (&optional arg)
15864 "Move subtree up or kill table row.
15865 Calls `org-move-subtree-up' or `org-table-kill-row' or
15866 `org-move-item-up' depending on context. See the individual commands
15867 for more information."
15868 (interactive "P")
15869 (cond
15870 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15871 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15872 ((org-at-item-p) (call-interactively 'org-move-item-up))
15873 (t (org-shiftcursor-error))))
15874 (defun org-shiftmetadown (&optional arg)
15875 "Move subtree down or insert table row.
15876 Calls `org-move-subtree-down' or `org-table-insert-row' or
15877 `org-move-item-down', depending on context. See the individual
15878 commands for more information."
15879 (interactive "P")
15880 (cond
15881 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15882 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15883 ((org-at-item-p) (call-interactively 'org-move-item-down))
15884 (t (org-shiftcursor-error))))
15886 (defun org-metaleft (&optional arg)
15887 "Promote heading or move table column to left.
15888 Calls `org-do-promote' or `org-table-move-column', depending on context.
15889 With no specific context, calls the Emacs default `backward-word'.
15890 See the individual commands for more information."
15891 (interactive "P")
15892 (cond
15893 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15894 ((or (org-on-heading-p) (org-region-active-p))
15895 (call-interactively 'org-do-promote))
15896 (t (call-interactively 'backward-word))))
15898 (defun org-metaright (&optional arg)
15899 "Demote subtree or move table column to right.
15900 Calls `org-do-demote' or `org-table-move-column', depending on context.
15901 With no specific context, calls the Emacs default `forward-word'.
15902 See the individual commands for more information."
15903 (interactive "P")
15904 (cond
15905 ((org-at-table-p) (call-interactively 'org-table-move-column))
15906 ((or (org-on-heading-p) (org-region-active-p))
15907 (call-interactively 'org-do-demote))
15908 (t (call-interactively 'forward-word))))
15910 (defun org-metaup (&optional arg)
15911 "Move subtree up or move table row up.
15912 Calls `org-move-subtree-up' or `org-table-move-row' or
15913 `org-move-item-up', depending on context. See the individual commands
15914 for more information."
15915 (interactive "P")
15916 (cond
15917 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15918 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15919 ((org-at-item-p) (call-interactively 'org-move-item-up))
15920 (t (org-shiftcursor-error))))
15922 (defun org-metadown (&optional arg)
15923 "Move subtree down or move table row down.
15924 Calls `org-move-subtree-down' or `org-table-move-row' or
15925 `org-move-item-down', depending on context. See the individual
15926 commands for more information."
15927 (interactive "P")
15928 (cond
15929 ((org-at-table-p) (call-interactively 'org-table-move-row))
15930 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15931 ((org-at-item-p) (call-interactively 'org-move-item-down))
15932 (t (org-shiftcursor-error))))
15934 (defun org-shiftup (&optional arg)
15935 "Increase item in timestamp or increase priority of current headline.
15936 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15937 See the individual commands for more information."
15938 (interactive "P")
15939 (cond
15940 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15941 ((org-on-heading-p) (call-interactively 'org-priority-up))
15942 ((org-at-item-p) (call-interactively 'org-previous-item))
15943 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15945 (defun org-shiftdown (&optional arg)
15946 "Decrease item in timestamp or decrease priority of current headline.
15947 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15948 See the individual commands for more information."
15949 (interactive "P")
15950 (cond
15951 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15952 ((org-on-heading-p) (call-interactively 'org-priority-down))
15953 (t (call-interactively 'org-next-item))))
15955 (defun org-shiftright ()
15956 "Next TODO keyword or timestamp one day later, depending on context."
15957 (interactive)
15958 (cond
15959 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15960 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15961 (t (org-shiftcursor-error))))
15963 (defun org-shiftleft ()
15964 "Previous TODO keyword or timestamp one day earlier, depending on context."
15965 (interactive)
15966 (cond
15967 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15968 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15969 (t (org-shiftcursor-error))))
15971 (defun org-copy-special ()
15972 "Copy region in table or copy current subtree.
15973 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15974 See the individual commands for more information."
15975 (interactive)
15976 (call-interactively
15977 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15979 (defun org-cut-special ()
15980 "Cut region in table or cut current subtree.
15981 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15982 See the individual commands for more information."
15983 (interactive)
15984 (call-interactively
15985 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15987 (defun org-paste-special (arg)
15988 "Paste rectangular region into table, or past subtree relative to level.
15989 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15990 See the individual commands for more information."
15991 (interactive "P")
15992 (if (org-at-table-p)
15993 (org-table-paste-rectangle)
15994 (org-paste-subtree arg)))
15996 (defun org-ctrl-c-ctrl-c (&optional arg)
15997 "Set tags in headline, or update according to changed information at point.
15999 This command does many different things, depending on context:
16001 - If the cursor is in a headline, prompt for tags and insert them
16002 into the current line, aligned to `org-tags-column'. When called
16003 with prefix arg, realign all tags in the current buffer.
16005 - If the cursor is in one of the special #+KEYWORD lines, this
16006 triggers scanning the buffer for these lines and updating the
16007 information.
16009 - If the cursor is inside a table, realign the table. This command
16010 works even if the automatic table editor has been turned off.
16012 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16013 the entire table.
16015 - If the cursor is inside a table created by the table.el package,
16016 activate that table.
16018 - If the current buffer is a remember buffer, close note and file it.
16019 with a prefix argument, file it without further interaction to the default
16020 location.
16022 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16023 links in this buffer.
16025 - If the cursor is on a numbered item in a plain list, renumber the
16026 ordered list."
16027 (interactive "P")
16028 (let ((org-enable-table-editor t))
16029 (cond
16030 ((or org-clock-overlays org-occur-highlights
16031 org-latex-fragment-image-overlays)
16032 (org-remove-clock-overlays)
16033 (org-remove-occur-highlights)
16034 (org-remove-latex-fragment-image-overlays)
16035 (message "Temporary highlights/overlays removed from current buffer"))
16036 ((and (local-variable-p 'org-finish-function (current-buffer))
16037 (fboundp org-finish-function))
16038 (funcall org-finish-function))
16039 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16040 ((org-on-heading-p) (call-interactively 'org-set-tags))
16041 ((org-at-table.el-p)
16042 (require 'table)
16043 (beginning-of-line 1)
16044 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
16045 (call-interactively 'table-recognize-table))
16046 ((org-at-table-p)
16047 (org-table-maybe-eval-formula)
16048 (if arg
16049 (call-interactively 'org-table-recalculate)
16050 (org-table-maybe-recalculate-line))
16051 (call-interactively 'org-table-align))
16052 ((org-at-item-checkbox-p)
16053 (call-interactively 'org-toggle-checkbox))
16054 ((org-at-item-p)
16055 (call-interactively 'org-renumber-ordered-list))
16056 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
16057 (cond
16058 ((equal (match-string 1) "TBLFM")
16059 ;; Recalculate the table before this line
16060 (save-excursion
16061 (beginning-of-line 1)
16062 (skip-chars-backward " \r\n\t")
16063 (if (org-at-table-p)
16064 (org-call-with-arg 'org-table-recalculate t))))
16066 (call-interactively 'org-mode-restart))))
16067 (t (error "C-c C-c can do nothing useful at this location.")))))
16069 (defun org-mode-restart ()
16070 "Restart Org-mode, to scan again for special lines.
16071 Also updates the keyword regular expressions."
16072 (interactive)
16073 (let ((org-inhibit-startup t)) (org-mode))
16074 (message "Org-mode restarted to refresh keyword and special line setup"))
16076 (defun org-return ()
16077 "Goto next table row or insert a newline.
16078 Calls `org-table-next-row' or `newline', depending on context.
16079 See the individual commands for more information."
16080 (interactive)
16081 (cond
16082 ((org-at-table-p)
16083 (org-table-justify-field-maybe)
16084 (call-interactively 'org-table-next-row))
16085 (t (newline))))
16087 (defun org-meta-return (&optional arg)
16088 "Insert a new heading or wrap a region in a table.
16089 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16090 See the individual commands for more information."
16091 (interactive "P")
16092 (cond
16093 ((org-at-table-p)
16094 (call-interactively 'org-table-wrap-region))
16095 (t (call-interactively 'org-insert-heading))))
16097 ;;; Menu entries
16099 ;; Define the Org-mode menus
16100 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16101 '("Tbl"
16102 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
16103 ["Next Field" org-cycle (org-at-table-p)]
16104 ["Previous Field" org-shifttab (org-at-table-p)]
16105 ["Next Row" org-return (org-at-table-p)]
16106 "--"
16107 ["Blank Field" org-table-blank-field (org-at-table-p)]
16108 ["Edit Field" org-table-edit-field (org-at-table-p)]
16109 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16110 "--"
16111 ("Column"
16112 ["Move Column Left" org-metaleft (org-at-table-p)]
16113 ["Move Column Right" org-metaright (org-at-table-p)]
16114 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16115 ["Insert Column" org-shiftmetaright (org-at-table-p)]
16116 "--"
16117 ["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])
16118 ("Row"
16119 ["Move Row Up" org-metaup (org-at-table-p)]
16120 ["Move Row Down" org-metadown (org-at-table-p)]
16121 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16122 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16123 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16124 "--"
16125 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
16126 ("Rectangle"
16127 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16128 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16129 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16130 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16131 "--"
16132 ("Calculate"
16133 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16134 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16135 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
16136 "--"
16137 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16138 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16139 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16140 "--"
16141 ["Sum Column/Rectangle" org-table-sum
16142 (or (org-at-table-p) (org-region-active-p))]
16143 ["Which Column?" org-table-current-column (org-at-table-p)])
16144 ["Debug Formulas"
16145 (setq org-table-formula-debug (not org-table-formula-debug))
16146 :style toggle :selected org-table-formula-debug]
16147 "--"
16148 ["Create" org-table-create (and (not (org-at-table-p))
16149 org-enable-table-editor)]
16150 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16151 ["Import from File" org-table-import (not (org-at-table-p))]
16152 ["Export to File" org-table-export (org-at-table-p)]
16153 "--"
16154 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16156 (easy-menu-define org-org-menu org-mode-map "Org menu"
16157 '("Org"
16158 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
16159 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
16160 ["Sparse Tree" org-occur t]
16161 ["Show All" show-all t]
16162 "--"
16163 ["New Heading" org-insert-heading t]
16164 ("Navigate Headings"
16165 ["Up" outline-up-heading t]
16166 ["Next" outline-next-visible-heading t]
16167 ["Previous" outline-previous-visible-heading t]
16168 ["Next Same Level" outline-forward-same-level t]
16169 ["Previous Same Level" outline-backward-same-level t]
16170 "--"
16171 ["Jump" org-goto t])
16172 ("Edit Structure"
16173 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16174 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16175 "--"
16176 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16177 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16178 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16179 "--"
16180 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16181 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16182 ["Demote Heading" org-metaright (not (org-at-table-p))]
16183 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16184 "--"
16185 ["Convert to odd levels" org-convert-to-odd-levels t]
16186 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16187 ("Archive"
16188 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16189 ["Check and Tag Children" (org-toggle-archive-tag (4))
16190 :active t :keys "C-u C-c C-x C-a"]
16191 ["Sparse trees open ARCHIVE trees"
16192 (setq org-sparse-tree-open-archived-trees
16193 (not org-sparse-tree-open-archived-trees))
16194 :style toggle :selected org-sparse-tree-open-archived-trees]
16195 ["Cycling opens ARCHIVE trees"
16196 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
16197 :style toggle :selected org-cycle-open-archived-trees]
16198 ["Agenda includes ARCHIVE trees"
16199 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
16200 :style toggle :selected (not org-agenda-skip-archived-trees)]
16201 "--"
16202 ["Move Subtree to Archive" org-archive-subtree t]
16203 ["Check and Move Children" (org-archive-subtree '(4))
16204 :active t :keys "C-u C-c $"])
16205 "--"
16206 ("TODO Lists"
16207 ["TODO/DONE/-" org-todo t]
16208 ("Select keyword"
16209 ["Next keyword" org-shiftright (org-on-heading-p)]
16210 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16211 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
16212 ["Show TODO Tree" org-show-todo-tree t]
16213 ["Global TODO list" org-todo-list t]
16214 "--"
16215 ["Set Priority" org-priority t]
16216 ["Priority Up" org-shiftup t]
16217 ["Priority Down" org-shiftdown t]
16218 "--"
16219 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
16220 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
16221 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
16222 ; (or (org-on-heading-p) (org-at-item-p))]
16223 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
16224 ; (or (org-on-heading-p) (org-at-item-p))]
16225 ; ["Update Statistics" org-update-checkbox-count t]
16227 ("Dates and Scheduling"
16228 ["Timestamp" org-time-stamp t]
16229 ["Timestamp (inactive)" org-time-stamp-inactive t]
16230 ("Change Date"
16231 ["1 Day Later" org-timestamp-up-day t]
16232 ["1 Day Earlier" org-timestamp-down-day t]
16233 ["1 ... Later" org-shiftup t]
16234 ["1 ... Earlier" org-shiftdown t])
16235 ["Compute Time Range" org-evaluate-time-range t]
16236 ["Schedule Item" org-schedule t]
16237 ["Deadline" org-deadline t]
16238 "--"
16239 ["Goto Calendar" org-goto-calendar t]
16240 ["Date from Calendar" org-date-from-calendar t])
16241 ("Logging work"
16242 ["Clock in" org-clock-in t]
16243 ["Clock out" org-clock-out t]
16244 ["Clock cancel" org-clock-cancel t]
16245 ["Display times" org-clock-display t]
16246 ["Create clock table" org-clock-report t]
16247 "--"
16248 ["Record DONE time"
16249 (progn (setq org-log-done (not org-log-done))
16250 (message "Switching to %s will %s record a timestamp"
16251 org-done-string
16252 (if org-log-done "automatically" "not")))
16253 :style toggle :selected org-log-done])
16254 "--"
16255 ["Agenda Command..." org-agenda t]
16256 ("File List for Agenda")
16257 ("Special views current file"
16258 ["TODO Tree" org-show-todo-tree t]
16259 ["Check Deadlines" org-check-deadlines t]
16260 ["Timeline" org-timeline t]
16261 ["Tags Tree" org-tags-sparse-tree t])
16262 "--"
16263 ("Hyperlinks"
16264 ["Store Link (Global)" org-store-link t]
16265 ["Insert Link" org-insert-link t]
16266 ["Follow Link" org-open-at-point t]
16267 "--"
16268 ["Descriptive Links"
16269 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16270 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
16271 ["Literal Links"
16272 (progn
16273 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16274 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
16275 "--"
16276 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
16277 (save-excursion (goto-char (point-min))
16278 (re-search-forward "<[a-z]+:" nil t))])
16279 "--"
16280 ["Export/Publish..." org-export t]
16281 ("LaTeX"
16282 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16283 :selected org-cdlatex-mode]
16284 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16285 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16286 ["Modify math symbol" org-cdlatex-math-modify
16287 (org-inside-LaTeX-fragment-p)]
16288 ["Export LaTeX fragments as images"
16289 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
16290 :style toggle :selected org-export-with-LaTeX-fragments])
16291 "--"
16292 ("Documentation"
16293 ["Show Version" org-version t]
16294 ["Info Documentation" org-info t])
16295 ("Customize"
16296 ["Browse Org Group" org-customize t]
16297 "--"
16298 ["Expand This Menu" org-create-customize-menu
16299 (fboundp 'customize-menu-create)])
16300 "--"
16301 ["Refresh setup" org-mode-restart t]
16304 (defun org-info (&optional node)
16305 "Read documentation for Org-mode in the info system.
16306 With optional NODE, go directly to that node."
16307 (interactive)
16308 (require 'info)
16309 (Info-goto-node (format "(org)%s" (or node ""))))
16311 (defun org-install-agenda-files-menu ()
16312 (let ((bl (buffer-list)))
16313 (save-excursion
16314 (while bl
16315 (set-buffer (pop bl))
16316 (if (org-mode-p) (setq bl nil)))
16317 (when (org-mode-p)
16318 (easy-menu-change
16319 '("Org") "File List for Agenda"
16320 (append
16321 (list
16322 ["Edit File List" (org-edit-agenda-file-list) t]
16323 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16324 ["Remove Current File from List" org-remove-file t]
16325 ["Cycle through agenda files" org-cycle-agenda-files t]
16326 "--")
16327 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16329 ;;; Documentation
16331 (defun org-customize ()
16332 "Call the customize function with org as argument."
16333 (interactive)
16334 (customize-browse 'org))
16336 (defun org-create-customize-menu ()
16337 "Create a full customization menu for Org-mode, insert it into the menu."
16338 (interactive)
16339 (if (fboundp 'customize-menu-create)
16340 (progn
16341 (easy-menu-change
16342 '("Org") "Customize"
16343 `(["Browse Org group" org-customize t]
16344 "--"
16345 ,(customize-menu-create 'org)
16346 ["Set" Custom-set t]
16347 ["Save" Custom-save t]
16348 ["Reset to Current" Custom-reset-current t]
16349 ["Reset to Saved" Custom-reset-saved t]
16350 ["Reset to Standard Settings" Custom-reset-standard t]))
16351 (message "\"Org\"-menu now contains full customization menu"))
16352 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16354 ;;; Miscellaneous stuff
16356 (defun org-context ()
16357 "Return a list of contexts of the current cursor position.
16358 If several contexts apply, all are returned.
16359 Each context entry is a list with a symbol naming the context, and
16360 two positions indicating start and end of the context. Possible
16361 contexts are:
16363 :headline anywhere in a headline
16364 :headline-stars on the leading stars in a headline
16365 :todo-keyword on a TODO keyword (including DONE) in a headline
16366 :tags on the TAGS in a headline
16367 :priority on the priority cookie in a headline
16368 :item on the first line of a plain list item
16369 :item-bullet on the bullet/number of a plain list item
16370 :checkbox on the checkbox in a plain list item
16371 :table in an org-mode table
16372 :table-special on a special filed in a table
16373 :table-table in a table.el table
16374 :link on a hyperline
16375 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16376 :target on a <<target>>
16377 :radio-target on a <<<radio-target>>>
16378 :latex-fragment on a LaTeX fragment
16379 :latex-preview on a LaTeX fragment with overlayed preview image
16381 This function expects the position to be visible because it uses font-lock
16382 faces as a help to recognize the following contexts: :table-special, :link,
16383 and :keyword."
16384 (let* ((f (get-text-property (point) 'face))
16385 (faces (if (listp f) f (list f)))
16386 (p (point)) clist o)
16387 ;; First the large context
16388 (cond
16389 ((org-on-heading-p)
16390 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16391 (when (progn
16392 (beginning-of-line 1)
16393 (looking-at org-todo-line-tags-regexp))
16394 (push (org-point-in-group p 1 :headline-stars) clist)
16395 (push (org-point-in-group p 2 :todo-keyword) clist)
16396 (push (org-point-in-group p 4 :tags) clist))
16397 (goto-char p)
16398 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16399 (if (looking-at "\\[#[A-Z]\\]")
16400 (push (org-point-in-group p 0 :priority) clist)))
16402 ((org-at-item-p)
16403 (push (org-point-in-group p 2 :item-bullet) clist)
16404 (push (list :item (point-at-bol)
16405 (save-excursion (org-end-of-item) (point)))
16406 clist)
16407 (and (org-at-item-checkbox-p)
16408 (push (org-point-in-group p 0 :checkbox) clist)))
16410 ((org-at-table-p)
16411 (push (list :table (org-table-begin) (org-table-end)) clist)
16412 (if (memq 'org-formula faces)
16413 (push (list :table-special
16414 (previous-single-property-change p 'face)
16415 (next-single-property-change p 'face)) clist)))
16416 ((org-at-table-p 'any)
16417 (push (list :table-table) clist)))
16418 (goto-char p)
16420 ;; Now the small context
16421 (cond
16422 ((org-at-timestamp-p)
16423 (push (org-point-in-group p 0 :timestamp) clist))
16424 ((memq 'org-link faces)
16425 (push (list :link
16426 (previous-single-property-change p 'face)
16427 (next-single-property-change p 'face)) clist))
16428 ((memq 'org-special-keyword faces)
16429 (push (list :keyword
16430 (previous-single-property-change p 'face)
16431 (next-single-property-change p 'face)) clist))
16432 ((org-on-target-p)
16433 (push (org-point-in-group p 0 :target) clist)
16434 (goto-char (1- (match-beginning 0)))
16435 (if (looking-at org-radio-target-regexp)
16436 (push (org-point-in-group p 0 :radio-target) clist))
16437 (goto-char p))
16438 ((setq o (car (delq nil
16439 (mapcar
16440 (lambda (x)
16441 (if (memq x org-latex-fragment-image-overlays) x))
16442 (org-overlays-at (point))))))
16443 (push (list :latex-fragment
16444 (org-overlay-start o) (org-overlay-end o)) clist)
16445 (push (list :latex-preview
16446 (org-overlay-start o) (org-overlay-end o)) clist))
16447 ((org-inside-LaTeX-fragment-p)
16448 ;; FIXME: positions wring.
16449 (push (list :latex-fragment (point) (point)) clist)))
16451 (setq clist (nreverse (delq nil clist)))
16452 clist))
16454 (defun org-point-in-group (point group &optional context)
16455 "Check if POINT is in match-group GROUP.
16456 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16457 match. If the match group does ot exist or point is not inside it,
16458 return nil."
16459 (and (match-beginning group)
16460 (>= point (match-beginning group))
16461 (<= point (match-end group))
16462 (if context
16463 (list context (match-beginning group) (match-end group))
16464 t)))
16466 (defun org-move-line-down (arg)
16467 "Move the current line down. With prefix argument, move it past ARG lines."
16468 (interactive "p")
16469 (let ((col (current-column))
16470 beg end pos)
16471 (beginning-of-line 1) (setq beg (point))
16472 (beginning-of-line 2) (setq end (point))
16473 (beginning-of-line (+ 1 arg))
16474 (setq pos (move-marker (make-marker) (point)))
16475 (insert (delete-and-extract-region beg end))
16476 (goto-char pos)
16477 (move-to-column col)))
16479 (defun org-move-line-up (arg)
16480 "Move the current line up. With prefix argument, move it past ARG lines."
16481 (interactive "p")
16482 (let ((col (current-column))
16483 beg end pos)
16484 (beginning-of-line 1) (setq beg (point))
16485 (beginning-of-line 2) (setq end (point))
16486 (beginning-of-line (- arg))
16487 (setq pos (move-marker (make-marker) (point)))
16488 (insert (delete-and-extract-region beg end))
16489 (goto-char pos)
16490 (move-to-column col)))
16492 ;; Paragraph filling stuff.
16493 ;; We want this to be just right, so use the full arsenal.
16495 (defun org-set-autofill-regexps ()
16496 (interactive)
16497 ;; In the paragraph separator we include headlines, because filling
16498 ;; text in a line directly attached to a headline would otherwise
16499 ;; fill the headline as well.
16500 (org-set-local 'comment-start-skip "^#+[ \t]*")
16501 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16502 ;; The paragraph starter includes hand-formatted lists.
16503 (org-set-local 'paragraph-start
16504 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16505 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16506 ;; But only if the user has not turned off tables or fixed-width regions
16507 (org-set-local
16508 'auto-fill-inhibit-regexp
16509 (concat "\\*\\|#"
16510 "\\|[ \t]*" org-keyword-time-regexp
16511 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16512 (concat
16513 "\\|[ \t]*["
16514 (if org-enable-table-editor "|" "")
16515 (if org-enable-fixed-width-editor ":" "")
16516 "]"))))
16517 ;; We use our own fill-paragraph function, to make sure that tables
16518 ;; and fixed-width regions are not wrapped. That function will pass
16519 ;; through to `fill-paragraph' when appropriate.
16520 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16521 ; Adaptive filling: To get full control, first make sure that
16522 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16523 (org-set-local 'adaptive-fill-regexp "\000")
16524 (org-set-local 'adaptive-fill-function
16525 'org-adaptive-fill-function))
16527 (defun org-fill-paragraph (&optional justify)
16528 "Re-align a table, pass through to fill-paragraph if no table."
16529 (let ((table-p (org-at-table-p))
16530 (table.el-p (org-at-table.el-p)))
16531 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16532 (table.el-p t) ; skip table.el tables
16533 (table-p (org-table-align) t) ; align org-mode tables
16534 (t nil)))) ; call paragraph-fill
16536 ;; For reference, this is the default value of adaptive-fill-regexp
16537 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16539 (defun org-adaptive-fill-function ()
16540 "Return a fill prefix for org-mode files.
16541 In particular, this makes sure hanging paragraphs for hand-formatted lists
16542 work correctly."
16543 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16544 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16546 ;; Functions needed for Emacs/XEmacs region compatibility
16548 (defun org-add-hook (hook function &optional append local)
16549 "Add-hook, compatible with both Emacsen."
16550 (if (and local (featurep 'xemacs))
16551 (add-local-hook hook function append)
16552 (add-hook hook function append local)))
16554 (defun org-region-active-p ()
16555 "Is `transient-mark-mode' on and the region active?
16556 Works on both Emacs and XEmacs."
16557 (if org-ignore-region
16559 (if (featurep 'xemacs)
16560 (and zmacs-regions (region-active-p))
16561 (and transient-mark-mode mark-active))))
16563 (defun org-add-to-invisibility-spec (arg)
16564 "Add elements to `buffer-invisibility-spec'.
16565 See documentation for `buffer-invisibility-spec' for the kind of elements
16566 that can be added."
16567 (cond
16568 ((fboundp 'add-to-invisibility-spec)
16569 (add-to-invisibility-spec arg))
16570 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16571 (setq buffer-invisibility-spec (list arg)))
16573 (setq buffer-invisibility-spec
16574 (cons arg buffer-invisibility-spec)))))
16576 (defun org-remove-from-invisibility-spec (arg)
16577 "Remove elements from `buffer-invisibility-spec'."
16578 (if (fboundp 'remove-from-invisibility-spec)
16579 (remove-from-invisibility-spec arg)
16580 (if (consp buffer-invisibility-spec)
16581 (setq buffer-invisibility-spec
16582 (delete arg buffer-invisibility-spec)))))
16584 (defun org-in-invisibility-spec-p (arg)
16585 "Is ARG a member of `buffer-invisibility-spec'?"
16586 (if (consp buffer-invisibility-spec)
16587 (member arg buffer-invisibility-spec)
16588 nil))
16590 (defun org-image-file-name-regexp ()
16591 "Return regexp matching the file names of images."
16592 (if (fboundp 'image-file-name-regexp)
16593 (image-file-name-regexp)
16594 (let ((image-file-name-extensions
16595 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16596 "xbm" "xpm" "pbm" "pgm" "ppm")))
16597 (concat "\\."
16598 (regexp-opt (nconc (mapcar 'upcase
16599 image-file-name-extensions)
16600 image-file-name-extensions)
16602 "\\'"))))
16604 ;; Functions extending outline functionality
16606 ;; C-a should go to the beginning of a *visible* line, also in the
16607 ;; new outline.el. I guess this should be patched into Emacs?
16608 (defun org-beginning-of-line ()
16609 "Go to the beginning of the current line. If that is invisible, continue
16610 to a visible line beginning. This makes the function of C-a more intuitive."
16611 (interactive)
16612 (beginning-of-line 1)
16613 (if (bobp)
16615 (backward-char 1)
16616 (if (org-invisible-p)
16617 (while (and (not (bobp)) (org-invisible-p))
16618 (backward-char 1)
16619 (beginning-of-line 1))
16620 (forward-char 1))))
16622 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16624 (defun org-invisible-p ()
16625 "Check if point is at a character currently not visible."
16626 ;; Early versions of noutline don't have `outline-invisible-p'.
16627 (if (fboundp 'outline-invisible-p)
16628 (outline-invisible-p)
16629 (get-char-property (point) 'invisible)))
16631 (defun org-invisible-p2 ()
16632 "Check if point is at a character currently not visible."
16633 (save-excursion
16634 (if (and (eolp) (not (bobp))) (backward-char 1))
16635 ;; Early versions of noutline don't have `outline-invisible-p'.
16636 (if (fboundp 'outline-invisible-p)
16637 (outline-invisible-p)
16638 (get-char-property (point) 'invisible))))
16640 (defalias 'org-back-to-heading 'outline-back-to-heading)
16641 (defalias 'org-on-heading-p 'outline-on-heading-p)
16643 (defun org-on-target-p ()
16644 (let ((pos (point)))
16645 (save-excursion
16646 (skip-chars-forward "<")
16647 (and (re-search-backward "<<" nil t)
16648 (or (looking-at org-radio-target-regexp)
16649 (looking-at org-target-regexp))
16650 (<= (match-beginning 0) pos)
16651 (>= (1+ (match-end 0)) pos)))))
16653 (defun org-up-heading-all (arg)
16654 "Move to the heading line of which the present line is a subheading.
16655 This function considers both visible and invisible heading lines.
16656 With argument, move up ARG levels."
16657 (if (fboundp 'outline-up-heading-all)
16658 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16659 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16661 (defun org-show-hidden-entry ()
16662 "Show an entry where even the heading is hidden."
16663 (save-excursion
16664 (org-show-entry)))
16666 (defun org-flag-heading (flag &optional entry)
16667 "Flag the current heading. FLAG non-nil means make invisible.
16668 When ENTRY is non-nil, show the entire entry."
16669 (save-excursion
16670 (org-back-to-heading t)
16671 ;; Check if we should show the entire entry
16672 (if entry
16673 (progn
16674 (org-show-entry)
16675 (save-excursion
16676 (and (outline-next-heading)
16677 (org-flag-heading nil))))
16678 (outline-flag-region (max 1 (1- (point)))
16679 (save-excursion (outline-end-of-heading) (point))
16680 flag))))
16682 (defun org-end-of-subtree (&optional invisible-OK)
16683 ;; This is an exact copy of the original function, but it uses
16684 ;; `org-back-to-heading', to make it work also in invisible
16685 ;; trees. And is uses an invisible-OK argument.
16686 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16687 (org-back-to-heading invisible-OK)
16688 (let ((first t)
16689 (level (funcall outline-level)))
16690 (while (and (not (eobp))
16691 (or first (> (funcall outline-level) level)))
16692 (setq first nil)
16693 (outline-next-heading))
16694 (if (memq (preceding-char) '(?\n ?\^M))
16695 (progn
16696 ;; Go to end of line before heading
16697 (forward-char -1)
16698 (if (memq (preceding-char) '(?\n ?\^M))
16699 ;; leave blank line before heading
16700 (forward-char -1)))))
16701 (point))
16703 (defun org-show-subtree ()
16704 "Show everything after this heading at deeper levels."
16705 (outline-flag-region
16706 (point)
16707 (save-excursion
16708 (outline-end-of-subtree) (outline-next-heading) (point))
16709 nil))
16711 (defun org-show-entry ()
16712 "Show the body directly following this heading.
16713 Show the heading too, if it is currently invisible."
16714 (interactive)
16715 (save-excursion
16716 (org-back-to-heading t)
16717 (outline-flag-region
16718 (max 1 (1- (point)))
16719 (save-excursion
16720 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16721 (or (match-beginning 1) (point-max)))
16722 nil)))
16724 (defun org-make-options-regexp (kwds)
16725 "Make a regular expression for keyword lines."
16726 (concat
16728 "#?[ \t]*\\+\\("
16729 (mapconcat 'regexp-quote kwds "\\|")
16730 "\\):[ \t]*"
16731 "\\(.+\\)"))
16733 ;; Make `bookmark-jump' show the jump location if it was hidden.
16734 (eval-after-load "bookmark"
16735 '(if (boundp 'bookmark-after-jump-hook)
16736 ;; We can use the hook
16737 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16738 ;; Hook not available, use advice
16739 (defadvice bookmark-jump (after org-make-visible activate)
16740 "Make the position visible."
16741 (org-bookmark-jump-unhide))))
16743 (defun org-bookmark-jump-unhide ()
16744 "Unhide the current position, to show the bookmark location."
16745 (and (org-mode-p)
16746 (or (org-invisible-p)
16747 (save-excursion (goto-char (max (point-min) (1- (point))))
16748 (org-invisible-p)))
16749 (org-show-hierarchy-above)))
16751 ;;; Experimental code
16754 ;(add-hook 'org-load-hook
16755 ; (lambda ()
16756 ; (defun outline-show-heading ()
16757 ; "Show the current heading and move to its end."
16758 ; (outline-flag-region
16759 ; (- (point)
16760 ; (cond
16761 ; ((bobp) 0)
16762 ; ((equal (buffer-substring
16763 ; (max (point-min) (- (point) 3)) (point))
16764 ; "\n\n\n")
16765 ; 2)
16766 ; (t 1)))
16767 ; (progn (outline-end-of-heading) (point))
16768 ; nil))))
16770 ;;; Finish up
16772 (provide 'org)
16774 (run-hooks 'org-load-hook)
16776 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16777 ;;; org.el ends here