Release 4.56
[org-mode.git] / org.el
blob30e72ebfe4b294672db5a2b2b2d80fa11a5a2dc8
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.56
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.56
65 ;; - `C-k' in agenda kills current line and corresponding subtree in file.
66 ;; - XEmacs compatibility issues fixed, in particular tag alignment.
67 ;; - M-left/right now in/outdents plain list items, no Shift needed.
68 ;; - Bug fixes.
70 ;; Version 4.55
71 ;; - Bug fixes.
73 ;; Version 4.54
74 ;; - Improvements to fast tag selection
75 ;; + show status also in target line.
76 ;; + option to auto-exit after first change to tags list (see manual).
77 ;; - Tags sparse trees now also respect the settings in
78 ;; `org-show-hierarchy-above' and `org-show-following-heading'.
79 ;; - Bug fixes.
81 ;; Version 4.53
82 ;; - Custom time formats can be overlayed over time stamps.
83 ;; - New option `org-agenda-todo-ignore-deadlines'.
84 ;; - Work-around for flyspell bug (CVS Emacs has this fixed in flyspell.el).
85 ;; - Work-around for session.el problem with circular data structures.
86 ;; - Bug fixes.
88 ;; Version 4.52
89 ;; - TAG matches can also specify conditions on TODO keywords.
90 ;; - The fast tag interface allows setting tags that are not in the
91 ;; predefined list.
92 ;; - Bug fixes.
94 ;; Version 4.51
95 ;; - Link abbreviations (manual section 4.5).
96 ;; - More control over how agenda is displayed. See the new variables
97 ;; `org-agenda-window-setup', `org-agenda-restore-windows-after-quit'.
98 ;; - Bug fixes.
100 ;;; Code:
102 (eval-when-compile
103 (require 'cl)
104 (require 'calendar))
105 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
106 ;; the file noutline.el being loaded.
107 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
108 ;; We require noutline, which might be provided in outline.el
109 (require 'outline) (require 'noutline)
110 ;; Other stuff we need.
111 (require 'time-date)
112 (require 'easymenu)
114 ;;; Customization variables
116 (defvar org-version "4.56"
117 "The version number of the file org.el.")
118 (defun org-version ()
119 (interactive)
120 (message "Org-mode version %s" org-version))
122 ;; Compatibility constants
123 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
124 (defconst org-format-transports-properties-p
125 (let ((x "a"))
126 (add-text-properties 0 1 '(test t) x)
127 (get-text-property 0 'test (format "%s" x)))
128 "Does format transport text properties?")
130 (defgroup org nil
131 "Outline-based notes management and organizer."
132 :tag "Org"
133 :group 'outlines
134 :group 'hypermedia
135 :group 'calendar)
137 (defgroup org-startup nil
138 "Options concerning startup of Org-mode."
139 :tag "Org Startup"
140 :group 'org)
142 (defcustom org-startup-folded t
143 "Non-nil means, entering Org-mode will switch to OVERVIEW.
144 This can also be configured on a per-file basis by adding one of
145 the following lines anywhere in the buffer:
147 #+STARTUP: fold
148 #+STARTUP: nofold
149 #+STARTUP: content"
150 :group 'org-startup
151 :type '(choice
152 (const :tag "nofold: show all" nil)
153 (const :tag "fold: overview" t)
154 (const :tag "content: all headlines" content)))
156 (defcustom org-startup-truncated t
157 "Non-nil means, entering Org-mode will set `truncate-lines'.
158 This is useful since some lines containing links can be very long and
159 uninteresting. Also tables look terrible when wrapped."
160 :group 'org-startup
161 :type 'boolean)
163 (defcustom org-startup-align-all-tables nil
164 "Non-nil means, align all tables when visiting a file.
165 This is useful when the column width in tables is forced with <N> cookies
166 in table fields. Such tables will look correct only after the first re-align.
167 This can also be configured on a per-file basis by adding one of
168 the following lines anywhere in the buffer:
169 #+STARTUP: align
170 #+STARTUP: noalign"
171 :group 'org-startup
172 :type 'boolean)
174 (defcustom org-startup-with-deadline-check nil
175 "Non-nil means, entering Org-mode will run the deadline check.
176 This means, if you start editing an org file, you will get an
177 immediate reminder of any due deadlines.
178 This can also be configured on a per-file basis by adding one of
179 the following lines anywhere in the buffer:
180 #+STARTUP: dlcheck
181 #+STARTUP: nodlcheck"
182 :group 'org-startup
183 :type 'boolean)
185 (defcustom org-insert-mode-line-in-empty-file nil
186 "Non-nil means insert the first line setting Org-mode in empty files.
187 When the function `org-mode' is called interactively in an empty file, this
188 normally means that the file name does not automatically trigger Org-mode.
189 To ensure that the file will always be in Org-mode in the future, a
190 line enforcing Org-mode will be inserted into the buffer, if this option
191 has been set."
192 :group 'org-startup
193 :type 'boolean)
195 (defcustom org-CUA-compatible nil
196 "Non-nil means use alternative key bindings for S-<cursor movement>.
197 Org-mode used S-<cursor movement> for changing timestamps and priorities.
198 S-<cursor movement> is also used for example by `CUA-mode' to select text.
199 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
200 alternative bindings. Setting this variable to t will replace the following
201 keys both in Org-mode and in the Org-agenda buffer.
203 S-RET -> C-S-RET
204 S-up -> M-p
205 S-down -> M-n
206 S-left -> M--
207 S-right -> M-+
209 If you do not like the alternative keys, take a look at the variable
210 `org-disputed-keys'.
212 This option is only relevant at load-time of Org-mode. Changing it requires
213 a restart of Emacs to become effective."
214 :group 'org-startup
215 :type 'boolean)
217 (defvar org-disputed-keys
218 '((S-up [(shift up)] [(meta ?p)])
219 (S-down [(shift down)] [(meta ?n)])
220 (S-left [(shift left)] [(meta ?-)])
221 (S-right [(shift right)] [(meta ?+)])
222 (S-return [(shift return)] [(control shift return)]))
223 "Keys for which Org-mode and other modes compete.
224 This is an alist, cars are symbols for lookup, 1st element is the default key,
225 second element will be used when `org-CUA-compatible' is t.")
227 (defun org-key (key)
228 "Select a key according to `org-CUA-compatible'."
229 (nth (if org-CUA-compatible 2 1)
230 (or (assq key org-disputed-keys)
231 (error "Invalid Key %s in `org-key'" key))))
233 (defcustom org-ellipsis nil
234 "The ellipsis to use in the Org-mode outline.
235 When nil, just use the standard three dots. When a string, use that instead,
236 and just in Org-mode (which will then use its own display table).
237 Changing this requires executing `M-x org-mode' in a buffer to become
238 effective."
239 :group 'org-startup
240 :type '(choice (const :tag "Default" nil)
241 (string :tag "String" :value "...#")))
243 (defvar org-display-table nil
244 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
246 (defgroup org-keywords nil
247 "Keywords in Org-mode."
248 :tag "Org Keywords"
249 :group 'org)
251 (defcustom org-deadline-string "DEADLINE:"
252 "String to mark deadline entries.
253 A deadline is this string, followed by a time stamp. Should be a word,
254 terminated by a colon. You can insert a schedule keyword and
255 a timestamp with \\[org-deadline].
256 Changes become only effective after restarting Emacs."
257 :group 'org-keywords
258 :type 'string)
260 (defcustom org-scheduled-string "SCHEDULED:"
261 "String to mark scheduled TODO entries.
262 A schedule is this string, followed by a time stamp. Should be a word,
263 terminated by a colon. You can insert a schedule keyword and
264 a timestamp with \\[org-schedule].
265 Changes become only effective after restarting Emacs."
266 :group 'org-keywords
267 :type 'string)
269 (defcustom org-closed-string "CLOSED:"
270 "String used as the prefix for timestamps logging closing a TODO entry."
271 :group 'org-keywords
272 :type 'string)
274 (defcustom org-clock-string "CLOCK:"
275 "String used as prefix for timestamps clocking work hours on an item."
276 :group 'org-keywords
277 :type 'string)
279 (defcustom org-comment-string "COMMENT"
280 "Entries starting with this keyword will never be exported.
281 An entry can be toggled between COMMENT and normal with
282 \\[org-toggle-comment].
283 Changes become only effective after restarting Emacs."
284 :group 'org-keywords
285 :type 'string)
287 (defcustom org-quote-string "QUOTE"
288 "Entries starting with this keyword will be exported in fixed-width font.
289 Quoting applies only to the text in the entry following the headline, and does
290 not extend beyond the next headline, even if that is lower level.
291 An entry can be toggled between QUOTE and normal with
292 \\[org-toggle-fixed-width-section]."
293 :group 'org-keywords
294 :type 'string)
296 (defgroup org-structure nil
297 "Options concerning the general structure of Org-mode files."
298 :tag "Org Structure"
299 :group 'org)
301 (defgroup org-cycle nil
302 "Options concerning visibility cycling in Org-mode."
303 :tag "Org Cycle"
304 :group 'org-structure)
306 (defcustom org-cycle-global-at-bob t
307 "Cycle globally if cursor is at beginning of buffer and not at a headline.
308 This makes it possible to do global cycling without having to use S-TAB or
309 C-u TAB. For this special case to work, the first line of the buffer
310 must not be a headline - it may be empty ot some other text. When used in
311 this way, `org-cycle-hook' is disables temporarily, to make sure the
312 cursor stays at the beginning of the buffer.
313 When this option is nil, don't do anything special at the beginning
314 of the buffer."
315 :group 'org-cycle
316 :type 'boolean)
318 (defcustom org-cycle-emulate-tab t
319 "Where should `org-cycle' emulate TAB.
320 nil Never
321 white Only in completely white lines
322 whitestart Only at the beginning of lines, before the first non-white char.
323 t Everywhere except in headlines
324 If TAB is used in a place where it does not emulate TAB, the current subtree
325 visibility is cycled."
326 :group 'org-cycle
327 :type '(choice (const :tag "Never" nil)
328 (const :tag "Only in completely white lines" white)
329 (const :tag "Before first char in a line" whitestart)
330 (const :tag "Everywhere except in headlines" t)
333 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
334 org-optimize-window-after-visibility-change)
335 "Hook that is run after `org-cycle' has changed the buffer visibility.
336 The function(s) in this hook must accept a single argument which indicates
337 the new state that was set by the most recent `org-cycle' command. The
338 argument is a symbol. After a global state change, it can have the values
339 `overview', `content', or `all'. After a local state change, it can have
340 the values `folded', `children', or `subtree'."
341 :group 'org-cycle
342 :type 'hook)
344 (defgroup org-edit-structure nil
345 "Options concerning structure editing in Org-mode."
346 :tag "Org Edit Structure"
347 :group 'org-structure)
349 (defcustom org-odd-levels-only nil
350 "Non-nil means, skip even levels and only use odd levels for the outline.
351 This has the effect that two stars are being added/taken away in
352 promotion/demotion commands. It also influences how levels are
353 handled by the exporters.
354 Changing it requires restart of `font-lock-mode' to become effective
355 for fontification also in regions already fontified.
356 You may also set this on a per-file basis by adding one of the following
357 lines to the buffer:
359 #+STARTUP: odd
360 #+STARTUP: oddeven"
361 :group 'org-edit-structure
362 :group 'org-font-lock
363 :type 'boolean)
365 (defcustom org-adapt-indentation t
366 "Non-nil means, adapt indentation when promoting and demoting.
367 When this is set and the *entire* text in an entry is indented, the
368 indentation is increased by one space in a demotion command, and
369 decreased by one in a promotion command. If any line in the entry
370 body starts at column 0, indentation is not changed at all."
371 :group 'org-edit-structure
372 :type 'boolean)
374 (defcustom org-blank-before-new-entry '((heading . nil)
375 (plain-list-item . nil))
376 "Should `org-insert-heading' leave a blank line before new heading/item?
377 The value is an alist, with `heading' and `plain-list-item' as car,
378 and a boolean flag as cdr."
379 :group 'org-edit-structure
380 :type '(list
381 (cons (const heading) (boolean))
382 (cons (const plain-list-item) (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-remove-highlights-with-change t
410 "Non-nil means, any change to the buffer will remove temporary highlights.
411 Such highlights are created by `org-occur' and `org-clock-display'.
412 When nil, `C-c C-c needs to be used to get rid of the highlights.
413 The highlights created by `org-preview-latex-fragment' always need
414 `C-c C-c' to be removed."
415 :group 'org-sparse-trees
416 :group 'org-time
417 :type 'boolean)
419 (defcustom org-show-hierarchy-above '((default . t))
420 "Non-nil means, show full hierarchy when showing a spot in the tree.
421 Turning this off makes sparse trees more compact, but also less clear.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. Valid contexts are
424 agenda when exposing an entry from the agenda
425 org-goto when using the command `org-goto' on key C-c C-j
426 occur-tree when using the command `org-occur' on key C-c /
427 tags-tree when constructing a sparse tree based on tags matches
428 link-search when exposing search matches associated with a link
429 mark-goto when exposing the jump goal of a mark
430 bookmark-jump when exposing a bookmark location
431 default default for all contexts not set explicitly"
432 :group 'org-sparse-trees
433 :type '(choice
434 (const :tag "Always" t)
435 (const :tag "Never" nil)
436 (repeat :greedy t :tag "Individual contexts"
437 (cons
438 (choice :tag "Context"
439 (const agenda)
440 (const org-goto)
441 (const occur-tree)
442 (const tags-tree)
443 (const link-search)
444 (const mark-goto)
445 (const bookmark-jump)
446 (const default))
447 (boolean)))))
449 (defcustom org-show-following-heading '((default . t))
450 "Non-nil means, show heading following match in `org-occur'.
451 When doing an `org-occur' it is useful to show the headline which
452 follows the match, even if they do not match the regexp. This makes it
453 easier to edit directly inside the sparse tree. However, if you use
454 `org-occur' mainly as an overview, the following headlines are
455 unnecessary clutter.
456 Instead of t, this can also be an alist specifying this option for different
457 contexts. See `org-show-hierarchy-above' for valid contexts."
458 :group 'org-sparse-trees
459 :type '(choice
460 (const :tag "Always" t)
461 (const :tag "Never" nil)
462 (repeat :greedy t :tag "Individual contexts"
463 (cons
464 (choice :tag "Context"
465 (const agenda)
466 (const org-goto)
467 (const occur-tree)
468 (const tags-tree)
469 (const link-search)
470 (const mark-goto)
471 (const bookmark-jump)
472 (const default))
473 (boolean)))))
475 (defcustom org-occur-hook '(org-first-headline-recenter)
476 "Hook that is run after `org-occur' has constructed a sparse tree.
477 This can be used to recenter the window to show as much of the structure
478 as possible."
479 :group 'org-sparse-trees
480 :type 'hook)
482 (defgroup org-plain-lists nil
483 "Options concerning plain lists in Org-mode."
484 :tag "Org Plain lists"
485 :group 'org-structure)
487 (defcustom org-cycle-include-plain-lists nil
488 "Non-nil means, include plain lists into visibility cycling.
489 This means that during cycling, plain list items will *temporarily* be
490 interpreted as outline headlines with a level given by 1000+i where i is the
491 indentation of the bullet. In all other operations, plain list items are
492 not seen as headlines. For example, you cannot assign a TODO keyword to
493 such an item."
494 :group 'org-plain-lists
495 :type 'boolean)
497 (defcustom org-plain-list-ordered-item-terminator t
498 "The character that makes a line with leading number an ordered list item.
499 Valid values are ?. and ?\). To get both terminators, use t. While
500 ?. may look nicer, it creates the danger that a line with leading
501 number may be incorrectly interpreted as an item. ?\) therefore is
502 the safe choice."
503 :group 'org-plain-lists
504 :type '(choice (const :tag "dot like in \"2.\"" ?.)
505 (const :tag "paren like in \"2)\"" ?\))
506 (const :tab "both" t)))
508 (defcustom org-auto-renumber-ordered-lists t
509 "Non-nil means, automatically renumber ordered plain lists.
510 Renumbering happens when the sequence have been changed with
511 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
512 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
513 :group 'org-plain-lists
514 :type 'boolean)
516 (defcustom org-provide-checkbox-statistics t
517 "Non-nil means, update checkbox statistics after insert and toggle.
518 When this is set, checkbox statistics is updated each time you either insert
519 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
520 with \\[org-ctrl-c-ctrl-c\\]."
521 :group 'org
522 :type 'boolean)
524 (defgroup org-archive nil
525 "Options concerning archiving in Org-mode."
526 :tag "Org Archive"
527 :group 'org-structure)
529 (defcustom org-archive-tag "ARCHIVE"
530 "The tag that marks a subtree as archived.
531 An archived subtree does not open during visibility cycling, and does
532 not contribute to the agenda listings."
533 :group 'org-archive
534 :group 'org-keywords
535 :type 'string)
537 (defcustom org-agenda-skip-archived-trees t
538 "Non-nil means, the agenda will skip any items located in archived trees.
539 An archived tree is a tree marked with the tag ARCHIVE."
540 :group 'org-archive
541 :group 'org-agenda-display
542 :type 'boolean)
544 (defcustom org-cycle-open-archived-trees nil
545 "Non-nil means, `org-cycle' will open archived trees.
546 An archived tree is a tree marked with the tag ARCHIVE.
547 When nil, archived trees will stay folded. You can still open them with
548 normal outline commands like `show-all', but not with the cycling commands."
549 :group 'org-archive
550 :group 'org-cycle
551 :type 'boolean)
553 (defcustom org-sparse-tree-open-archived-trees nil
554 "Non-nil means sparse tree construction shows matches in archived trees.
555 When nil, matches in these trees are highlighted, but the trees are kept in
556 collapsed state."
557 :group 'org-archive
558 :group 'org-sparse-trees
559 :type 'boolean)
561 (defcustom org-archive-location "%s_archive::"
562 "The location where subtrees should be archived.
563 This string consists of two parts, separated by a double-colon.
565 The first part is a file name - when omitted, archiving happens in the same
566 file. %s will be replaced by the current file name (without directory part).
567 Archiving to a different file is useful to keep archived entries from
568 contributing to the Org-mode Agenda.
570 The part after the double colon is a headline. The archived entries will be
571 filed under that headline. When omitted, the subtrees are simply filed away
572 at the end of the file, as top-level entries.
574 Here are a few examples:
575 \"%s_archive::\"
576 If the current file is Projects.org, archive in file
577 Projects.org_archive, as top-level trees. This is the default.
579 \"::* Archived Tasks\"
580 Archive in the current file, under the top-level headline
581 \"* Archived Tasks\".
583 \"~/org/archive.org::\"
584 Archive in file ~/org/archive.org (absolute path), as top-level trees.
586 \"basement::** Finished Tasks\"
587 Archive in file ./basement (relative path), as level 3 trees
588 below the level 2 heading \"** Finished Tasks\".
590 You may set this option on a per-file basis by adding to the buffer a
591 line like
593 #+ARCHIVE: basement::** Finished Tasks"
594 :group 'org-archive
595 :type 'string)
597 (defcustom org-archive-mark-done t
598 "Non-nil means, mark entries as DONE when they are moved to the archive file."
599 :group 'org-archive
600 :type 'boolean)
602 (defcustom org-archive-stamp-time t
603 "Non-nil means, add a time stamp to entries moved to an archive file.
604 The time stamp will be added directly after the TODO state keyword in the
605 first line, so it is probably best to use this in combinations with
606 `org-archive-mark-done'."
607 :group 'org-archive
608 :type 'boolean)
610 (defgroup org-table nil
611 "Options concerning tables in Org-mode."
612 :tag "Org Table"
613 :group 'org)
615 (defcustom org-enable-table-editor 'optimized
616 "Non-nil means, lines starting with \"|\" are handled by the table editor.
617 When nil, such lines will be treated like ordinary lines.
619 When equal to the symbol `optimized', the table editor will be optimized to
620 do the following:
621 - Automatic overwrite mode in front of whitespace in table fields.
622 This makes the structure of the table stay in tact as long as the edited
623 field does not exceed the column width.
624 - Minimize the number of realigns. Normally, the table is aligned each time
625 TAB or RET are pressed to move to another field. With optimization this
626 happens only if changes to a field might have changed the column width.
627 Optimization requires replacing the functions `self-insert-command',
628 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
629 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
630 very good at guessing when a re-align will be necessary, but you can always
631 force one with \\[org-ctrl-c-ctrl-c].
633 If you would like to use the optimized version in Org-mode, but the
634 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
636 This variable can be used to turn on and off the table editor during a session,
637 but in order to toggle optimization, a restart is required.
639 See also the variable `org-table-auto-blank-field'."
640 :group 'org-table
641 :type '(choice
642 (const :tag "off" nil)
643 (const :tag "on" t)
644 (const :tag "on, optimized" optimized)))
646 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
647 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
648 In the optimized version, the table editor takes over all simple keys that
649 normally just insert a character. In tables, the characters are inserted
650 in a way to minimize disturbing the table structure (i.e. in overwrite mode
651 for empty fields). Outside tables, the correct binding of the keys is
652 restored.
654 The default for this option is t if the optimized version is also used in
655 Org-mode. See the variable `org-enable-table-editor' for details. Changing
656 this variable requires a restart of Emacs to become effective."
657 :group 'org-table
658 :type 'boolean)
660 (defgroup org-table-settings nil
661 "Settings for tables in Org-mode."
662 :tag "Org Table Settings"
663 :group 'org-table)
665 (defcustom org-table-default-size "5x2"
666 "The default size for newly created tables, Columns x Rows."
667 :group 'org-table-settings
668 :type 'string)
670 (defcustom org-table-number-regexp
671 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$"
672 "Regular expression for recognizing numbers in table columns.
673 If a table column contains mostly numbers, it will be aligned to the
674 right. If not, it will be aligned to the left.
676 The default value of this option is a regular expression which allows
677 anything which looks remotely like a number as used in scientific
678 context. For example, all of the following will be considered a
679 number:
680 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
682 Other options offered by the customize interface are more restrictive."
683 :group 'org-table-settings
684 :type '(choice
685 (const :tag "Positive Integers"
686 "^[0-9]+$")
687 (const :tag "Integers"
688 "^[-+]?[0-9]+$")
689 (const :tag "Floating Point Numbers"
690 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
691 (const :tag "Floating Point Number or Integer"
692 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
693 (const :tag "Exponential, Floating point, Integer"
694 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
695 (const :tag "Very General Number-Like, including hex"
696 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$")
697 (string :tag "Regexp:")))
699 (defcustom org-table-number-fraction 0.5
700 "Fraction of numbers in a column required to make the column align right.
701 In a column all non-white fields are considered. If at least this
702 fraction of fields is matched by `org-table-number-fraction',
703 alignment to the right border applies."
704 :group 'org-table-settings
705 :type 'number)
707 (defgroup org-table-editing nil
708 "Bahavior of tables during editing in Org-mode."
709 :tag "Org Table Editing"
710 :group 'org-table)
712 (defcustom org-table-automatic-realign t
713 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
714 When nil, aligning is only done with \\[org-table-align], or after column
715 removal/insertion."
716 :group 'org-table-editing
717 :type 'boolean)
719 (defcustom org-table-limit-column-width t ;kw
720 "Non-nil means, allow to limit the width of table columns with <N> fields."
721 :group 'org-table-editing
722 :type 'boolean)
724 (defcustom org-table-auto-blank-field t
725 "Non-nil means, automatically blank table field when starting to type into it.
726 This only happens when typing immediately after a field motion
727 command (TAB, S-TAB or RET).
728 Only relevant when `org-enable-table-editor' is equal to `optimized'."
729 :group 'org-table-editing
730 :type 'boolean)
732 (defcustom org-table-tab-jumps-over-hlines t
733 "Non-nil means, tab in the last column of a table with jump over a hline.
734 If a horizontal separator line is following the current line,
735 `org-table-next-field' can either create a new row before that line, or jump
736 over the line. When this option is nil, a new line will be created before
737 this line."
738 :group 'org-table-editing
739 :type 'boolean)
741 (defcustom org-table-tab-recognizes-table.el t
742 "Non-nil means, TAB will automatically notice a table.el table.
743 When it sees such a table, it moves point into it and - if necessary -
744 calls `table-recognize-table'."
745 :group 'org-table-editing
746 :type 'boolean)
748 (defgroup org-table-calculation nil
749 "Options concerning tables in Org-mode."
750 :tag "Org Table Calculation"
751 :group 'org-table)
753 (defcustom org-table-copy-increment t
754 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
755 :group 'org-table-calculation
756 :type 'boolean)
758 (defcustom org-calc-default-modes
759 '(calc-internal-prec 12
760 calc-float-format (float 5)
761 calc-angle-mode deg
762 calc-prefer-frac nil
763 calc-symbolic-mode nil
764 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
765 calc-display-working-message t
767 "List with Calc mode settings for use in calc-eval for table formulas.
768 The list must contain alternating symbols (Calc modes variables and values).
769 Don't remove any of the default settings, just change the values. Org-mode
770 relies on the variables to be present in the list."
771 :group 'org-table-calculation
772 :type 'plist)
774 (defcustom org-table-formula-evaluate-inline t
775 "Non-nil means, TAB and RET evaluate a formula in current table field.
776 If the current field starts with an equal sign, it is assumed to be a formula
777 which should be evaluated as described in the manual and in the documentation
778 string of the command `org-table-eval-formula'. This feature requires the
779 Emacs calc package.
780 When this variable is nil, formula calculation is only available through
781 the command \\[org-table-eval-formula]."
782 :group 'org-table-calculation
783 :type 'boolean)
786 (defcustom org-table-formula-use-constants t
787 "Non-nil means, interpret constants in formulas in tables.
788 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
789 by the value given in `org-table-formula-constants', or by a value obtained
790 from the `constants.el' package."
791 :group 'org-table-calculation
792 :type 'boolean)
794 (defcustom org-table-formula-constants nil
795 "Alist with constant names and values, for use in table formulas.
796 The car of each element is a name of a constant, without the `$' before it.
797 The cdr is the value as a string. For example, if you'd like to use the
798 speed of light in a formula, you would configure
800 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
802 and then use it in an equation like `$1*$c'."
803 :group 'org-table-calculation
804 :type '(repeat
805 (cons (string :tag "name")
806 (string :tag "value"))))
808 (defcustom org-table-formula-numbers-only nil
809 "Non-nil means, calculate only with numbers in table formulas.
810 Then all input fields will be converted to a number, and the result
811 must also be a number. When nil, calc's full potential is available
812 in table calculations, including symbolics etc."
813 :group 'org-table-calculation
814 :type 'boolean)
816 (defcustom org-table-allow-automatic-line-recalculation t
817 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
818 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
819 :group 'org-table-calculation
820 :type 'boolean)
822 (defgroup org-link nil
823 "Options concerning links in Org-mode."
824 :tag "Org Link"
825 :group 'org)
827 (defvar org-link-abbrev-alist-local nil
828 "buffer-local version of `org-link-abbrev-alist', which see.
829 The value of this is taken from the #+LINK lines.")
830 (make-variable-buffer-local 'org-link-abbrev-alist-local)
832 (defcustom org-link-abbrev-alist nil
833 "Alist of link abbreviations.
834 The car of each element is a string, to be replaced at the start of a link.
835 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
836 links in Org-mode buffers can have an optional tag after a double colon, e.g.
838 [[linkkey::tag][description]]
840 If REPLACE is a string, the tag will simply be appended to create the link.
841 If the string contains \"%s\", the tag will be inserted there. REPLACE may
842 also be a function that will be called with the tag as the only argument to
843 create the link. See the manual for examples."
844 :group 'org-link
845 :type 'alist)
847 (defcustom org-descriptive-links t
848 "Non-nil means, hide link part and only show description of bracket links.
849 Bracket links are like [[link][descritpion]]. This variable sets the initial
850 state in new org-mode buffers. The setting can then be toggled on a
851 per-buffer basis from the Org->Hyperlinks menu."
852 :group 'org-link
853 :type 'boolean)
855 (defcustom org-link-style 'bracket
856 "The style of links to be inserted with \\[org-insert-link].
857 Possible values are:
858 bracket [[link][description]]. This is recommended
859 plain Description \\n link. The old way, no longer recommended."
860 :group 'org-link
861 :type '(choice
862 (const :tag "Bracket (recommended)" bracket)
863 (const :tag "Plain (no longer recommended)" plain)))
865 (defcustom org-link-format "%s"
866 "Default format for external, URL-like linkes in the buffer.
867 This is a format string for printf, %s will be replaced by the link text.
868 The recommended value is just \"%s\", since links will be protected by
869 enclosing them in double brackets. If you prefer plain links (see variable
870 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
871 additional URL: prefix, so the format would be \"<URL:%s>\"."
872 :group 'org-link
873 :type '(choice
874 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
875 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
876 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
877 (string :tag "Other" :value "<%s>")))
879 (defcustom org-link-file-path-type 'adaptive
880 "How the path name in file links should be stored.
881 Valid values are:
883 relative relative to the current directory, i.e. the directory of the file
884 into which the link is being inserted.
885 absolute absolute path, if possible with ~ for home directory.
886 noabbrev absolute path, no abbreviation of home directory.
887 adaptive Use relative path for files in the current directory and sub-
888 directories of it. For other files, use an absolute path."
889 :group 'org-link
890 :type '(choice
891 (const relative)
892 (const absolute)
893 (const noabbrev)
894 (const adaptive)))
896 (defcustom org-activate-links '(bracket angle plain radio tag date)
897 "Types of links that should be activated in Org-mode files.
898 This is a list of symbols, each leading to the activation of a certain link
899 type. In principle, it does not hurt to turn on most link types - there may
900 be a small gain when turning off unused link types. The types are:
902 bracket The recommended [[link][description]] or [[link]] links with hiding.
903 angular Links in angular brackes that may contain whitespace like
904 <bbdb:Carsten Dominik>.
905 plain Plain links in normal text, no whitespace, like http://google.com.
906 radio Text that is matched by a radio target, see manual for details.
907 tag Tag settings in a headline (link to tag search).
908 date Time stamps (link to calendar).
909 camel CamelCase words defining text searches.
911 Changing this variable requires a restart of Emacs to become effective."
912 :group 'org-link
913 :type '(set (const :tag "Double bracket links (new style)" bracket)
914 (const :tag "Angular bracket links (old style)" angular)
915 (const :tag "plain text links" plain)
916 (const :tag "Radio target matches" radio)
917 (const :tag "Tags" tag)
918 (const :tag "Timestamps" date)
919 (const :tag "CamelCase words" camel)))
921 (defgroup org-link-store nil
922 "Options concerning storing links in Org-mode"
923 :tag "Org Store Link"
924 :group 'org-link)
926 (defcustom org-context-in-file-links t
927 "Non-nil means, file links from `org-store-link' contain context.
928 A search string will be added to the file name with :: as separator and
929 used to find the context when the link is activated by the command
930 `org-open-at-point'.
931 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
932 negates this setting for the duration of the command."
933 :group 'org-link-store
934 :type 'boolean)
936 (defcustom org-file-link-context-use-camel-case nil
937 "Non-nil means, use CamelCase to store a search context in a file link.
938 When nil, the search string simply consists of the words of the string.
939 CamelCase is deprecated, and support for it may be dropped in the future."
940 :group 'org-link-store
941 :type 'boolean)
943 (defcustom org-keep-stored-link-after-insertion nil
944 "Non-nil means, keep link in list for entire session.
946 The command `org-store-link' adds a link pointing to the current
947 location to an internal list. These links accumulate during a session.
948 The command `org-insert-link' can be used to insert links into any
949 Org-mode file (offering completion for all stored links). When this
950 option is nil, every link which has been inserted once using \\[org-insert-link]
951 will be removed from the list, to make completing the unused links
952 more efficient."
953 :group 'org-link-store
954 :type 'boolean)
956 (defcustom org-usenet-links-prefer-google nil
957 "Non-nil means, `org-store-link' will create web links to Google groups.
958 When nil, Gnus will be used for such links.
959 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
960 negates this setting for the duration of the command."
961 :group 'org-link-store
962 :type 'boolean)
964 (defgroup org-link-follow nil
965 "Options concerning following links in Org-mode"
966 :tag "Org Follow Link"
967 :group 'org-link)
969 (defcustom org-tab-follows-link nil
970 "Non-nil means, on links TAB will follow the link.
971 Needs to be set before org.el is loaded."
972 :group 'org-link-follow
973 :type 'boolean)
975 (defcustom org-return-follows-link nil
976 "Non-nil means, on links RET will follow the link.
977 Needs to be set before org.el is loaded."
978 :group 'org-link-follow
979 :type 'boolean)
981 (defcustom org-mouse-1-follows-link t
982 "Non-nil means, mouse-1 on a link will follow the link.
983 A longer mouse click will still set point. Does not wortk on XEmacs.
984 Needs to be set before org.el is loaded."
985 :group 'org-link-follow
986 :type 'boolean)
988 (defcustom org-mark-ring-length 4
989 "Number of different positions to be recorded in the ring
990 Changing this requires a restart of Emacs to work correctly."
991 :group 'org-link-follow
992 :type 'interger)
994 (defcustom org-link-frame-setup
995 '((vm . vm-visit-folder-other-frame)
996 (gnus . gnus-other-frame)
997 (file . find-file-other-window))
998 "Setup the frame configuration for following links.
999 When following a link with Emacs, it may often be useful to display
1000 this link in another window or frame. This variable can be used to
1001 set this up for the different types of links.
1002 For VM, use any of
1003 `vm-visit-folder'
1004 `vm-visit-folder-other-frame'
1005 For Gnus, use any of
1006 `gnus'
1007 `gnus-other-frame'
1008 For FILE, use any of
1009 `find-file'
1010 `find-file-other-window'
1011 `find-file-other-frame'
1012 For the calendar, use the variable `calendar-setup'.
1013 For BBDB, it is currently only possible to display the matches in
1014 another window."
1015 :group 'org-link-follow
1016 :type '(list
1017 (cons (const vm)
1018 (choice
1019 (const vm-visit-folder)
1020 (const vm-visit-folder-other-window)
1021 (const vm-visit-folder-other-frame)))
1022 (cons (const gnus)
1023 (choice
1024 (const gnus)
1025 (const gnus-other-frame)))
1026 (cons (const file)
1027 (choice
1028 (const find-file)
1029 (const find-file-other-window)
1030 (const find-file-other-frame)))))
1032 (defcustom org-display-internal-link-with-indirect-buffer nil
1033 "Non-nil means, use indirect buffer to display infile links.
1034 Activating internal links (from one location in a file to another location
1035 in the same file) normally just jumps to the location. When the link is
1036 activated with a C-u prefix (or with mouse-3), the link is displayed in
1037 another window. When this option is set, the other window actually displays
1038 an indirect buffer clone of the current buffer, to avoid any visibility
1039 changes to the current buffer."
1040 :group 'org-link-follow
1041 :type 'boolean)
1044 (defcustom org-open-non-existing-files nil
1045 "Non-nil means, `org-open-file' will open non-existing file.
1046 When nil, an error will be generated."
1047 :group 'org-link-follow
1048 :type 'boolean)
1050 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1051 "Function and arguments to call for following mailto links.
1052 This is a list with the first element being a lisp function, and the
1053 remaining elements being arguments to the function. In string arguments,
1054 %a will be replaced by the address, and %s will be replaced by the subject
1055 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1056 :group 'org-link-follow
1057 :type '(choice
1058 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1059 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1060 (const :tag "message-mail" (message-mail "%a" "%s"))
1061 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1063 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1064 "Non-nil means, ask for confirmation before executing shell links.
1065 Shell links can be dangerous, just thing about a link
1067 [[shell:rm -rf ~/*][Google Search]]
1069 This link would show up in your Org-mode document as \"Google Search\"
1070 but really it would remove your entire home directory.
1071 Therefore I *definitely* advise against setting this variable to nil.
1072 Just change it to `y-or-n-p' of you want to confirm with a single key press
1073 rather than having to type \"yes\"."
1074 :group 'org-link-follow
1075 :type '(choice
1076 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1077 (const :tag "with y-or-n (faster)" y-or-n-p)
1078 (const :tag "no confirmation (dangerous)" nil)))
1080 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1081 "Non-nil means, ask for confirmation before executing elisp links.
1082 Elisp links can be dangerous, just think about a link
1084 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1086 This link would show up in your Org-mode document as \"Google Search\"
1087 but really it would remove your entire home directory.
1088 Therefore I *definitely* advise against setting this variable to nil.
1089 Just change it to `y-or-n-p' of you want to confirm with a single key press
1090 rather than having to type \"yes\"."
1091 :group 'org-link-follow
1092 :type '(choice
1093 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1094 (const :tag "with y-or-n (faster)" y-or-n-p)
1095 (const :tag "no confirmation (dangerous)" nil)))
1097 (defconst org-file-apps-defaults-gnu
1098 '((remote . emacs)
1099 (t . mailcap))
1100 "Default file applications on a UNIX or GNU/Linux system.
1101 See `org-file-apps'.")
1103 (defconst org-file-apps-defaults-macosx
1104 '((remote . emacs)
1105 (t . "open %s")
1106 ("ps" . "gv %s")
1107 ("ps.gz" . "gv %s")
1108 ("eps" . "gv %s")
1109 ("eps.gz" . "gv %s")
1110 ("dvi" . "xdvi %s")
1111 ("fig" . "xfig %s"))
1112 "Default file applications on a MacOS X system.
1113 The system \"open\" is known as a default, but we use X11 applications
1114 for some files for which the OS does not have a good default.
1115 See `org-file-apps'.")
1117 (defconst org-file-apps-defaults-windowsnt
1118 (list
1119 '(remote . emacs)
1120 (cons t
1121 (list (if (featurep 'xemacs)
1122 'mswindows-shell-execute
1123 'w32-shell-execute)
1124 "open" 'file)))
1125 "Default file applications on a Windows NT system.
1126 The system \"open\" is used for most files.
1127 See `org-file-apps'.")
1129 (defcustom org-file-apps
1131 ("txt" . emacs)
1132 ("tex" . emacs)
1133 ("ltx" . emacs)
1134 ("org" . emacs)
1135 ("el" . emacs)
1136 ("bib" . emacs)
1138 "External applications for opening `file:path' items in a document.
1139 Org-mode uses system defaults for different file types, but
1140 you can use this variable to set the application for a given file
1141 extension. The entries in this list are cons cells where the car identifies
1142 files and the cdr the corresponding command. Possible values for the
1143 file identifier are
1144 \"ext\" A string identifying an extension
1145 `directory' Matches a directory
1146 `remote' Matches a remote file, accessible through tramp or efs.
1147 Remote files most likely should be visited through Emacs
1148 because external applications cannot handle such paths.
1149 t Default for all remaining files
1151 Possible values for the command are:
1152 `emacs' The file will be visited by the current Emacs process.
1153 `default' Use the default application for this file type.
1154 string A command to be executed by a shell; %s will be replaced
1155 by the path to the file.
1156 sexp A Lisp form which will be evaluated. The file path will
1157 be available in the Lisp variable `file'.
1158 For more examples, see the system specific constants
1159 `org-file-apps-defaults-macosx'
1160 `org-file-apps-defaults-windowsnt'
1161 `org-file-apps-defaults-gnu'."
1162 :group 'org-link-follow
1163 :type '(repeat
1164 (cons (choice :value ""
1165 (string :tag "Extension")
1166 (const :tag "Default for unrecognized files" t)
1167 (const :tag "Remote file" remote)
1168 (const :tag "Links to a directory" directory))
1169 (choice :value ""
1170 (const :tag "Visit with Emacs" emacs)
1171 (const :tag "Use system default" default)
1172 (string :tag "Command")
1173 (sexp :tag "Lisp form")))))
1175 (defcustom org-mhe-search-all-folders nil
1176 "Non-nil means, that the search for the mh-message will be extended to
1177 all folders if the message cannot be found in the folder given in the link.
1178 Searching all folders is very effective with one of the search engines
1179 supported by MH-E, but will be slow with pick."
1180 :group 'org-link-follow
1181 :type 'boolean)
1183 (defgroup org-remember nil
1184 "Options concerning interaction with remember.el."
1185 :tag "Org Remember"
1186 :group 'org)
1188 (defcustom org-directory "~/org"
1189 "Directory with org files.
1190 This directory will be used as default to prompt for org files.
1191 Used by the hooks for remember.el."
1192 :group 'org-remember
1193 :type 'directory)
1195 (defcustom org-default-notes-file "~/.notes"
1196 "Default target for storing notes.
1197 Used by the hooks for remember.el. This can be a string, or nil to mean
1198 the value of `remember-data-file'."
1199 :group 'org-remember
1200 :type '(choice
1201 (const :tag "Default from remember-data-file" nil)
1202 file))
1204 (defcustom org-remember-templates nil
1205 "Templates for the creation of remember buffers.
1206 When nil, just let remember make the buffer.
1207 When not nil, this is a list of 3-element lists. In each entry, the first
1208 element is a character, a unique key to select this template.
1209 The second element is the template. The third element is optional and can
1210 specify a destination file for remember items created with this template.
1211 The default file is given by `org-default-notes-file'.
1213 The template specifies the structure of the remember buffer. It should have
1214 a first line starting with a star, to act as the org-mode headline.
1215 Furthermore, the following %-escapes will be replaced with content:
1216 %t time stamp, date only
1217 %T time stamp with date and time
1218 %u inactive time stamp, date only
1219 %U inactive time stamp with date and time
1220 %n user name
1221 %a annotation, normally the link created with org-store-link
1222 %i initial content, the region when remember is called with C-u.
1223 If %i is indented, the entire inserted text will be indented as well.
1224 %? This will be removed, and the cursor placed at this position."
1225 :group 'org-remember
1226 :type '(repeat :tag "enabled"
1227 (list :value (?a "\n" nil)
1228 (character :tag "Selection Key")
1229 (string :tag "Template")
1230 (file :tag "Destination file (optional)"))))
1232 (defcustom org-reverse-note-order nil
1233 "Non-nil means, store new notes at the beginning of a file or entry.
1234 When nil, new notes will be filed to the end of a file or entry."
1235 :group 'org-remember
1236 :type '(choice
1237 (const :tag "Reverse always" t)
1238 (const :tag "Reverse never" nil)
1239 (repeat :tag "By file name regexp"
1240 (cons regexp boolean))))
1242 (defgroup org-todo nil
1243 "Options concerning TODO items in Org-mode."
1244 :tag "Org TODO"
1245 :group 'org)
1247 (defcustom org-todo-keywords '("TODO" "DONE")
1248 "List of TODO entry keywords.
1249 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1250 considered to mean that the entry is \"done\". All the other mean that
1251 action is required, and will make the entry show up in todo lists, diaries
1252 etc.
1253 The command \\[org-todo] cycles an entry through these states, and an
1254 additional state where no keyword is present. For details about this
1255 cycling, see also the variable `org-todo-interpretation'
1256 Changes become only effective after restarting Emacs."
1257 :group 'org-todo
1258 :group 'org-keywords
1259 :type '(repeat (string :tag "Keyword")))
1261 (defcustom org-todo-interpretation 'sequence
1262 "Controls how TODO keywords are interpreted.
1263 This variable is only relevant if `org-todo-keywords' contains more than two
1264 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1266 When `sequence', \\[org-todo] will always switch to the next state in the
1267 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1268 to state when executed several times in direct succession. Otherwise, it
1269 switches directly to DONE from any state.
1270 See the manual for more information."
1271 :group 'org-todo
1272 :group 'org-keywords
1273 :type '(choice (const sequence)
1274 (const type)))
1276 (defcustom org-after-todo-state-change-hook nil
1277 "Hook which is run after the state of a TODO item was changed.
1278 The new state (a string with a TODO keyword, or nil) is available in the
1279 Lisp variable `state'."
1280 :group 'org-todo
1281 :type 'hook)
1283 (defcustom org-log-done nil
1284 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1285 When the state of an entry is changed from nothing to TODO, remove a previous
1286 closing date.
1288 This can also be a list of symbols indicating under which conditions
1289 the time stamp recording the action should be annotated with a short note.
1290 Valid members of this list are
1292 done Offer to record a note when marking entries done
1293 clock-out Offer to record a note when clocking out of an item.
1295 A separate window will then pop up and allow you to type a note.
1296 After finishing with C-c C-c, the note will be added directly after the
1297 timestamp, as a plain list item. See also the variable
1298 `org-log-note-headings'.
1300 Logging can also be configured on a per-file basis by adding one of
1301 the following lines anywhere in the buffer:
1303 #+STARTUP: logging
1304 #+STARTUP: nologging"
1305 ;; FIXME: in-buffer words for notes???????
1306 :group 'org-todo
1307 :type '(choice
1308 (const :tag "off" nil)
1309 (const :tag "on" t)
1310 (set :tag "on, with notes" :greedy t :value (done)
1311 (const done) (const clock-out))))
1313 (defcustom org-log-note-headings '((done . "CLOSING NOTE") (clock-out . ""))
1314 "Headings for notes added when clocking out or closing TODO items.
1315 The value is an alist, with the car being a sympol indicating the note
1316 context, and the cdr is the heading to be used. The heading may also be the
1317 empty string."
1318 :group 'org-todo
1319 :type '(list :greedy t
1320 (cons (const :tag "Heading when closing an item" done) string)
1321 (cons (const :tag "Heading when clocking out" clock-out) string)))
1323 (defgroup org-priorities nil
1324 "Priorities in Org-mode."
1325 :tag "Org Priorities"
1326 :group 'org-todo)
1328 (defcustom org-default-priority ?B
1329 "The default priority of TODO items.
1330 This is the priority an item get if no explicit priority is given."
1331 :group 'org-priorities
1332 :type 'character)
1334 (defcustom org-lowest-priority ?C
1335 "The lowest priority of TODO items. A character like ?A, ?B etc."
1336 :group 'org-priorities
1337 :type 'character)
1339 (defgroup org-time nil
1340 "Options concerning time stamps and deadlines in Org-mode."
1341 :tag "Org Time"
1342 :group 'org)
1344 (defcustom org-insert-labeled-timestamps-at-point nil
1345 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1346 When nil, these labeled time stamps are forces into the second line of an
1347 entry, just after the headline. When scheduling from the global TODO list,
1348 the time stamp will always be forced into the second line."
1349 :group 'org-time
1350 :type 'boolean)
1352 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1353 "Formats for `format-time-string' which are used for time stamps.
1354 It is not recommended to change this constant.")
1356 (defcustom org-time-stamp-rounding-minutes 0
1357 "Number of minutes to round time stamps to upon insertion.
1358 When zero, insert the time unmodified. Useful rounding numbers
1359 should be factors of 60, so for example 5, 10, 15.
1360 When this is not zero, you can still force an exact time-stamp by using
1361 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1362 :group 'org-time
1363 :type 'integer)
1365 (defcustom org-display-custom-times nil
1366 "Non-nil means, overlay custom formats over all time stamps.
1367 The formats are defined through the variable `org-time-stamp-custom-formats'.
1368 To turn this on on a per-file basis, insert anywhere in the file:
1369 #+STARTUP: customtime"
1370 :group 'org-time
1371 :set 'set-default
1372 :type 'sexp)
1373 (make-variable-buffer-local 'org-display-custom-times)
1375 (defcustom org-time-stamp-custom-formats
1376 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1377 "Custom formats for time stamps. See `format-time-string' for the syntax.
1378 These are overlayed over the default ISO format if the variable
1379 `org-display-custom-times' is set."
1380 :group 'org-time
1381 :type 'sexp)
1383 (defcustom org-deadline-warning-days 30
1384 "No. of days before expiration during which a deadline becomes active.
1385 This variable governs the display in sparse trees and in the agenda."
1386 :group 'org-time
1387 :type 'number)
1389 (defcustom org-popup-calendar-for-date-prompt t
1390 "Non-nil means, pop up a calendar when prompting for a date.
1391 In the calendar, the date can be selected with mouse-1. However, the
1392 minibuffer will also be active, and you can simply enter the date as well.
1393 When nil, only the minibuffer will be available."
1394 :group 'org-time
1395 :type 'boolean)
1397 (defcustom org-calendar-follow-timestamp-change t
1398 "Non-nil means, make the calendar window follow timestamp changes.
1399 When a timestamp is modified and the calendar window is visible, it will be
1400 moved to the new date."
1401 :group 'org-time
1402 :type 'boolean)
1404 (defgroup org-tags nil
1405 "Options concerning tags in Org-mode."
1406 :tag "Org Tags"
1407 :group 'org)
1409 (defcustom org-tag-alist nil
1410 "List of tags allowed in Org-mode files.
1411 When this list is nil, Org-mode will base TAG input on what is already in the
1412 buffer.
1413 The value of this variable is an alist, the car may be (and should) be a
1414 character that is used to select that tag through the fast-tag-selection
1415 interface. See the manual for details."
1416 :group 'org-tags
1417 :type '(repeat
1418 (choice
1419 (cons (string :tag "Tag name")
1420 (character :tag "Access char"))
1421 (const :tag "Start radio group" (:startgroup))
1422 (const :tag "End radio group" (:endgroup)))))
1424 (defcustom org-use-fast-tag-selection 'auto
1425 "Non-nil means, use fast tag selection scheme.
1426 This is a special interface to select and deselect tags with single keys.
1427 When nil, fast selection is never used.
1428 When the symbol `auto', fast selection is used if and only if selection
1429 characters for tags have been configured, either through the variable
1430 `org-tag-alist' or through a #+TAGS line in the buffer.
1431 When t, fast selection is always used and selection keys are assigned
1432 automatically if necessary."
1433 :group 'org-tags
1434 :type '(choice
1435 (const :tag "Always" t)
1436 (const :tag "Never" nil)
1437 (const :tag "When selection characters are configured" 'auto)))
1439 (defcustom org-fast-tag-selection-single-key nil
1440 "Non-nil means, fast tag selection exits after first change.
1441 When nil, you have to press RET to exit it.
1442 During fast tag selection, you can toggle this flag with `C-c'."
1443 :group 'org-tags
1444 :type 'boolean)
1446 (defcustom org-tags-column 48
1447 "The column to which tags should be indented in a headline.
1448 If this number is positive, it specifies the column. If it is negative,
1449 it means that the tags should be flushright to that column. For example,
1450 -79 works well for a normal 80 character screen."
1451 :group 'org-tags
1452 :type 'integer)
1454 (defcustom org-auto-align-tags t
1455 "Non-nil means, realign tags after pro/demotion of TODO state change.
1456 These operations change the length of a headline and therefore shift
1457 the tags around. With this options turned on, after each such operation
1458 the tags are again aligned to `org-tags-column'."
1459 :group 'org-tags
1460 :type 'boolean)
1462 (defcustom org-use-tag-inheritance t
1463 "Non-nil means, tags in levels apply also for sublevels.
1464 When nil, only the tags directly given in a specific line apply there.
1465 If you turn off this option, you very likely want to turn on the
1466 companion option `org-tags-match-list-sublevels'."
1467 :group 'org-tags
1468 :type 'boolean)
1470 (defcustom org-tags-match-list-sublevels nil
1471 "Non-nil means list also sublevels of headlines matching tag search.
1472 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1473 the sublevels of a headline matching a tag search often also match
1474 the same search. Listing all of them can create very long lists.
1475 Setting this variable to nil causes subtrees of a match to be skipped.
1476 This option is off by default, because inheritance in on. If you turn
1477 inheritance off, you very likely want to turn this option on.
1479 As a special case, if the tag search is restricted to TODO items, the
1480 value of this variable is ignored and sublevels are always checked, to
1481 make sure all corresponding TODO items find their way into the list."
1482 :group 'org-tags
1483 :type 'boolean)
1485 (defvar org-tags-history nil
1486 "History of minibuffer reads for tags.")
1487 (defvar org-last-tags-completion-table nil
1488 "The last used completion table for tags.")
1490 (defgroup org-agenda nil
1491 "Options concerning agenda display Org-mode."
1492 :tag "Org Agenda"
1493 :group 'org)
1495 (defvar org-category nil
1496 "Variable used by org files to set a category for agenda display.
1497 Such files should use a file variable to set it, for example
1499 -*- mode: org; org-category: \"ELisp\"
1501 or contain a special line
1503 #+CATEGORY: ELisp
1505 If the file does not specify a category, then file's base name
1506 is used instead.")
1507 (make-variable-buffer-local 'org-category)
1509 (defcustom org-agenda-files nil
1510 "The files to be used for agenda display.
1511 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1512 \\[org-remove-file]. You can also use customize to edit the list.
1514 If the value of the variable is not a list but a single file name, then
1515 the list of agenda files is actually stored and maintained in that file, one
1516 agenda file per line."
1517 :group 'org-agenda
1518 :type '(choice
1519 (repeat :tag "List of files" file)
1520 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1522 (defcustom org-agenda-custom-commands ;'(("w" todo "WAITING"))
1523 '(("w" todo "WAITING" ((aaa 1) (bbb 2))))
1524 "Custom commands for the agenda.
1525 These commands will be offered on the splash screen displayed by the
1526 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1528 (key type match options)
1530 key The key (a single char as a string) to be associated with the command.
1531 type The command type, any of the following symbols:
1532 todo Entries with a specific TODO keyword, in all agenda files.
1533 tags Tags match in all agenda files.
1534 tags-todo Tags match in all agenda files, TODO entries only.
1535 todo-tree Sparse tree of specific TODO keyword in *current* file.
1536 tags-tree Sparse tree with all tags matches in *current* file.
1537 occur-tree Occur sparse tree for *current* file.
1538 match What to search for:
1539 - a single keyword for TODO keyword searches
1540 - a tags match expression for tags searches
1541 - a regular expression for occur searches
1542 options A list of option setttings, similar to that in a let form, so like
1543 this: ((opt1 val1) (opt2 val2) ...)
1545 You can also define a set of commands, to create a composite agenda buffer.
1546 In this case, an entry looks like this:
1548 (key desc (cmd1 cmd2 ...) general-options)
1550 where
1552 desc A description string to be displayed in the dispatcher menu.
1553 cmd An agenda command, similar to the above. However, tree commands
1554 are no allowed, but instead you can get agenda and global todo list.
1555 So valid commands for a set are:
1556 (agenda)
1557 (alltodo)
1558 (todo \"match\" options)
1559 (tags \"match\" options )
1560 (tags-todo \"match\" options)
1562 Each command can carry a list of options, and another set of options can be
1563 given for the whole set of commands. Individual command options take
1564 precedence over the general options."
1565 :group 'org-agenda
1566 :type '(repeat
1567 (choice
1568 (list :tag "Single command"
1569 (string :tag "Key")
1570 (choice
1571 (const :tag "Tags search (all agenda files)" tags)
1572 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1573 (const :tag "TODO keyword search (all agenda files)" todo)
1574 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1575 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1576 (const :tag "Occur tree (current buffer)" occur-tree))
1577 (string :tag "Match")
1578 (repeat :tag "Local options"
1579 (list (variable :tag "Option") (sexp :tag "Value"))))
1580 (list :tag "Command series, all agenda files"
1581 (string :tag "Key")
1582 (string :tag "Description")
1583 (repeat
1584 (choice
1585 (const :tag "Agenda" (agenda))
1586 (const :tag "TODO list" (alltodo))
1587 (list :tag "Tags search"
1588 (const :format "" tags)
1589 (string :tag "Match")
1590 (repeat :tag "Local options"
1591 (list (variable :tag "Option")
1592 (sexp :tag "Value"))))
1594 (list :tag "Tags search, TODO entries only"
1595 (const :format "" tags-todo)
1596 (string :tag "Match")
1597 (repeat :tag "Local options"
1598 (list (variable :tag "Option")
1599 (sexp :tag "Value"))))
1601 (list :tag "TODO keyword search"
1602 (const :format "" todo)
1603 (string :tag "Match")
1604 (repeat :tag "Local options"
1605 (list (variable :tag "Option")
1606 (sexp :tag "Value"))))))
1607 (repeat :tag "General options"
1608 (list (variable :tag "Option")
1609 (sexp :tag "Value")))))))
1611 (defcustom org-agenda-todo-list-sublevels t
1612 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1613 When nil, the sublevels of a TODO entry are not checked, resulting in
1614 potentially much shorter TODO lists."
1615 :group 'org-agenda
1616 :group 'org-todo
1617 :type 'boolean)
1619 (defcustom org-agenda-todo-ignore-scheduled nil
1620 "Non-nil means, don't show scheduled entries in the global todo list.
1621 The idea behind this is that by scheduling it, you have already taken care
1622 of this item."
1623 :group 'org-agenda
1624 :group 'org-todo
1625 :type 'boolean)
1627 (defcustom org-agenda-todo-ignore-deadlines nil
1628 "Non-nil means, don't show near deadline entries in the global todo list.
1629 Near means closer than `org-deadline-warning-days' days.
1630 The idea behind this is that such items will appear in the agenda anyway."
1631 :group 'org-agenda
1632 :group 'org-todo
1633 :type 'boolean)
1636 (defcustom org-timeline-show-empty-dates 3
1637 "Non-nil means, `org-timeline' also shows dates without an entry.
1638 When nil, only the days which actually have entries are shown.
1639 When t, all days between the first and the last date are shown.
1640 When an integer, show also empty dates, but if there is a gap of more than
1641 N days, just insert a special line indicating the size of the gap."
1642 :group 'org-agenda
1643 :type '(choice
1644 (const :tag "None" nil)
1645 (const :tag "All" t)
1646 (number :tag "at most")))
1648 (defcustom org-agenda-confirm-kill 1
1649 "When set, remote killing from the agenda buffer needs confirmation.
1650 When t, a confirmation is always needed. When a number N, confirmation is
1651 only needed when the text to be killed contains more than N non-white lines."
1652 :group 'org-agenda ;; FIXME
1653 :type '(choice
1654 (const :tag "Never" nil)
1655 (const :tag "Always" t)
1656 (number :tag "When more than N lines")))
1658 ;; FIXME: This variable could be removed
1659 (defcustom org-agenda-include-all-todo nil
1660 "Set means weekly/daily agenda will always contain all TODO entries.
1661 The TODO entries will be listed at the top of the agenda, before
1662 the entries for specific days."
1663 :group 'org-agenda
1664 :type 'boolean)
1666 (defcustom org-agenda-include-diary nil
1667 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1668 :group 'org-agenda
1669 :type 'boolean)
1671 (defcustom org-calendar-to-agenda-key [?c]
1672 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1673 The command `org-calendar-goto-agenda' will be bound to this key. The
1674 default is the character `c' because then `c' can be used to switch back and
1675 forth between agenda and calendar."
1676 :group 'org-agenda
1677 :type 'sexp)
1679 (defgroup org-agenda-setup nil
1680 "Options concerning setting up the Agenda window in Org Mode."
1681 :tag "Org Agenda Window Setup"
1682 :group 'org-agenda)
1684 (defcustom org-agenda-window-setup 'reorganize-frame
1685 "How the agenda buffer should be displayed.
1686 Possible values for this option are:
1688 current-window Show agenda in the current window, keeping all other windows.
1689 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1690 other-window Use `switch-to-buffer-other-window' to display agenda.
1691 reorganize-frame Show only two windows on the current frame, the current
1692 window and the agenda. Also, if the option
1693 `org-fit-agenda-window' is set, resize the agenda window to
1694 try to show as much as possible of the buffer content.
1695 See also the variable `org-agenda-restore-windows-after-quit'."
1696 :group 'org-agenda-setup
1697 :type '(choice
1698 (const current-window)
1699 (const other-frame)
1700 (const other-window)
1701 (const reorganize-frame)))
1703 (defcustom org-agenda-restore-windows-after-quit nil
1704 "Non-nil means, restore window configuration open exiting agenda.
1705 Before the window configuration is changed for displaying the agenda,
1706 the current status is recorded. When the agenda is exited with
1707 `q' or `x' and this option is set, the old state is restored. If
1708 `org-agenda-window-setup' is `other-frame', the value of this
1709 option will be ignored.."
1710 :group 'org-agenda-setup
1711 :type 'boolean)
1713 ;; FIXME: I think this variable could be removed.
1714 (defcustom org-select-agenda-window t
1715 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1716 When nil, cursor will remain in the current window."
1717 :group 'org-agenda-setup
1718 :type 'boolean)
1720 ;; FIXME: I think this variable could be removed.
1721 (defcustom org-fit-agenda-window t
1722 "Non-nil means, change window size of agenda to fit content.
1723 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1724 :group 'org-agenda-setup
1725 :type 'boolean)
1727 (defcustom org-finalize-agenda-hook nil
1728 "Hook run just before displaying an agenda buffer."
1729 :group 'org-agenda-setup
1730 :type 'hook)
1732 (defcustom org-agenda-mouse-1-follows-link nil
1733 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1734 A longer mouse click will still set point. Does not wortk on XEmacs.
1735 Needs to be set before org.el is loaded."
1736 :group 'org-agenda-setup
1737 :type 'boolean)
1739 (defcustom org-agenda-start-with-follow-mode nil
1740 "The initial value of follwo-mode in a newly created agenda window."
1741 :group 'org-agenda-setup
1742 :type 'boolean)
1744 (defgroup org-agenda-display nil
1745 "Options concerning what to display initially in Agenda."
1746 :tag "Org Agenda Display"
1747 :group 'org-agenda)
1749 (defcustom org-agenda-show-all-dates t
1750 "Non-nil means, `org-agenda' shows every day in the selected range.
1751 When nil, only the days which actually have entries are shown."
1752 :group 'org-agenda-display
1753 :type 'boolean)
1755 (defcustom org-agenda-start-on-weekday 1
1756 "Non-nil means, start the overview always on the specified weekday.
1757 0 denotes Sunday, 1 denotes Monday etc.
1758 When nil, always start on the current day."
1759 :group 'org-agenda-display
1760 :type '(choice (const :tag "Today" nil)
1761 (number :tag "Weekday No.")))
1763 (defcustom org-agenda-ndays 7
1764 "Number of days to include in overview display.
1765 Should be 1 or 7."
1766 :group 'org-agenda-display
1767 :type 'number)
1769 (defcustom org-agenda-use-time-grid t
1770 "Non-nil means, show a time grid in the agenda schedule.
1771 A time grid is a set of lines for specific times (like every two hours between
1772 8:00 and 20:00). The items scheduled for a day at specific times are
1773 sorted in between these lines.
1774 For details about when the grid will be shown, and what it will look like, see
1775 the variable `org-agenda-time-grid'."
1776 :group 'org-agenda-display
1777 :type 'boolean)
1779 (defcustom org-agenda-time-grid
1780 '((daily today require-timed)
1781 "----------------"
1782 (800 1000 1200 1400 1600 1800 2000))
1784 "The settings for time grid for agenda display.
1785 This is a list of three items. The first item is again a list. It contains
1786 symbols specifying conditions when the grid should be displayed:
1788 daily if the agenda shows a single day
1789 weekly if the agenda shows an entire week
1790 today show grid on current date, independent of daily/weekly display
1791 require-timed show grid only if at least one item has a time specification
1793 The second item is a string which will be places behing the grid time.
1795 The third item is a list of integers, indicating the times that should have
1796 a grid line."
1797 :group 'org-agenda-display
1798 :type
1799 '(list
1800 (set :greedy t :tag "Grid Display Options"
1801 (const :tag "Show grid in single day agenda display" daily)
1802 (const :tag "Show grid in weekly agenda display" weekly)
1803 (const :tag "Always show grid for today" today)
1804 (const :tag "Show grid only if any timed entries are present"
1805 require-timed)
1806 (const :tag "Skip grid times already present in an entry"
1807 remove-match))
1808 (string :tag "Grid String")
1809 (repeat :tag "Grid Times" (integer :tag "Time"))))
1811 (let ((sorting-choice
1812 '(choice
1813 (const time-up) (const time-down)
1814 (const category-keep) (const category-up) (const category-down)
1815 (const tag-down) (const tag-up)
1816 (const priority-up) (const priority-down))))
1818 (defcustom org-agenda-sorting-strategy
1819 '((agenda time-up category-keep priority-down)
1820 (todo category-keep priority-down)
1821 (tags category-keep))
1822 "Sorting structure for the agenda items of a single day.
1823 This is a list of symbols which will be used in sequence to determine
1824 if an entry should be listed before another entry. The following
1825 symbols are recognized:
1827 time-up Put entries with time-of-day indications first, early first
1828 time-down Put entries with time-of-day indications first, late first
1829 category-keep Keep the default order of categories, corresponding to the
1830 sequence in `org-agenda-files'.
1831 category-up Sort alphabetically by category, A-Z.
1832 category-down Sort alphabetically by category, Z-A.
1833 tag-up Sort alphabetically by last tag, A-Z.
1834 tag-down Sort alphabetically by last tag, Z-A.
1835 priority-up Sort numerically by priority, high priority last.
1836 priority-down Sort numerically by priority, high priority first.
1838 The different possibilities will be tried in sequence, and testing stops
1839 if one comparison returns a \"not-equal\". For example, the default
1840 '(time-up category-keep priority-down)
1841 means: Pull out all entries having a specified time of day and sort them,
1842 in order to make a time schedule for the current day the first thing in the
1843 agenda listing for the day. Of the entries without a time indication, keep
1844 the grouped in categories, don't sort the categories, but keep them in
1845 the sequence given in `org-agenda-files'. Within each category sort by
1846 priority.
1848 Leaving out `category-keep' would mean that items will be sorted across
1849 categories by priority."
1850 :group 'org-agenda-display
1851 :type `(choice
1852 (repeat :tag "General" ,sorting-choice)
1853 (list :tag "Individually"
1854 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1855 (repeat ,sorting-choice))
1856 (cons (const :tag "Strategy for TODO lists" todo)
1857 (repeat ,sorting-choice))
1858 (cons (const :tag "Strategy for Tags matches" tags)
1859 (repeat ,sorting-choice))))))
1861 (defcustom org-sort-agenda-notime-is-late t
1862 "Non-nil means, items without time are considered late.
1863 This is only relevant for sorting. When t, items which have no explicit
1864 time like 15:30 will be considered as 99:01, i.e. later than any items which
1865 do have a time. When nil, the default time is before 0:00. You can use this
1866 option to decide if the schedule for today should come before or after timeless
1867 agenda entries."
1868 :group 'org-agenda-display
1869 :type 'boolean)
1871 (defgroup org-agenda-prefix nil
1872 "Options concerning the entry prefix in the Org-mode agenda display."
1873 :tag "Org Agenda Prefix"
1874 :group 'org-agenda)
1876 (defcustom org-agenda-prefix-format
1877 '((agenda . " %-12:c%?-12t% s")
1878 (timeline . " % s")
1879 (todo . " %-12:c")
1880 (tags . " %-12:c"))
1881 "Format specifications for the prefix of items in the agenda views.
1882 An alist with four entries, for the different agenda types. The keys to the
1883 sublists are `agenda', `timeline', `todo', and `tags'. The values
1884 are format strings.
1885 This format works similar to a printf format, with the following meaning:
1887 %c the category of the item, \"Diary\" for entries from the diary, or
1888 as given by the CATEGORY keyword or derived from the file name.
1889 %T the *last* tag of the item. Last because inherited tags come
1890 first in the list.
1891 %t the time-of-day specification if one applies to the entry, in the
1892 format HH:MM
1893 %s Scheduling/Deadline information, a short string
1895 All specifiers work basically like the standard `%s' of printf, but may
1896 contain two additional characters: A question mark just after the `%' and
1897 a whitespace/punctuation character just before the final letter.
1899 If the first character after `%' is a question mark, the entire field
1900 will only be included if the corresponding value applies to the
1901 current entry. This is useful for fields which should have fixed
1902 width when present, but zero width when absent. For example,
1903 \"%?-12t\" will result in a 12 character time field if a time of the
1904 day is specified, but will completely disappear in entries which do
1905 not contain a time.
1907 If there is punctuation or whitespace character just before the final
1908 format letter, this character will be appended to the field value if
1909 the value is not empty. For example, the format \"%-12:c\" leads to
1910 \"Diary: \" if the category is \"Diary\". If the category were be
1911 empty, no additional colon would be interted.
1913 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1914 - Indent the line with two space characters
1915 - Give the category in a 12 chars wide field, padded with whitespace on
1916 the right (because of `-'). Append a colon if there is a category
1917 (because of `:').
1918 - If there is a time-of-day, put it into a 12 chars wide field. If no
1919 time, don't put in an empty field, just skip it (because of '?').
1920 - Finally, put the scheduling information and append a whitespace.
1922 As another example, if you don't want the time-of-day of entries in
1923 the prefix, you could use:
1925 (setq org-agenda-prefix-format \" %-11:c% s\")
1927 See also the variables `org-agenda-remove-times-when-in-prefix' and
1928 `org-agenda-remove-tags-when-in-prefix'."
1929 :type '(choice
1930 (string :tag "General format")
1931 (list :greedy t :tag "View dependent"
1932 (cons (const agenda) (string :tag "Format"))
1933 (cons (const timeline) (string :tag "Format"))
1934 (cons (const todo) (string :tag "Format"))
1935 (cons (const tags) (string :tag "Format"))))
1936 :group 'org-agenda-prefix)
1938 (defvar org-prefix-format-compiled nil
1939 "The compiled version of the most recently used prefix format.
1940 See the variable `org-agenda-prefix-format'.")
1942 (defcustom org-agenda-remove-times-when-in-prefix t
1943 "Non-nil means, remove duplicate time specifications in agenda items.
1944 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1945 time-of-day specification in a headline or diary entry is extracted and
1946 placed into the prefix. If this option is non-nil, the original specification
1947 \(a timestamp or -range, or just a plain time(range) specification like
1948 11:30-4pm) will be removed for agenda display. This makes the agenda less
1949 cluttered.
1950 The option can be t or nil. It may also be the symbol `beg', indicating
1951 that the time should only be removed what it is located at the beginning of
1952 the headline/diary entry."
1953 :group 'org-agenda-prefix
1954 :type '(choice
1955 (const :tag "Always" t)
1956 (const :tag "Never" nil)
1957 (const :tag "When at beginning of entry" beg)))
1959 (defcustom org-agenda-remove-tags-when-in-prefix nil
1960 "Non-nil means, remove the tags from the headline copy in the agenda.
1961 When this is the symbol `prefix', only remove tags when
1962 `org-agenda-prefix-format' contains a `%T' specifier."
1963 :group 'org-agenda-prefix
1964 :type '(choice
1965 (const :tag "Always" t)
1966 (const :tag "Never" nil)
1967 (const :tag "When prefix format contains %T" prefix)))
1969 (defcustom org-agenda-align-tags-to-column 65
1970 "Shift tags in agenda items to this column."
1971 :group 'org-agenda-prefix
1972 :type 'integer)
1974 (defgroup org-latex nil
1975 "Options for embedding LaTeX code into Org-mode"
1976 :tag "Org LaTeX"
1977 :group 'org)
1979 (defcustom org-format-latex-options
1980 '(:foreground "Black" :background "Transparent" :scale 1.0
1981 :matchers ("begin" "$" "$$" "\\(" "\\["))
1982 "Options for creating images from LaTeX fragments.
1983 This is a property list with the following properties:
1984 :foreground the foreground color, for example \"Black\".
1985 :background the background color, or \"Transparent\".
1986 :scale a scaling factor for the size of the images
1987 :matchers a list indicating which matchers should be used to
1988 find LaTeX fragments. Valid members of this list are:
1989 \"begin\" find environments
1990 \"$\" find math expressions surrounded by $...$
1991 \"$$\" find math expressions surrounded by $$....$$
1992 \"\\(\" find math expressions surrounded by \\(...\\)
1993 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1994 :group 'org-latex
1995 :type 'plist)
1997 (defgroup org-export nil
1998 "Options for exporting org-listings."
1999 :tag "Org Export"
2000 :group 'org)
2002 (defgroup org-export-general nil
2003 "General options for exporting Org-mode files."
2004 :tag "Org Export General"
2005 :group 'org-export)
2007 (defcustom org-export-publishing-directory "."
2008 "Path to the location where exported files should be located.
2009 This path may be relative to the directory where the Org-mode file lives.
2010 The default is to put them into the same directory as the Org-mode file.
2011 The variable may also be an alist with export types `:html', `:ascii',
2012 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2013 is relative, it is interpreted relative to the directory where the exported
2014 Org-mode files lives."
2015 :group 'org-export-general
2016 :type '(choice
2017 (directory)
2018 (repeat
2019 (cons
2020 (choice :tag "Type"
2021 (const :html) (const :ascii) (const :ical) (const :xoxo))
2022 (directory)))))
2024 (defcustom org-export-language-setup
2025 '(("en" "Author" "Date" "Table of Contents")
2026 ("cs" "Autor" "Datum" "Obsah")
2027 ("da" "Ophavsmand" "Dato" "Indhold")
2028 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2029 ("es" "Autor" "Fecha" "\xccndice")
2030 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2031 ("it" "Autore" "Data" "Indice")
2032 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2033 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2034 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2035 "Terms used in export text, translated to different languages.
2036 Use the variable `org-export-default-language' to set the language,
2037 or use the +OPTION lines for a per-file setting."
2038 :group 'org-export-general
2039 :type '(repeat
2040 (list
2041 (string :tag "HTML language tag")
2042 (string :tag "Author")
2043 (string :tag "Date")
2044 (string :tag "Table of Contents"))))
2046 (defcustom org-export-default-language "en"
2047 "The default language of HTML export, as a string.
2048 This should have an association in `org-export-language-setup'."
2049 :group 'org-export-general
2050 :type 'string)
2052 (defcustom org-export-headline-levels 3
2053 "The last level which is still exported as a headline.
2054 Inferior levels will produce itemize lists when exported.
2055 Note that a numeric prefix argument to an exporter function overrides
2056 this setting.
2058 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2059 :group 'org-export-general
2060 :type 'number)
2062 (defcustom org-export-with-section-numbers t
2063 "Non-nil means, add section numbers to headlines when exporting.
2065 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2066 :group 'org-export-general
2067 :type 'boolean)
2069 (defcustom org-export-with-toc t
2070 "Non-nil means, create a table of contents in exported files.
2071 The TOC contains headlines with levels up to`org-export-headline-levels'.
2073 Headlines which contain any TODO items will be marked with \"(*)\" in
2074 ASCII export, and with red color in HTML output.
2076 In HTML output, the TOC will be clickable.
2078 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2079 :group 'org-export-general
2080 :type 'boolean)
2082 (defcustom org-export-mark-todo-in-toc nil
2083 "Non-nil means, mark TOC lines that contain any open TODO items."
2084 :group 'org-export-general
2085 :type 'boolean)
2087 (defcustom org-export-preserve-breaks nil
2088 "Non-nil means, preserve all line breaks when exporting.
2089 Normally, in HTML output paragraphs will be reformatted. In ASCII
2090 export, line breaks will always be preserved, regardless of this variable.
2092 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2093 :group 'org-export-general
2094 :type 'boolean)
2096 (defcustom org-export-with-archived-trees 'headline
2097 "Whether subtrees with the ARCHIVE tag should be exported.
2098 This can have three different values
2099 nil Do not export, pretend this tree is not present
2100 t Do export the entire tree
2101 headline Only export the headline, but skip the tree below it."
2102 :group 'org-export-general
2103 :group 'org-archive
2104 :type '(choice
2105 (const :tag "not at all" nil)
2106 (const :tag "headline only" 'headline)
2107 (const :tag "entirely" t)))
2109 (defcustom org-export-with-timestamps t
2110 "If nil, do not export time stamps and associated keywords."
2111 :group 'org-export-general
2112 :type 'boolean)
2114 (defcustom org-export-remove-timestamps-from-toc t
2115 "If nil, remove timestamps from the table of contents entries."
2116 :group 'org-export-general
2117 :type 'boolean)
2119 (defcustom org-export-with-tags 'not-in-toc
2120 "If nil, do not export tags, just remove them from headlines.
2121 If this is the symbol `not-in-toc', tags will be removed from table of
2122 contents entries, but still be shown in the headlines of the document."
2123 :group 'org-export-general
2124 :type '(choice
2125 (const :tag "Off" nil)
2126 (const :tag "Not in TOC" not-in-toc)
2127 (const :tag "On" t)))
2129 (defgroup org-export-translation nil
2130 "Options for translating special ascii sequences for the export backends."
2131 :tag "Org Export Translation"
2132 :group 'org-export)
2134 (defcustom org-export-with-emphasize t
2135 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2136 If the export target supports emphasizing text, the word will be
2137 typeset in bold, italic, or underlined, respectively. Works only for
2138 single words, but you can say: I *really* *mean* *this*.
2139 Not all export backends support this.
2141 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2142 :group 'org-export-translation
2143 :type 'boolean)
2145 (defcustom org-export-with-sub-superscripts t
2146 "Non-nil means, interpret \"_\" and \"^\" for export.
2147 When this option is turned on, you can use TeX-like syntax for sub- and
2148 superscripts. Several characters after \"_\" or \"^\" will be
2149 considered as a single item - so grouping with {} is normally not
2150 needed. For example, the following things will be parsed as single
2151 sub- or superscripts.
2153 10^24 or 10^tau several digits will be considered 1 item.
2154 10^-12 or 10^-tau a leading sign with digits or a word
2155 x^2-y^3 will be read as x^2 - y^3, because items are
2156 terminated by almost any nonword/nondigit char.
2157 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2159 Still, ambiguity is possible - so when in doubt use {} to enclose the
2160 sub/superscript.
2161 Not all export backends support this, but HTML does.
2163 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2164 :group 'org-export-translation
2165 :type 'boolean)
2167 (defcustom org-export-with-TeX-macros t
2168 "Non-nil means, interpret simple TeX-like macros when exporting.
2169 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2170 No only real TeX macros will work here, but the standard HTML entities
2171 for math can be used as macro names as well. For a list of supported
2172 names in HTML export, see the constant `org-html-entities'.
2173 Not all export backends support this.
2175 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2176 :group 'org-export-translation
2177 :group 'org-latex
2178 :type 'boolean)
2180 (defcustom org-export-with-LaTeX-fragments nil
2181 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2182 When set, the exporter will find LaTeX environments if the \\begin line is
2183 the first non-white thing on a line. It will also find the math delimiters
2184 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2185 display math.
2187 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2188 :group 'org-export-translation
2189 :group 'org-latex
2190 :type 'boolean)
2192 (defcustom org-export-with-fixed-width t
2193 "Non-nil means, lines starting with \":\" will be in fixed width font.
2194 This can be used to have pre-formatted text, fragments of code etc. For
2195 example:
2196 : ;; Some Lisp examples
2197 : (while (defc cnt)
2198 : (ding))
2199 will be looking just like this in also HTML. See also the QUOTE keyword.
2200 Not all export backends support this.
2202 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2203 :group 'org-export-translation
2204 :type 'boolean)
2206 (defcustom org-match-sexp-depth 3
2207 "Number of stacked braces for sub/superscript matching.
2208 This has to be set before loading org.el to be effective."
2209 :group 'org-export-translation
2210 :type 'integer)
2212 (defgroup org-export-tables nil
2213 "Options for exporting tables in Org-mode."
2214 :tag "Org Export Tables"
2215 :group 'org-export)
2217 (defcustom org-export-with-tables t
2218 "If non-nil, lines starting with \"|\" define a table.
2219 For example:
2221 | Name | Address | Birthday |
2222 |-------------+----------+-----------|
2223 | Arthur Dent | England | 29.2.2100 |
2225 Not all export backends support this.
2227 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2228 :group 'org-export-tables
2229 :type 'boolean)
2231 (defcustom org-export-highlight-first-table-line t
2232 "Non-nil means, highlight the first table line.
2233 In HTML export, this means use <th> instead of <td>.
2234 In tables created with table.el, this applies to the first table line.
2235 In Org-mode tables, all lines before the first horizontal separator
2236 line will be formatted with <th> tags."
2237 :group 'org-export-tables
2238 :type 'boolean)
2240 (defcustom org-export-table-remove-special-lines t
2241 "Remove special lines and marking characters in calculating tables.
2242 This removes the special marking character column from tables that are set
2243 up for spreadsheet calculations. It also removes the entire lines
2244 marked with `!', `_', or `^'. The lines with `$' are kept, because
2245 the values of constants may be useful to have."
2246 :group 'org-export-tables
2247 :type 'boolean)
2249 (defcustom org-export-prefer-native-exporter-for-tables nil
2250 "Non-nil means, always export tables created with table.el natively.
2251 Natively means, use the HTML code generator in table.el.
2252 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2253 the table does not use row- or column-spanning). This has the
2254 advantage, that the automatic HTML conversions for math symbols and
2255 sub/superscripts can be applied. Org-mode's HTML generator is also
2256 much faster."
2257 :group 'org-export-tables
2258 :type 'boolean)
2260 (defgroup org-export-ascii nil
2261 "Options specific for ASCII export of Org-mode files."
2262 :tag "Org Export ASCII"
2263 :group 'org-export)
2265 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2266 "Characters for underlining headings in ASCII export.
2267 In the given sequence, these characters will be used for level 1, 2, ..."
2268 :group 'org-export-ascii
2269 :type '(repeat character))
2271 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2272 "Bullet characters for headlines converted to lists in ASCII export.
2273 The first character is is used for the first lest level generated in this
2274 way, and so on. If there are more levels than characters given here,
2275 the list will be repeated.
2276 Note that plain lists will keep the same bullets as the have in the
2277 Org-mode file."
2278 :group 'org-export-ascii
2279 :type '(repeat character))
2281 (defcustom org-export-ascii-show-new-buffer t
2282 "Non-nil means, popup buffer containing the exported ASCII text.
2283 Otherwise the buffer will just be saved to a file and stay hidden."
2284 :group 'org-export-ascii
2285 :type 'boolean)
2287 (defgroup org-export-xml nil
2288 "Options specific for XML export of Org-mode files."
2289 :tag "Org Export XML"
2290 :group 'org-export)
2292 (defgroup org-export-html nil
2293 "Options specific for HTML export of Org-mode files."
2294 :tag "Org Export HTML"
2295 :group 'org-export)
2297 (defcustom org-export-html-style
2298 "<style type=\"text/css\">
2299 html {
2300 font-family: Times, serif;
2301 font-size: 12pt;
2303 .title { text-align: center; }
2304 .todo { color: red; }
2305 .done { color: green; }
2306 .timestamp { color: grey }
2307 .timestamp-kwd { color: CadetBlue }
2308 .tag { background-color:lightblue; font-weight:normal }
2309 .target { background-color: lavender; }
2310 pre {
2311 border: 1pt solid #AEBDCC;
2312 background-color: #F3F5F7;
2313 padding: 5pt;
2314 font-family: courier, monospace;
2316 table { border-collapse: collapse; }
2317 td, th {
2318 vertical-align: top;
2319 border: 1pt solid #ADB9CC;
2321 </style>"
2322 "The default style specification for exported HTML files.
2323 Since there are different ways of setting style information, this variable
2324 needs to contain the full HTML structure to provide a style, including the
2325 surrounding HTML tags. The style specifications should include definitions
2326 for new classes todo, done, title, and deadline. For example, legal values
2327 would be:
2329 <style type=\"text/css\">
2330 p { font-weight: normal; color: gray; }
2331 h1 { color: black; }
2332 .title { text-align: center; }
2333 .todo, .deadline { color: red; }
2334 .done { color: green; }
2335 </style>
2337 or, if you want to keep the style in a file,
2339 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2341 As the value of this option simply gets inserted into the HTML <head> header,
2342 you can \"misuse\" it to add arbitrary text to the header."
2343 :group 'org-export-html
2344 :type 'string)
2346 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2347 "Format for typesetting the document title in HTML export."
2348 :group 'org-export-html
2349 :type 'string)
2351 (defcustom org-export-html-toplevel-hlevel 2
2352 "The <H> level for level 1 headings in HTML export."
2353 :group 'org-export-html
2354 :type 'string)
2356 (defcustom org-export-html-link-org-files-as-html t
2357 "Non-nil means, make file links to `file.org' point to `file.html'.
2358 When org-mode is exporting an org-mode file to HTML, links to
2359 non-html files are directly put into a href tag in HTML.
2360 However, links to other Org-mode files (recognized by the
2361 extension `.org.) should become links to the corresponding html
2362 file, assuming that the linked org-mode file will also be
2363 converted to HTML.
2364 When nil, the links still point to the plain `.org' file."
2365 :group 'org-export-html
2366 :type 'boolean)
2368 (defcustom org-export-html-inline-images 'maybe
2369 "Non-nil means, inline images into exported HTML pages.
2370 This is done using an <img> tag. When nil, an anchor with href is used to
2371 link to the image. If this option is `maybe', then images in links with
2372 an empty description will be inlined, while images with a description will
2373 be linked only."
2374 :group 'org-export-html
2375 :type '(choice (const :tag "Never" nil)
2376 (const :tag "Always" t)
2377 (const :tag "When there is no description" maybe)))
2379 (defcustom org-export-html-expand t
2380 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2381 When nil, these tags will be exported as plain text and therefore
2382 not be interpreted by a browser.
2384 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2385 :group 'org-export-html
2386 :type 'boolean)
2388 (defcustom org-export-html-table-tag
2389 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2390 "The HTML tag used to start a table.
2391 This must be a <table> tag, but you may change the options like
2392 borders and spacing."
2393 :group 'org-export-html
2394 :type 'string)
2396 (defcustom org-export-html-with-timestamp nil
2397 "If non-nil, write `org-export-html-html-helper-timestamp'
2398 into the exported HTML text. Otherwise, the buffer will just be saved
2399 to a file."
2400 :group 'org-export-html
2401 :type 'boolean)
2403 (defcustom org-export-html-html-helper-timestamp
2404 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2405 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2406 :group 'org-export-html
2407 :type 'string)
2409 (defcustom org-export-html-show-new-buffer nil
2410 "Non-nil means, popup buffer containing the exported html text.
2411 Otherwise, the buffer will just be saved to a file and stay hidden."
2412 :group 'org-export-html
2413 :type 'boolean)
2415 (defgroup org-export-icalendar nil
2416 "Options specific for iCalendar export of Org-mode files."
2417 :tag "Org Export iCalendar"
2418 :group 'org-export)
2420 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2421 "The file name for the iCalendar file covering all agenda files.
2422 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2423 The file name should be absolute."
2424 :group 'org-export-icalendar
2425 :type 'file)
2427 (defcustom org-icalendar-include-todo nil
2428 "Non-nil means, export to iCalendar files should also cover TODO items."
2429 :group 'org-export-icalendar
2430 :type 'boolean)
2432 (defcustom org-icalendar-combined-name "OrgMode"
2433 "Calendar name for the combined iCalendar representing all agenda files."
2434 :group 'org-export-icalendar
2435 :type 'string)
2437 (defgroup org-font-lock nil
2438 "Font-lock settings for highlighting in Org-mode."
2439 :tag "Org Font Lock"
2440 :group 'org)
2442 (defcustom org-level-color-stars-only nil
2443 "Non-nil means fontify only the stars in each headline.
2444 When nil, the entire headline is fontified.
2445 Changing it requires restart of `font-lock-mode' to become effective
2446 also in regions already fontified."
2447 :group 'org-font-lock
2448 :type 'boolean)
2450 (defcustom org-hide-leading-stars nil
2451 "Non-nil means, hide the first N-1 stars in a headline.
2452 This works by using the face `org-hide' for these stars. This
2453 face is white for a light background, and black for a dark
2454 background. You may have to customize the face `org-hide' to
2455 make this work.
2456 Changing it requires restart of `font-lock-mode' to become effective
2457 also in regions already fontified.
2458 You may also set this on a per-file basis by adding one of the following
2459 lines to the buffer:
2461 #+STARTUP: hidestars
2462 #+STARTUP: showstars"
2463 :group 'org-font-lock
2464 :type 'boolean)
2466 (defcustom org-fontify-done-headline nil
2467 "Non-nil means, change the face of a headline if it is marked DONE.
2468 Normally, only the TODO/DONE keyword indicates the state of a headline.
2469 When this is non-nil, the headline after the keyword is set to the
2470 `org-headline-done' as an additional indication."
2471 :group 'org-font-lock
2472 :type 'boolean)
2474 (defcustom org-fontify-emphasized-text t
2475 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2476 Changing this variable requires a restart of Emacs to take effect."
2477 :group 'org-font-lock
2478 :type 'boolean)
2480 (defvar org-emph-re nil
2481 "Regular expression for matching emphasis.")
2482 (defvar org-emphasis-regexp-components) ; defined just below
2483 (defvar org-emphasis-alist) ; defined just below
2484 (defun org-set-emph-re (var val)
2485 "Set variable and compute the emphasis regular expression."
2486 (set var val)
2487 (when (and (boundp 'org-emphasis-alist)
2488 (boundp 'org-emphasis-regexp-components)
2489 org-emphasis-alist org-emphasis-regexp-components)
2490 (let* ((e org-emphasis-regexp-components)
2491 (pre (car e))
2492 (post (nth 1 e))
2493 (border (nth 2 e))
2494 (body (nth 3 e))
2495 (nl (nth 4 e))
2496 (stacked (nth 5 e))
2497 (body1 (concat body "*?"))
2498 (markers (mapconcat 'car org-emphasis-alist "")))
2499 ;; make sure special characters appear at the right position in the class
2500 (if (string-match "\\^" markers)
2501 (setq markers (concat (replace-match "" t t markers) "^")))
2502 (if (string-match "-" markers)
2503 (setq markers (concat (replace-match "" t t markers) "-")))
2504 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2505 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2506 (if (> nl 0)
2507 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2508 (int-to-string nl) "\\}")))
2509 ;; Make the regexp
2510 (setq org-emph-re
2511 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2512 "\\("
2513 "\\([" markers "]\\)"
2514 "\\("
2515 "[^" border markers "]"
2516 body1
2517 "[^" border markers "]"
2518 "\\)"
2519 "\\3\\)"
2520 "\\([" post (if stacked markers) "]\\|$\\)")))))
2522 (defcustom org-emphasis-regexp-components
2523 '(" \t(" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2524 "Components used to build the reqular expression for emphasis.
2525 This is a list with 6 entries. Terminology: In an emphasis string
2526 like \" *strong word* \", we call the initial space PREMATCH, the final
2527 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2528 and \"trong wor\" is the body. The different components in this variable
2529 specify what is allowed/forbidden in each part:
2531 pre Chars allowed as prematch. Beginning of line will be allowed too.
2532 post Chars allowed as postmatch. End of line will be allowed too.
2533 border The chars *forbidden* as border characters. In addition to the
2534 characters given here, all marker characters are forbidden too.
2535 body-regexp A regexp like \".\" to match a body character. Don't use
2536 non-shy groups here, and don't allow newline here.
2537 newline The maximum number of newlines allowed in an emphasis exp.
2538 stacked Non-nil means, allow stacked styles. This works only in HTML
2539 export. When this is set, all marker characters (as given in
2540 `org-emphasis-alist') will be allowed as pre/post, aiding
2541 inside-out matching.
2542 Use customize to modify this, or restart Emacs after changing it."
2543 :group 'org-font-lock
2544 :set 'org-set-emph-re
2545 :type '(list
2546 (sexp :tag "Allowed chars in pre ")
2547 (sexp :tag "Allowed chars in post ")
2548 (sexp :tag "Forbidden chars in border ")
2549 (sexp :tag "Regexp for body ")
2550 (integer :tag "number of newlines allowed")
2551 (boolean :tag "Stacking allowed ")))
2553 (defcustom org-emphasis-alist
2554 '(("*" bold "<b>" "</b>")
2555 ("/" italic "<i>" "</i>")
2556 ("_" underline "<u>" "</u>")
2557 ("=" shadow "<code>" "</code>")
2558 ("+" (:strike-through t) "<del>" "</del>")
2560 "Special syntax for emphasized text.
2561 Text starting and ending with a special character will be emphasized, for
2562 example *bold*, _underlined_ and /italic/. This variable sets the marker
2563 characters, the face to bbe used by font-lock for highlighting in Org-mode
2564 Emacs buffers, and the HTML tags to be used for this.
2565 Use customize to modify this, or restart Emacs after changing it."
2566 :group 'org-font-lock
2567 :set 'org-set-emph-re
2568 :type '(repeat
2569 (list
2570 (string :tag "Marker character")
2571 (choice
2572 (face :tag "Font-lock-face")
2573 (plist :tag "Face property list"))
2574 (string :tag "HTML start tag")
2575 (string :tag "HTML end tag"))))
2577 (defgroup org-faces nil
2578 "Faces in Org-mode."
2579 :tag "Org Faces"
2580 :group 'org-font-lock)
2582 (defun org-compatible-face (specs)
2583 "Make a compatible face specification.
2584 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2585 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2586 to the top of the list. The `min-colors' attribute will be removed from
2587 any other entries, and any resulting duplicates will be removed entirely."
2588 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2589 (let (r e a)
2590 (while (setq e (pop specs))
2591 (cond
2592 ((memq (car e) '(t default)) (push e r))
2593 ((setq a (member '(min-colors 8) (car e)))
2594 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2595 (cdr e)))))
2596 ((setq a (assq 'min-colors (car e)))
2597 (setq e (cons (delq a (car e)) (cdr e)))
2598 (or (assoc (car e) r) (push e r)))
2599 (t (or (assoc (car e) r) (push e r)))))
2600 (nreverse r))
2601 specs))
2603 (defface org-hide
2604 '((((background light)) (:foreground "white"))
2605 (((background dark)) (:foreground "black")))
2606 "Face used to hide leading stars in headlines.
2607 The forground color of this face should be equal to the background
2608 color of the frame."
2609 :group 'org-faces)
2611 (defface org-level-1 ;; font-lock-function-name-face
2612 (org-compatible-face
2613 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2614 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2615 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2616 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2617 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2618 (t (:bold t))))
2619 "Face used for level 1 headlines."
2620 :group 'org-faces)
2622 (defface org-level-2 ;; font-lock-variable-name-face
2623 (org-compatible-face
2624 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2625 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2626 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2627 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2628 (t (:bold t))))
2629 "Face used for level 2 headlines."
2630 :group 'org-faces)
2632 (defface org-level-3 ;; font-lock-keyword-face
2633 (org-compatible-face
2634 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2635 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2636 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2637 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2638 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2639 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2640 (t (:bold t))))
2641 "Face used for level 3 headlines."
2642 :group 'org-faces)
2644 (defface org-level-4 ;; font-lock-comment-face
2645 (org-compatible-face
2646 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2647 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2648 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2649 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2650 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2651 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2652 (t (:bold t))))
2653 "Face used for level 4 headlines."
2654 :group 'org-faces)
2656 (defface org-level-5 ;; font-lock-type-face
2657 (org-compatible-face
2658 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2659 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2660 (((class color) (min-colors 8)) (:foreground "green"))))
2661 "Face used for level 5 headlines."
2662 :group 'org-faces)
2664 (defface org-level-6 ;; font-lock-constant-face
2665 (org-compatible-face
2666 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2667 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2668 (((class color) (min-colors 8)) (:foreground "magenta"))))
2669 "Face used for level 6 headlines."
2670 :group 'org-faces)
2672 (defface org-level-7 ;; font-lock-builtin-face
2673 (org-compatible-face
2674 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2675 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2676 (((class color) (min-colors 8)) (:foreground "blue"))))
2677 "Face used for level 7 headlines."
2678 :group 'org-faces)
2680 (defface org-level-8 ;; font-lock-string-face
2681 (org-compatible-face
2682 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2683 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2684 (((class color) (min-colors 8)) (:foreground "green"))))
2685 "Face used for level 8 headlines."
2686 :group 'org-faces)
2688 (defface org-special-keyword ;; font-lock-string-face
2689 (org-compatible-face
2690 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2691 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2692 (t (:italic t))))
2693 "Face used for special keywords."
2694 :group 'org-faces)
2696 (defface org-warning ;; font-lock-warning-face
2697 (org-compatible-face
2698 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2699 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2700 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2701 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2702 (t (:bold t))))
2703 "Face for deadlines and TODO keywords."
2704 :group 'org-faces)
2706 (defface org-headline-done ;; font-lock-string-face
2707 (org-compatible-face
2708 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2709 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2710 (((class color) (min-colors 8) (background light)) (:bold nil))))
2711 "Face used to indicate that a headline is DONE.
2712 This face is only used if `org-fontify-done-headline' is set."
2713 :group 'org-faces)
2715 (defface org-archived ; similar to shadow
2716 (org-compatible-face
2717 '((((class color grayscale) (min-colors 88) (background light))
2718 (:foreground "grey50"))
2719 (((class color grayscale) (min-colors 88) (background dark))
2720 (:foreground "grey70"))
2721 (((class color) (min-colors 8) (background light))
2722 (:foreground "green"))
2723 (((class color) (min-colors 8) (background dark))
2724 (:foreground "yellow"))))
2725 "Face for headline with the ARCHIVE tag."
2726 :group 'org-faces)
2728 (defface org-link
2729 '((((class color) (background light)) (:foreground "Purple" :underline t))
2730 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2731 (t (:underline t)))
2732 "Face for links."
2733 :group 'org-faces)
2735 (defface org-date
2736 '((((class color) (background light)) (:foreground "Purple" :underline t))
2737 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2738 (t (:underline t)))
2739 "Face for links."
2740 :group 'org-faces)
2742 (defface org-tag
2743 '((t (:bold t)))
2744 "Face for tags."
2745 :group 'org-faces)
2747 (defface org-todo ;; font-lock-warning-face
2748 (org-compatible-face
2749 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2750 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2751 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2752 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2753 (t (:inverse-video t :bold t))))
2754 "Face for TODO keywords."
2755 :group 'org-faces)
2757 (defface org-done ;; font-lock-type-face
2758 (org-compatible-face
2759 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2760 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2761 (((class color) (min-colors 8)) (:foreground "green"))
2762 (t (:bold t))))
2763 "Face used for DONE."
2764 :group 'org-faces)
2766 (defface org-table ;; font-lock-function-name-face
2767 (org-compatible-face
2768 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2769 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2770 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2771 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2772 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2773 (((class color) (min-colors 8) (background dark)))))
2774 "Face used for tables."
2775 :group 'org-faces)
2777 (defface org-formula
2778 (org-compatible-face
2779 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2780 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2781 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2782 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2783 (t (:bold t :italic t))))
2784 "Face for formulas."
2785 :group 'org-faces)
2787 (defface org-scheduled-today
2788 (org-compatible-face
2789 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2790 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2791 (((class color) (min-colors 8)) (:foreground "green"))
2792 (t (:bold t :italic t))))
2793 "Face for items scheduled for a certain day."
2794 :group 'org-faces)
2796 (defface org-scheduled-previously
2797 (org-compatible-face
2798 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2799 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2800 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2801 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2802 (t (:bold t))))
2803 "Face for items scheduled previously, and not yet done."
2804 :group 'org-faces)
2806 (defface org-upcoming-deadline
2807 (org-compatible-face
2808 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2809 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2810 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2811 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2812 (t (:bold t))))
2813 "Face for items scheduled previously, and not yet done."
2814 :group 'org-faces)
2816 (defface org-time-grid ;; font-lock-variable-name-face
2817 (org-compatible-face
2818 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2819 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2820 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2821 "Face used for time grids."
2822 :group 'org-faces)
2824 (defconst org-level-faces
2825 '(org-level-1 org-level-2 org-level-3 org-level-4
2826 org-level-5 org-level-6 org-level-7 org-level-8
2828 (defconst org-n-levels (length org-level-faces))
2831 ;; Variables for pre-computed regular expressions, all buffer local
2832 (defvar org-done-string nil
2833 "The last string in `org-todo-keywords', indicating an item is DONE.")
2834 (make-variable-buffer-local 'org-done-string)
2835 (defvar org-todo-regexp nil
2836 "Matches any of the TODO state keywords.")
2837 (make-variable-buffer-local 'org-todo-regexp)
2838 (defvar org-not-done-regexp nil
2839 "Matches any of the TODO state keywords except the last one.")
2840 (make-variable-buffer-local 'org-not-done-regexp)
2841 (defvar org-todo-line-regexp nil
2842 "Matches a headline and puts TODO state into group 2 if present.")
2843 (make-variable-buffer-local 'org-todo-line-regexp)
2844 (defvar org-todo-line-tags-regexp nil
2845 "Matches a headline and puts TODO state into group 2 if present.
2846 Also put tags into group 4 if tags are present.")
2847 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2848 (defvar org-nl-done-regexp nil
2849 "Matches newline followed by a headline with the DONE keyword.")
2850 (make-variable-buffer-local 'org-nl-done-regexp)
2851 (defvar org-looking-at-done-regexp nil
2852 "Matches the DONE keyword a point.")
2853 (make-variable-buffer-local 'org-looking-at-done-regexp)
2854 (defvar org-todo-kwd-priority-p nil
2855 "Do TODO items have priorities?")
2856 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2857 (defvar org-todo-kwd-max-priority nil
2858 "Maximum priority of TODO items.")
2859 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2860 (defvar org-ds-keyword-length 12
2861 "Maximum length of the Deadline and SCHEDULED keywords.")
2862 (make-variable-buffer-local 'org-ds-keyword-length)
2863 (defvar org-deadline-regexp nil
2864 "Matches the DEADLINE keyword.")
2865 (make-variable-buffer-local 'org-deadline-regexp)
2866 (defvar org-deadline-time-regexp nil
2867 "Matches the DEADLINE keyword together with a time stamp.")
2868 (make-variable-buffer-local 'org-deadline-time-regexp)
2869 (defvar org-deadline-line-regexp nil
2870 "Matches the DEADLINE keyword and the rest of the line.")
2871 (make-variable-buffer-local 'org-deadline-line-regexp)
2872 (defvar org-scheduled-regexp nil
2873 "Matches the SCHEDULED keyword.")
2874 (make-variable-buffer-local 'org-scheduled-regexp)
2875 (defvar org-scheduled-time-regexp nil
2876 "Matches the SCHEDULED keyword together with a time stamp.")
2877 (make-variable-buffer-local 'org-scheduled-time-regexp)
2878 (defvar org-closed-time-regexp nil
2879 "Matches the CLOSED keyword together with a time stamp.")
2880 (make-variable-buffer-local 'org-closed-time-regexp)
2882 (defvar org-keyword-time-regexp nil
2883 "Matches any of the 3 keywords, together with the time stamp.")
2884 (make-variable-buffer-local 'org-keyword-time-regexp)
2885 (defvar org-maybe-keyword-time-regexp nil
2886 "Matches a timestamp, possibly preceeded by a keyword.")
2887 (make-variable-buffer-local 'org-keyword-time-regexp)
2889 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2890 rear-nonsticky t mouse-map t)
2891 "Properties to remove when a string without properties is wanted.")
2893 (defsubst org-match-string-no-properties (num &optional string)
2894 (if (featurep 'xemacs)
2895 (let ((s (match-string num string)))
2896 (remove-text-properties 0 (length s) org-rm-props s)
2898 (match-string-no-properties num string)))
2900 (defsubst org-no-properties (s)
2901 (remove-text-properties 0 (length s) org-rm-props s)
2904 (defsubst org-get-alist-option (option key)
2905 (cond ((eq key t) t)
2906 ((eq option t) t)
2907 ((assoc key option) (cdr (assoc key option)))
2908 (t (cdr (assq 'default option)))))
2910 (defsubst org-set-local (var value)
2911 "Make VAR local in current buffer and set it to VALUE."
2912 (set (make-variable-buffer-local var) value))
2914 (defsubst org-mode-p ()
2915 "Check if the current buffer is in Org-mode."
2916 (eq major-mode 'org-mode))
2918 (defsubst org-last (list)
2919 "Return the last element of LIST."
2920 (car (last list)))
2922 (defun org-let (list &rest body)
2923 (eval (cons 'let (cons list body))))
2924 (put 'org-let 'lisp-indent-function 1)
2926 (defun org-let2 (list1 list2 &rest body)
2927 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
2928 (put 'org-let2 'lisp-indent-function 2)
2930 (defconst org-startup-options
2931 '(("fold" org-startup-folded t)
2932 ("overview" org-startup-folded t)
2933 ("nofold" org-startup-folded nil)
2934 ("showall" org-startup-folded nil)
2935 ("content" org-startup-folded content)
2936 ("hidestars" org-hide-leading-stars t)
2937 ("showstars" org-hide-leading-stars nil)
2938 ("odd" org-odd-levels-only t)
2939 ("oddeven" org-odd-levels-only nil)
2940 ("align" org-startup-align-all-tables t)
2941 ("noalign" org-startup-align-all-tables nil)
2942 ("customtime" org-display-custom-times t)
2943 ("logging" org-log-done t)
2944 ("nologging" org-log-done nil)
2945 ("dlcheck" org-startup-with-deadline-check t)
2946 ("nodlcheck" org-startup-with-deadline-check nil)))
2948 (defun org-set-regexps-and-options ()
2949 "Precompute regular expressions for current buffer."
2950 (when (org-mode-p)
2951 (let ((re (org-make-options-regexp
2952 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2953 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
2954 (splitre "[ \t]+")
2955 kwds int key value cat arch tags links)
2956 (save-excursion
2957 (save-restriction
2958 (widen)
2959 (goto-char (point-min))
2960 (while (re-search-forward re nil t)
2961 (setq key (match-string 1) value (org-match-string-no-properties 2))
2962 (cond
2963 ((equal key "CATEGORY")
2964 (if (string-match "[ \t]+$" value)
2965 (setq value (replace-match "" t t value)))
2966 (setq cat (intern value)))
2967 ((equal key "SEQ_TODO")
2968 (setq int 'sequence
2969 kwds (append kwds (org-split-string value splitre))))
2970 ((equal key "PRI_TODO")
2971 (setq int 'priority
2972 kwds (append kwds (org-split-string value splitre))))
2973 ((equal key "TYP_TODO")
2974 (setq int 'type
2975 kwds (append kwds (org-split-string value splitre))))
2976 ((equal key "TAGS")
2977 (setq tags (append tags (org-split-string value splitre))))
2978 ((equal key "LINK")
2979 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2980 (push (cons (match-string 1 value)
2981 (org-trim (match-string 2 value)))
2982 links)))
2983 ((equal key "STARTUP")
2984 (let ((opts (org-split-string value splitre))
2985 l var val)
2986 (while (setq l (assoc (pop opts) org-startup-options))
2987 (setq var (nth 1 l) val (nth 2 l))
2988 (set (make-local-variable var) val))))
2989 ((equal key "ARCHIVE")
2990 (string-match " *$" value)
2991 (setq arch (replace-match "" t t value))
2992 (remove-text-properties 0 (length arch)
2993 '(face t fontified t) arch)))
2995 (and cat (org-set-local 'org-category cat))
2996 (and kwds (org-set-local 'org-todo-keywords kwds))
2997 (and arch (org-set-local 'org-archive-location arch))
2998 (and int (org-set-local 'org-todo-interpretation int))
2999 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3000 (when tags
3001 (let (e tgs)
3002 (while (setq e (pop tags))
3003 (cond
3004 ((equal e "{") (push '(:startgroup) tgs))
3005 ((equal e "}") (push '(:endgroup) tgs))
3006 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3007 (push (cons (match-string 1 e)
3008 (string-to-char (match-string 2 e)))
3009 tgs))
3010 (t (push (list e) tgs))))
3011 (org-set-local 'org-tag-alist nil)
3012 (while (setq e (pop tgs))
3013 (or (and (stringp (car e))
3014 (assoc (car e) org-tag-alist))
3015 (push e org-tag-alist))))))
3017 ;; Compute the regular expressions and other local variables
3018 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3019 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3020 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3021 (length org-scheduled-string)))
3022 org-done-string
3023 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3024 org-todo-regexp
3025 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3026 "\\|") "\\)\\>")
3027 org-not-done-regexp
3028 (concat "\\<\\("
3029 (mapconcat 'regexp-quote
3030 (nreverse (cdr (reverse org-todo-keywords)))
3031 "\\|")
3032 "\\)\\>")
3033 org-todo-line-regexp
3034 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3035 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3036 "\\)\\>\\)? *\\(.*\\)")
3037 org-nl-done-regexp
3038 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3039 org-todo-line-tags-regexp
3040 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3041 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3042 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3043 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3044 org-deadline-regexp (concat "\\<" org-deadline-string)
3045 org-deadline-time-regexp
3046 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3047 org-deadline-line-regexp
3048 (concat "\\<\\(" org-deadline-string "\\).*")
3049 org-scheduled-regexp
3050 (concat "\\<" org-scheduled-string)
3051 org-scheduled-time-regexp
3052 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3053 org-closed-time-regexp
3054 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3055 org-keyword-time-regexp
3056 (concat "\\<\\(" org-scheduled-string
3057 "\\|" org-deadline-string
3058 "\\|" org-closed-string
3059 "\\|" org-clock-string "\\)"
3060 " *[[<]\\([^]>]+\\)[]>]")
3061 org-maybe-keyword-time-regexp
3062 (concat "\\(\\<\\(" org-scheduled-string
3063 "\\|" org-deadline-string
3064 "\\|" org-closed-string
3065 "\\|" org-clock-string "\\)\\)?"
3066 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3068 (org-set-font-lock-defaults)))
3070 ;; Tell the compiler about dynamically scoped variables,
3071 ;; and variables from other packages
3072 (defvar calc-embedded-close-formula) ; defined by the calc package
3073 (defvar calc-embedded-open-formula) ; defined by the calc package
3074 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
3075 (defvar zmacs-regions) ; XEmacs regions
3076 (defvar original-date) ; dynamically scoped in calendar
3077 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
3078 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3079 (defvar org-html-entities) ; defined later in this file
3080 (defvar org-goto-start-pos) ; dynamically scoped parameter
3081 (defvar org-time-was-given) ; dynamically scoped parameter
3082 (defvar org-ts-what) ; dynamically scoped parameter
3083 (defvar org-current-export-file) ; dynamically scoped parameter
3084 (defvar org-current-export-dir) ; dynamically scoped parameter
3085 (defvar mark-active) ; Emacs only, not available in XEmacs.
3086 (defvar timecnt) ; dynamically scoped parameter
3087 (defvar levels-open) ; dynamically scoped parameter
3088 (defvar entry) ; dynamically scoped parameter
3089 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
3090 (defvar date) ; dynamically scoped parameter
3091 (defvar description) ; dynamically scoped parameter
3092 (defvar ans1) ; dynamically scoped parameter
3093 (defvar ans2) ; dynamically scoped parameter
3094 (defvar starting-day) ; local variable
3095 (defvar include-all-loc) ; local variable
3096 (defvar vm-message-pointer) ; from vm
3097 (defvar vm-folder-directory) ; from vm
3098 (defvar gnus-other-frame-object) ; from gnus
3099 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
3100 (defvar wl-summary-buffer-folder-name) ; from wanderlust
3101 (defvar gnus-group-name) ; from gnus
3102 (defvar gnus-article-current) ; from gnus
3103 (defvar w3m-current-url) ; from w3m
3104 (defvar w3m-current-title) ; from w3m
3105 (defvar mh-progs) ; from MH-E
3106 (defvar mh-current-folder) ; from MH-E
3107 (defvar mh-show-folder-buffer) ; from MH-E
3108 (defvar mh-index-folder) ; from MH-E
3109 (defvar mh-searcher) ; from MH-E
3110 (defvar org-selected-point) ; dynamically scoped parameter
3111 (defvar calendar-mode-map) ; from calendar.el
3112 (defvar last-arg) ; local variable
3113 (defvar remember-save-after-remembering) ; from remember.el
3114 (defvar remember-data-file) ; from remember.el
3115 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3116 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3117 (defvar orgtbl-mode) ; defined later in this file
3118 (defvar Info-current-file) ; from info.el
3119 (defvar Info-current-node) ; from info.el
3120 (defvar texmathp-why) ; from texmathp.el
3121 (defvar org-latex-regexps)
3122 (defvar outline-mode-menu-heading)
3123 (defvar outline-mode-menu-show)
3124 (defvar outline-mode-menu-hide)
3126 ;;; Define the mode
3128 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3129 (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."))
3131 (defvar org-struct-menu) ; defined later in this file
3132 (defvar org-org-menu) ; defined later in this file
3133 (defvar org-tbl-menu) ; defined later in this file
3135 ;; We use a before-change function to check if a table might need
3136 ;; an update.
3137 (defvar org-table-may-need-update t
3138 "Indicates that a table might need an update.
3139 This variable is set by `org-before-change-function'.
3140 `org-table-align' sets it back to nil.")
3141 (defvar org-mode-map)
3142 (defvar org-mode-hook nil)
3143 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3144 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3147 ;;;###autoload
3148 (define-derived-mode org-mode outline-mode "Org"
3149 "Outline-based notes management and organizer, alias
3150 \"Carsten's outline-mode for keeping track of everything.\"
3152 Org-mode develops organizational tasks around a NOTES file which
3153 contains information about projects as plain text. Org-mode is
3154 implemented on top of outline-mode, which is ideal to keep the content
3155 of large files well structured. It supports ToDo items, deadlines and
3156 time stamps, which magically appear in the diary listing of the Emacs
3157 calendar. Tables are easily created with a built-in table editor.
3158 Plain text URL-like links connect to websites, emails (VM), Usenet
3159 messages (Gnus), BBDB entries, and any files related to the project.
3160 For printing and sharing of notes, an Org-mode file (or a part of it)
3161 can be exported as a structured ASCII or HTML file.
3163 The following commands are available:
3165 \\{org-mode-map}"
3167 ;; Get rid of Outline menus, they are not needed
3168 ;; Need to do this here because define-derived-mode sets up
3169 ;; the keymap so late. Still, it is a waste to call this each time
3170 ;; we switch another buffer into org-mode.
3171 (if (featurep 'xemacs)
3172 (when (boundp 'outline-mode-menu-heading)
3173 ;; Assume this is Greg's port, it used easymenu
3174 (easy-menu-remove outline-mode-menu-heading)
3175 (easy-menu-remove outline-mode-menu-show)
3176 (easy-menu-remove outline-mode-menu-hide))
3177 (define-key org-mode-map [menu-bar headings] 'undefined)
3178 (define-key org-mode-map [menu-bar hide] 'undefined)
3179 (define-key org-mode-map [menu-bar show] 'undefined))
3181 (easy-menu-add org-org-menu)
3182 (easy-menu-add org-tbl-menu)
3183 (org-install-agenda-files-menu)
3184 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3185 (org-add-to-invisibility-spec '(org-cwidth))
3186 (when (featurep 'xemacs)
3187 (org-set-local 'line-move-ignore-invisible t))
3188 (setq outline-regexp "\\*+")
3189 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3190 (setq outline-level 'org-outline-level)
3191 (when (and org-ellipsis (stringp org-ellipsis))
3192 (unless org-display-table
3193 (setq org-display-table (make-display-table)))
3194 (set-display-table-slot org-display-table
3195 4 (string-to-vector org-ellipsis))
3196 (setq buffer-display-table org-display-table))
3197 (org-set-regexps-and-options)
3198 ;; Calc embedded
3199 (org-set-local 'calc-embedded-open-mode "# ")
3200 (modify-syntax-entry ?# "<")
3201 (if org-startup-truncated (setq truncate-lines t))
3202 (org-set-local 'font-lock-unfontify-region-function
3203 'org-unfontify-region)
3204 ;; Activate before-change-function
3205 (org-set-local 'org-table-may-need-update t)
3206 (org-add-hook 'before-change-functions 'org-before-change-function nil
3207 'local)
3208 ;; Check for running clock before killing a buffer
3209 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3210 ;; Paragraphs and auto-filling
3211 (org-set-autofill-regexps)
3212 (org-update-radio-target-regexp)
3214 (if (and org-insert-mode-line-in-empty-file
3215 (interactive-p)
3216 (= (point-min) (point-max)))
3217 (insert " -*- mode: org -*-\n\n"))
3219 (unless org-inhibit-startup
3220 (when org-startup-align-all-tables
3221 (let ((bmp (buffer-modified-p)))
3222 (org-table-map-tables 'org-table-align)
3223 (set-buffer-modified-p bmp)))
3224 (if org-startup-with-deadline-check
3225 (call-interactively 'org-check-deadlines)
3226 (cond
3227 ((eq org-startup-folded t)
3228 (org-cycle '(4)))
3229 ((eq org-startup-folded 'content)
3230 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3231 (org-cycle '(4)) (org-cycle '(4))))))))
3233 (defsubst org-call-with-arg (command arg)
3234 "Call COMMAND interactively, but pretend prefix are was ARG."
3235 (let ((current-prefix-arg arg)) (call-interactively command)))
3237 (defsubst org-current-line (&optional pos)
3238 (save-excursion
3239 (and pos (goto-char pos))
3240 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
3242 (defun org-current-time ()
3243 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3244 (if (> org-time-stamp-rounding-minutes 0)
3245 (let ((r org-time-stamp-rounding-minutes)
3246 (time (decode-time)))
3247 (apply 'encode-time
3248 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3249 (nthcdr 2 time))))
3250 (current-time)))
3252 (defun org-add-props (string plist &rest props)
3253 "Add text properties to entire string, from beginning to end.
3254 PLIST may be a list of properties, PROPS are individual properties and values
3255 that will be added to PLIST. Returns the string that was modified."
3256 (add-text-properties
3257 0 (length string) (if props (append plist props) plist) string)
3258 string)
3259 (put 'org-add-props 'lisp-indent-function 2)
3262 ;;; Font-Lock stuff
3264 (defvar org-mouse-map (make-sparse-keymap))
3265 (define-key org-mouse-map
3266 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3267 (define-key org-mouse-map
3268 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3269 (when org-mouse-1-follows-link
3270 (define-key org-mouse-map [follow-link] 'mouse-face))
3271 (when org-tab-follows-link
3272 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3273 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3274 (when org-return-follows-link
3275 (define-key org-mouse-map [(return)] 'org-open-at-point)
3276 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3278 (require 'font-lock)
3280 (defconst org-non-link-chars "]\t\n\r<>")
3281 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3282 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3283 (defconst org-link-re-with-space
3284 (concat
3285 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3286 "\\([^" org-non-link-chars " ]"
3287 "[^" org-non-link-chars "]*"
3288 "[^" org-non-link-chars " ]\\)>?")
3289 "Matches a link with spaces, optional angular brackets around it.")
3291 (defconst org-link-re-with-space2
3292 (concat
3293 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3294 "\\([^" org-non-link-chars " ]"
3295 "[^]\t\n\r]*"
3296 "[^" org-non-link-chars " ]\\)>?")
3297 "Matches a link with spaces, optional angular brackets around it.")
3299 (defconst org-angle-link-re
3300 (concat
3301 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3302 "\\([^" org-non-link-chars " ]"
3303 "[^" org-non-link-chars "]*"
3304 "\\)>")
3305 "Matches link with angular brackets, spaces are allowed.")
3306 (defconst org-plain-link-re
3307 (concat
3308 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3309 "\\([^]\t\n\r<>,;() ]+\\)")
3310 "Matches plain link, without spaces.")
3312 (defconst org-bracket-link-regexp
3313 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3314 "Matches a link in double brackets.")
3316 (defconst org-bracket-link-analytic-regexp
3317 (concat
3318 "\\[\\["
3319 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3320 "\\([^]]+\\)"
3321 "\\]"
3322 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3323 "\\]"))
3324 ; 1: http:
3325 ; 2: http
3326 ; 3: path
3327 ; 4: [desc]
3328 ; 5: desc
3330 (defconst org-ts-lengths
3331 (cons (length (format-time-string (car org-time-stamp-formats)))
3332 (length (format-time-string (cdr org-time-stamp-formats))))
3333 "This holds the lengths of the two different time formats.")
3334 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3335 "Regular expression for fast time stamp matching.")
3336 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3337 "Regular expression for fast time stamp matching.")
3338 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3339 "Regular expression matching time strings for analysis.")
3340 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3341 "Regular expression matching time stamps, with groups.")
3342 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3343 "Regular expression matching time stamps (also [..]), with groups.")
3344 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3345 "Regular expression matching a time stamp range.")
3346 (defconst org-tr-regexp-both
3347 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3348 "Regular expression matching a time stamp range.")
3349 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3350 org-ts-regexp "\\)?")
3351 "Regular expression matching a time stamp or time stamp range.")
3352 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3353 org-ts-regexp-both "\\)?")
3354 "Regular expression matching a time stamp or time stamp range.
3355 The time stamps may be either active or inactive.")
3357 (defvar org-emph-face nil)
3359 (defun org-do-emphasis-faces (limit)
3360 "Run through the buffer and add overlays to links."
3361 (if (re-search-forward org-emph-re limit t)
3362 (progn
3363 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3364 'face
3365 (nth 1 (assoc (match-string 3)
3366 org-emphasis-alist)))
3367 (add-text-properties (match-beginning 2) (match-end 2)
3368 '(font-lock-multiline t))
3369 (backward-char 1)
3370 t)))
3372 (defun org-activate-plain-links (limit)
3373 "Run through the buffer and add overlays to links."
3374 (if (re-search-forward org-plain-link-re limit t)
3375 (progn
3376 (add-text-properties (match-beginning 0) (match-end 0)
3377 (list 'mouse-face 'highlight
3378 'rear-nonsticky t
3379 'keymap org-mouse-map
3381 t)))
3383 (defun org-activate-angle-links (limit)
3384 "Run through the buffer and add overlays to links."
3385 (if (re-search-forward org-angle-link-re limit t)
3386 (progn
3387 (add-text-properties (match-beginning 0) (match-end 0)
3388 (list 'mouse-face 'highlight
3389 'rear-nonsticky t
3390 'keymap org-mouse-map
3392 t)))
3394 (defmacro org-maybe-intangible (props)
3395 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3396 In emacs 21, invisible text is not avoided by the command loop, so the
3397 intangible property is needed to make sure point skips this text.
3398 In Emacs 22, this is not necessary. The intangible text property has
3399 led to problems with flyspell. These problems are fixed in flyspell.el,
3400 but we still avoid setting the property in Emacs 22 and later.
3401 We use a macro so that the test can happen at compilation time."
3402 (if (< emacs-major-version 22)
3403 `(append '(intangible t) ,props)
3404 props))
3406 (defun org-activate-bracket-links (limit)
3407 "Run through the buffer and add overlays to bracketed links."
3408 (if (re-search-forward org-bracket-link-regexp limit t)
3409 (let* ((help (concat "LINK: "
3410 (org-match-string-no-properties 1)))
3411 ;; FIXME: above we should remove the escapes.
3412 ;; but that requires another match, protecting match data,
3413 ;; a lot of overhead for font-lock.
3414 (ip (org-maybe-intangible
3415 (list 'invisible 'org-link 'rear-nonsticky t
3416 'keymap org-mouse-map 'mouse-face 'highlight
3417 'help-echo help)))
3418 (vp (list 'rear-nonsticky t
3419 'keymap org-mouse-map 'mouse-face 'highlight
3420 'help-echo help)))
3421 ;; We need to remove the invisible property here. Table narrowing
3422 ;; may have made some of this invisible.
3423 (remove-text-properties (match-beginning 0) (match-end 0)
3424 '(invisible nil))
3425 (if (match-end 3)
3426 (progn
3427 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3428 (add-text-properties (match-beginning 3) (match-end 3) vp)
3429 (add-text-properties (match-end 3) (match-end 0) ip))
3430 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3431 (add-text-properties (match-beginning 1) (match-end 1) vp)
3432 (add-text-properties (match-end 1) (match-end 0) ip))
3433 t)))
3435 (defun org-activate-dates (limit)
3436 "Run through the buffer and add overlays to dates."
3437 ; (if (re-search-forward org-tsr-regexp limit t)
3438 ; (if (re-search-forward
3439 ; (if org-display-custom-times org-ts-regexp-both org-tsr-regexp-both)
3440 ; limit t)
3441 (if (re-search-forward org-tsr-regexp-both limit t)
3442 (progn
3443 (add-text-properties (match-beginning 0) (match-end 0)
3444 (list 'mouse-face 'highlight
3445 'rear-nonsticky t
3446 'keymap org-mouse-map))
3447 (when org-display-custom-times
3448 (if (match-end 3)
3449 (org-display-custom-time (match-beginning 3) (match-end 3)))
3450 (org-display-custom-time (match-beginning 1) (match-end 1)))
3451 t)))
3453 (defvar org-target-link-regexp nil
3454 "Regular expression matching radio targets in plain text.")
3455 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3456 "Regular expression matching a link target.")
3457 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3458 "Regular expression matching a link target.")
3460 (defun org-activate-target-links (limit)
3461 "Run through the buffer and add overlays to target matches."
3462 (when org-target-link-regexp
3463 (let ((case-fold-search t))
3464 (if (re-search-forward org-target-link-regexp limit t)
3465 (progn
3466 (add-text-properties (match-beginning 0) (match-end 0)
3467 (list 'mouse-face 'highlight
3468 'rear-nonsticky t
3469 'keymap org-mouse-map
3470 'help-echo "Radio target link"
3471 'org-linked-text t))
3472 t)))))
3474 (defun org-update-radio-target-regexp ()
3475 "Find all radio targets in this file and update the regular expression."
3476 (interactive)
3477 (when (memq 'radio org-activate-links)
3478 (setq org-target-link-regexp
3479 (org-make-target-link-regexp (org-all-targets 'radio)))
3480 (org-restart-font-lock)))
3482 (defun org-hide-wide-columns (limit)
3483 (let (s e)
3484 (setq s (text-property-any (point) (or limit (point-max))
3485 'org-cwidth t))
3486 (when s
3487 (setq e (next-single-property-change s 'org-cwidth))
3488 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3489 (goto-char e)
3490 t)))
3492 (defun org-restart-font-lock ()
3493 "Restart font-lock-mode, to force refontification."
3494 (when (and (boundp 'font-lock-mode) font-lock-mode)
3495 (font-lock-mode -1)
3496 (font-lock-mode 1)))
3498 (defun org-all-targets (&optional radio)
3499 "Return a list of all targets in this file.
3500 With optional argument RADIO, only find radio targets."
3501 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3502 rtn)
3503 (save-excursion
3504 (goto-char (point-min))
3505 (while (re-search-forward re nil t)
3506 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3507 rtn)))
3509 (defun org-make-target-link-regexp (targets)
3510 "Make regular expression matching all strings in TARGETS.
3511 The regular expression finds the targets also if there is a line break
3512 between words."
3513 (and targets
3514 (concat
3515 "\\<\\("
3516 (mapconcat
3517 (lambda (x)
3518 (while (string-match " +" x)
3519 (setq x (replace-match "\\s-+" t t x)))
3521 targets
3522 "\\|")
3523 "\\)\\>")))
3525 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3526 "Matches CamelCase words, possibly with a star before it.")
3528 (defun org-activate-camels (limit)
3529 "Run through the buffer and add overlays to dates."
3530 (if (re-search-forward org-camel-regexp limit t)
3531 (progn
3532 (add-text-properties (match-beginning 0) (match-end 0)
3533 (list 'mouse-face 'highlight
3534 'rear-nonsticky t
3535 'keymap org-mouse-map))
3536 t)))
3538 (defun org-activate-tags (limit)
3539 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3540 (progn
3541 (add-text-properties (match-beginning 1) (match-end 1)
3542 (list 'mouse-face 'highlight
3543 'rear-nonsticky t
3544 'keymap org-mouse-map))
3545 t)))
3547 (defun org-font-lock-level ()
3548 (save-excursion
3549 (org-back-to-heading t)
3550 (- (match-end 0) (match-beginning 0))))
3552 (defun org-outline-level ()
3553 (save-excursion
3554 (looking-at outline-regexp)
3555 (if (match-beginning 1)
3556 (+ (org-get-string-indentation (match-string 1)) 1000)
3557 (- (match-end 0) (match-beginning 0)))))
3559 (defvar org-font-lock-keywords nil)
3561 (defun org-set-font-lock-defaults ()
3562 (let* ((em org-fontify-emphasized-text)
3563 (lk org-activate-links)
3564 (org-font-lock-extra-keywords
3565 ;; Headlines
3566 (list
3567 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3568 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3569 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3570 (1 'org-table))
3571 ;; Links
3572 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3573 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3574 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3575 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3576 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3577 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3578 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3579 (if org-table-limit-column-width
3580 '(org-hide-wide-columns (0 nil append)))
3581 ;; TODO lines
3582 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3583 '(1 'org-todo t))
3584 ;; Priorities
3585 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3586 ;; Special keywords
3587 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3588 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3589 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3590 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3591 ;; Emphasis
3592 (if em
3593 (if (featurep 'xemacs)
3594 '(org-do-emphasis-faces (0 nil append))
3595 '(org-do-emphasis-faces)))
3596 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3597 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3598 2 'bold prepend)
3599 (if org-provide-checkbox-statistics
3600 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3601 (0 (org-get-checkbox-statistics-face) t)))
3602 ;; COMMENT
3603 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3604 "\\|" org-quote-string "\\)\\>")
3605 '(1 'org-special-keyword t))
3606 '("^#.*" (0 'font-lock-comment-face t))
3607 ;; DONE
3608 (if org-fontify-done-headline
3609 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3610 '(1 'org-done t) '(2 'org-headline-done t))
3611 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3612 '(1 'org-done t)))
3613 ;; Table stuff
3614 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3615 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3616 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3617 (if org-format-transports-properties-p
3618 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3619 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3621 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3622 ;; Now set the full font-lock-keywords
3623 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3624 (org-set-local 'font-lock-defaults
3625 '(org-font-lock-keywords t nil nil backward-paragraph))
3626 (kill-local-variable 'font-lock-keywords) nil))
3628 (defvar org-m nil)
3629 (defvar org-l nil)
3630 (defvar org-f nil)
3631 (defun org-get-level-face (n)
3632 "Get the right face for match N in font-lock matching of healdines."
3633 (setq org-l (- (match-end 2) (match-beginning 1)))
3634 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3635 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3636 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3637 (cond
3638 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3639 ((eq n 2) org-f)
3640 (t (if org-level-color-stars-only nil org-f))))
3642 (defun org-unfontify-region (beg end &optional maybe_loudly)
3643 "Remove fontification and activation overlays from links."
3644 (font-lock-default-unfontify-region beg end)
3645 (let* ((buffer-undo-list t)
3646 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3647 (inhibit-modification-hooks t)
3648 deactivate-mark buffer-file-name buffer-file-truename)
3649 (remove-text-properties beg end
3650 '(mouse-face t keymap t org-linked-text t
3651 rear-nonsticky t
3652 invisible t intangible t))))
3654 ;;; Visibility cycling
3656 (defvar org-cycle-global-status nil)
3657 (make-variable-buffer-local 'org-cycle-global-status)
3658 (defvar org-cycle-subtree-status nil)
3659 (make-variable-buffer-local 'org-cycle-subtree-status)
3661 ;;;###autoload
3662 (defun org-cycle (&optional arg)
3663 "Visibility cycling for Org-mode.
3665 - When this function is called with a prefix argument, rotate the entire
3666 buffer through 3 states (global cycling)
3667 1. OVERVIEW: Show only top-level headlines.
3668 2. CONTENTS: Show all headlines of all levels, but no body text.
3669 3. SHOW ALL: Show everything.
3671 - When point is at the beginning of a headline, rotate the subtree started
3672 by this line through 3 different states (local cycling)
3673 1. FOLDED: Only the main headline is shown.
3674 2. CHILDREN: The main headline and the direct children are shown.
3675 From this state, you can move to one of the children
3676 and zoom in further.
3677 3. SUBTREE: Show the entire subtree, including body text.
3679 - When there is a numeric prefix, go up to a heading with level ARG, do
3680 a `show-subtree' and return to the previous cursor position. If ARG
3681 is negative, go up that many levels.
3683 - When point is not at the beginning of a headline, execute
3684 `indent-relative', like TAB normally does. See the option
3685 `org-cycle-emulate-tab' for details.
3687 - Special case: if point is the the beginning of the buffer and there is
3688 no headline in line 1, this function will act as if called with prefix arg."
3689 (interactive "P")
3690 (let* ((outline-regexp
3691 (if (and (org-mode-p) org-cycle-include-plain-lists)
3692 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3693 outline-regexp))
3694 (bob-special (and org-cycle-global-at-bob (bobp)
3695 (not (looking-at outline-regexp))))
3696 (org-cycle-hook
3697 (if bob-special
3698 (delq 'org-optimize-window-after-visibility-change
3699 (copy-sequence org-cycle-hook))
3700 org-cycle-hook))
3701 (pos (point)))
3703 (if (or bob-special (equal arg '(4)))
3704 ;; special case: use global cycling
3705 (setq arg t))
3707 (cond
3709 ((org-at-table-p 'any)
3710 ;; Enter the table or move to the next field in the table
3711 (or (org-table-recognize-table.el)
3712 (progn
3713 (if arg (org-table-edit-field t)
3714 (org-table-justify-field-maybe)
3715 (call-interactively 'org-table-next-field)))))
3717 ((eq arg t) ;; Global cycling
3719 (cond
3720 ((and (eq last-command this-command)
3721 (eq org-cycle-global-status 'overview))
3722 ;; We just created the overview - now do table of contents
3723 ;; This can be slow in very large buffers, so indicate action
3724 (message "CONTENTS...")
3725 (org-content)
3726 (message "CONTENTS...done")
3727 (setq org-cycle-global-status 'contents)
3728 (run-hook-with-args 'org-cycle-hook 'contents))
3730 ((and (eq last-command this-command)
3731 (eq org-cycle-global-status 'contents))
3732 ;; We just showed the table of contents - now show everything
3733 (show-all)
3734 (message "SHOW ALL")
3735 (setq org-cycle-global-status 'all)
3736 (run-hook-with-args 'org-cycle-hook 'all))
3739 ;; Default action: go to overview
3740 (org-overview)
3741 (message "OVERVIEW")
3742 (setq org-cycle-global-status 'overview)
3743 (run-hook-with-args 'org-cycle-hook 'overview))))
3745 ((integerp arg)
3746 ;; Show-subtree, ARG levels up from here.
3747 (save-excursion
3748 (org-back-to-heading)
3749 (outline-up-heading (if (< arg 0) (- arg)
3750 (- (funcall outline-level) arg)))
3751 (org-show-subtree)))
3753 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3754 ;; At a heading: rotate between three different views
3755 (org-back-to-heading)
3756 (let ((goal-column 0) eoh eol eos)
3757 ;; First, some boundaries
3758 (save-excursion
3759 (org-back-to-heading)
3760 (save-excursion
3761 (beginning-of-line 2)
3762 (while (and (not (eobp)) ;; this is like `next-line'
3763 (get-char-property (1- (point)) 'invisible))
3764 (beginning-of-line 2)) (setq eol (point)))
3765 (outline-end-of-heading) (setq eoh (point))
3766 (org-end-of-subtree t) (setq eos (point))
3767 (outline-next-heading))
3768 ;; Find out what to do next and set `this-command'
3769 (cond
3770 ((and (= eos eoh)
3771 ;; Nothing is hidden behind this heading
3772 (message "EMPTY ENTRY")
3773 (setq org-cycle-subtree-status nil)))
3774 ((>= eol eos)
3775 ;; Entire subtree is hidden in one line: open it
3776 (org-show-entry)
3777 (show-children)
3778 (message "CHILDREN")
3779 (setq org-cycle-subtree-status 'children)
3780 (run-hook-with-args 'org-cycle-hook 'children))
3781 ((and (eq last-command this-command)
3782 (eq org-cycle-subtree-status 'children))
3783 ;; We just showed the children, now show everything.
3784 (org-show-subtree)
3785 (message "SUBTREE")
3786 (setq org-cycle-subtree-status 'subtree)
3787 (run-hook-with-args 'org-cycle-hook 'subtree))
3789 ;; Default action: hide the subtree.
3790 (hide-subtree)
3791 (message "FOLDED")
3792 (setq org-cycle-subtree-status 'folded)
3793 (run-hook-with-args 'org-cycle-hook 'folded)))))
3795 ;; TAB emulation
3796 (buffer-read-only (org-back-to-heading))
3798 ((org-try-cdlatex-tab))
3800 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3801 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3802 (or (and (eq org-cycle-emulate-tab 'white)
3803 (= (match-end 0) (point-at-eol)))
3804 (and (eq org-cycle-emulate-tab 'whitestart)
3805 (>= (match-end 0) pos))))
3807 (eq org-cycle-emulate-tab t))
3808 (if (and (looking-at "[ \n\r\t]")
3809 (string-match "^[ \t]*$" (buffer-substring
3810 (point-at-bol) (point))))
3811 (progn
3812 (beginning-of-line 1)
3813 (and (looking-at "[ \t]+") (replace-match ""))))
3814 (indent-relative))
3816 (t (save-excursion
3817 (org-back-to-heading)
3818 (org-cycle))))))
3820 ;;;###autoload
3821 (defun org-global-cycle (&optional arg)
3822 "Cycle the global visibility. For details see `org-cycle'."
3823 (interactive "P")
3824 (let ((org-cycle-include-plain-lists
3825 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3826 (if (integerp arg)
3827 (progn
3828 (show-all)
3829 (hide-sublevels arg)
3830 (setq org-cycle-global-status 'contents))
3831 (org-cycle '(4)))))
3833 (defun org-overview ()
3834 "Switch to overview mode, shoing only top-level headlines.
3835 Really, this shows all headlines with level equal or greater than the level
3836 of the first headline in the buffer. This is important, because if the
3837 first headline is not level one, then (hide-sublevels 1) gives confusing
3838 results."
3839 (interactive)
3840 (hide-sublevels (save-excursion
3841 (goto-char (point-min))
3842 (if (re-search-forward (concat "^" outline-regexp) nil t)
3843 (progn
3844 (goto-char (match-beginning 0))
3845 (funcall outline-level))
3846 1))))
3848 ;; FIXME: allow an argument to give a limiting level for this.
3849 (defun org-content ()
3850 "Show all headlines in the buffer, like a table of contents"
3851 (interactive)
3852 (save-excursion
3853 ;; Visit all headings and show their offspring
3854 (goto-char (point-max))
3855 (catch 'exit
3856 (while (and (progn (condition-case nil
3857 (outline-previous-visible-heading 1)
3858 (error (goto-char (point-min))))
3860 (looking-at outline-regexp))
3861 (show-branches)
3862 (if (bobp) (throw 'exit nil))))))
3865 (defun org-optimize-window-after-visibility-change (state)
3866 "Adjust the window after a change in outline visibility.
3867 This function is the default value of the hook `org-cycle-hook'."
3868 (when (get-buffer-window (current-buffer))
3869 (cond
3870 ((eq state 'overview) (org-first-headline-recenter 1))
3871 ((eq state 'content) nil)
3872 ((eq state 'all) nil)
3873 ((eq state 'folded) nil)
3874 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3875 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3877 (defun org-subtree-end-visible-p ()
3878 "Is the end of the current subtree visible?"
3879 (pos-visible-in-window-p
3880 (save-excursion (org-end-of-subtree t) (point))))
3882 (defun org-first-headline-recenter (&optional N)
3883 "Move cursor to the first headline and recenter the headline.
3884 Optional argument N means, put the headline into the Nth line of the window."
3885 (goto-char (point-min))
3886 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3887 (beginning-of-line)
3888 (recenter (prefix-numeric-value N))))
3890 (defvar org-goto-window-configuration nil)
3891 (defvar org-goto-marker nil)
3892 (defvar org-goto-map (make-sparse-keymap))
3893 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3894 (while (setq cmd (pop cmds))
3895 (substitute-key-definition cmd cmd org-goto-map global-map)))
3896 (define-key org-goto-map "\C-m" 'org-goto-ret)
3897 (define-key org-goto-map [(left)] 'org-goto-left)
3898 (define-key org-goto-map [(right)] 'org-goto-right)
3899 (define-key org-goto-map [(?q)] 'org-goto-quit)
3900 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3901 (define-key org-goto-map "\C-i" 'org-cycle)
3902 (define-key org-goto-map [(tab)] 'org-cycle)
3903 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3904 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3905 (define-key org-goto-map "n" 'outline-next-visible-heading)
3906 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3907 (define-key org-goto-map "f" 'outline-forward-same-level)
3908 (define-key org-goto-map "b" 'outline-backward-same-level)
3909 (define-key org-goto-map "u" 'outline-up-heading)
3910 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3911 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3912 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3913 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3914 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3915 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3916 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3918 (defconst org-goto-help
3919 "Select a location to jump to, press RET
3920 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3922 (defun org-goto ()
3923 "Go to a different location of the document, keeping current visibility.
3925 When you want to go to a different location in a document, the fastest way
3926 is often to fold the entire buffer and then dive into the tree. This
3927 method has the disadvantage, that the previous location will be folded,
3928 which may not be what you want.
3930 This command works around this by showing a copy of the current buffer in
3931 overview mode. You can dive into the tree in that copy, to find the
3932 location you want to reach. When pressing RET, the command returns to the
3933 original buffer in which the visibility is still unchanged. It then jumps
3934 to the new location, making it and the headline hierarchy above it visible."
3935 (interactive)
3936 (let* ((org-goto-start-pos (point))
3937 (selected-point
3938 (org-get-location (current-buffer) org-goto-help)))
3939 (if selected-point
3940 (progn
3941 (org-mark-ring-push org-goto-start-pos)
3942 (goto-char selected-point)
3943 (if (or (org-invisible-p) (org-invisible-p2))
3944 (org-show-context 'org-goto)))
3945 (error "Quit"))))
3947 (defun org-get-location (buf help)
3948 "Let the user select a location in the Org-mode buffer BUF.
3949 This function uses a recursive edit. It returns the selected position
3950 or nil."
3951 (let (org-selected-point)
3952 (save-excursion
3953 (save-window-excursion
3954 (delete-other-windows)
3955 (switch-to-buffer (get-buffer-create "*org-goto*"))
3956 (with-output-to-temp-buffer "*Help*"
3957 (princ help))
3958 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3959 (setq buffer-read-only nil)
3960 (erase-buffer)
3961 (insert-buffer-substring buf)
3962 (let ((org-startup-truncated t)
3963 (org-startup-folded t)
3964 (org-startup-align-all-tables nil)
3965 (org-startup-with-deadline-check nil))
3966 (org-mode))
3967 (setq buffer-read-only t)
3968 (if (boundp 'org-goto-start-pos)
3969 (goto-char org-goto-start-pos)
3970 (goto-char (point-min)))
3971 (org-beginning-of-line)
3972 (message "Select location and press RET")
3973 ;; now we make sure that during selection, ony very few keys work
3974 ;; and that it is impossible to switch to another window.
3975 (let ((gm (current-global-map))
3976 (overriding-local-map org-goto-map))
3977 (unwind-protect
3978 (progn
3979 (use-global-map org-goto-map)
3980 (recursive-edit))
3981 (use-global-map gm)))))
3982 (kill-buffer "*org-goto*")
3983 org-selected-point))
3985 (defun org-goto-ret (&optional arg)
3986 "Finish `org-goto' by going to the new location."
3987 (interactive "P")
3988 (setq org-selected-point (point)
3989 current-prefix-arg arg)
3990 (throw 'exit nil))
3992 (defun org-goto-left ()
3993 "Finish `org-goto' by going to the new location."
3994 (interactive)
3995 (if (org-on-heading-p)
3996 (progn
3997 (beginning-of-line 1)
3998 (setq org-selected-point (point)
3999 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4000 (throw 'exit nil))
4001 (error "Not on a heading")))
4003 (defun org-goto-right ()
4004 "Finish `org-goto' by going to the new location."
4005 (interactive)
4006 (if (org-on-heading-p)
4007 (progn
4008 (outline-end-of-subtree)
4009 (or (eobp) (forward-char 1))
4010 (setq org-selected-point (point)
4011 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4012 (throw 'exit nil))
4013 (error "Not on a heading")))
4015 (defun org-goto-quit ()
4016 "Finish `org-goto' without cursor motion."
4017 (interactive)
4018 (setq org-selected-point nil)
4019 (throw 'exit nil))
4021 ;;; Promotion, Demotion, Inserting new headlines
4023 (defvar org-ignore-region nil
4024 "To temporarily disable the active region.")
4026 (defun org-insert-heading (&optional force-heading)
4027 "Insert a new heading or item with same depth at point.
4028 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4029 If point is at the beginning of a headline, insert a sibling before the
4030 current headline. If point is in the middle of a headline, split the headline
4031 at that position and make the rest of the headline part of the sibling below
4032 the current headline."
4033 (interactive "P")
4034 (if (= (buffer-size) 0)
4035 (insert "\n* ")
4036 (when (or force-heading (not (org-insert-item)))
4037 (let* ((head (save-excursion
4038 (condition-case nil
4039 (progn
4040 (org-back-to-heading)
4041 (match-string 0))
4042 (error "*"))))
4043 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4044 pos)
4045 (cond
4046 ((and (org-on-heading-p) (bolp)
4047 (save-excursion (backward-char 1) (not (org-invisible-p))))
4048 (open-line (if blank 2 1)))
4049 ((and (bolp) (save-excursion
4050 (backward-char 1) (not (org-invisible-p))))
4051 nil)
4052 (t (newline (if blank 2 1))))
4053 (insert head) (just-one-space)
4054 (setq pos (point))
4055 (end-of-line 1)
4056 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4057 (run-hooks 'org-insert-heading-hook)))))
4059 (defun org-in-item-p ()
4060 "It the cursor inside a plain list item.
4061 Does not have to be the first line."
4062 (save-excursion
4063 (condition-case nil
4064 (progn
4065 (org-beginning-of-item)
4066 (org-at-item-p)
4068 (error nil))))
4070 (defun org-insert-item (&optional checkbox)
4071 "Insert a new item at the current level.
4072 Return t when things worked, nil when we are not in an item."
4073 (when (save-excursion
4074 (condition-case nil
4075 (progn
4076 (org-beginning-of-item)
4077 (org-at-item-p)
4078 (if (org-invisible-p) (error "Invisible item"))
4080 (error nil)))
4081 (let* ((bul (match-string 0))
4082 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
4083 (match-end 0)))
4084 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
4085 pos)
4086 (cond
4087 ((and (org-at-item-p) (<= (point) eow))
4088 ;; before the bullet
4089 (beginning-of-line 1)
4090 (open-line (if blank 2 1)))
4091 ((<= (point) eow)
4092 (beginning-of-line 1))
4093 (t (newline (if blank 2 1))))
4094 (insert bul (if checkbox "[ ]" ""))
4095 (just-one-space)
4096 (setq pos (point))
4097 (end-of-line 1)
4098 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
4099 (org-maybe-renumber-ordered-list)
4100 (and checkbox (org-update-checkbox-count-maybe))
4103 (defun org-insert-todo-heading (arg)
4104 "Insert a new heading with the same level and TODO state as current heading.
4105 If the heading has no TODO state, or if the state is DONE, use the first
4106 state (TODO by default). Also with prefix arg, force first state."
4107 (interactive "P")
4108 (when (not (org-insert-item 'checkbox))
4109 (org-insert-heading)
4110 (save-excursion
4111 (org-back-to-heading)
4112 (outline-previous-heading)
4113 (looking-at org-todo-line-regexp))
4114 (if (or arg
4115 (not (match-beginning 2))
4116 (equal (match-string 2) org-done-string))
4117 (insert (car org-todo-keywords) " ")
4118 (insert (match-string 2) " "))))
4120 (defun org-promote-subtree ()
4121 "Promote the entire subtree.
4122 See also `org-promote'."
4123 (interactive)
4124 (save-excursion
4125 (org-map-tree 'org-promote))
4126 (org-fix-position-after-promote))
4128 (defun org-demote-subtree ()
4129 "Demote the entire subtree. See `org-demote'.
4130 See also `org-promote'."
4131 (interactive)
4132 (save-excursion
4133 (org-map-tree 'org-demote))
4134 (org-fix-position-after-promote))
4137 (defun org-do-promote ()
4138 "Promote the current heading higher up the tree.
4139 If the region is active in `transient-mark-mode', promote all headings
4140 in the region."
4141 (interactive)
4142 (save-excursion
4143 (if (org-region-active-p)
4144 (org-map-region 'org-promote (region-beginning) (region-end))
4145 (org-promote)))
4146 (org-fix-position-after-promote))
4148 (defun org-do-demote ()
4149 "Demote the current heading lower down the tree.
4150 If the region is active in `transient-mark-mode', demote all headings
4151 in the region."
4152 (interactive)
4153 (save-excursion
4154 (if (org-region-active-p)
4155 (org-map-region 'org-demote (region-beginning) (region-end))
4156 (org-demote)))
4157 (org-fix-position-after-promote))
4159 (defun org-fix-position-after-promote ()
4160 "Make sure that after pro/demotion cursor position is right."
4161 (if (and (equal (char-after) ?\n)
4162 (save-excursion
4163 (skip-chars-backward "a-zA-Z0-9_@")
4164 (looking-at org-todo-regexp)))
4165 (insert " "))
4166 (and (equal (char-after) ?\ )
4167 (equal (char-before) ?*)
4168 (forward-char 1)))
4170 (defun org-get-legal-level (level &optional change)
4171 "Rectify a level change under the influence of `org-odd-levels-only'
4172 LEVEL is a current level, CHANGE is by how much the level should be
4173 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4174 even level numbers will become the next higher odd number."
4175 (if org-odd-levels-only
4176 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4177 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4178 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4179 (max 1 (+ level change))))
4181 (defun org-promote ()
4182 "Promote the current heading higher up the tree.
4183 If the region is active in `transient-mark-mode', promote all headings
4184 in the region."
4185 (org-back-to-heading t)
4186 (let* ((level (save-match-data (funcall outline-level)))
4187 (up-head (make-string (org-get-legal-level level -1) ?*))
4188 (diff (abs (- level (length up-head)))))
4189 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4190 (replace-match up-head nil t)
4191 ;; Fixup tag positioning
4192 (and org-auto-align-tags (org-set-tags nil t))
4193 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4195 (defun org-demote ()
4196 "Demote the current heading lower down the tree.
4197 If the region is active in `transient-mark-mode', demote all headings
4198 in the region."
4199 (org-back-to-heading t)
4200 (let* ((level (save-match-data (funcall outline-level)))
4201 (down-head (make-string (org-get-legal-level level 1) ?*))
4202 (diff (abs (- level (length down-head)))))
4203 (replace-match down-head nil t)
4204 ;; Fixup tag positioning
4205 (and org-auto-align-tags (org-set-tags nil t))
4206 (if org-adapt-indentation (org-fixup-indentation diff))))
4208 (defun org-map-tree (fun)
4209 "Call FUN for every heading underneath the current one."
4210 (org-back-to-heading)
4211 (let ((level (funcall outline-level)))
4212 (save-excursion
4213 (funcall fun)
4214 (while (and (progn
4215 (outline-next-heading)
4216 (> (funcall outline-level) level))
4217 (not (eobp)))
4218 (funcall fun)))))
4220 (defun org-map-region (fun beg end)
4221 "Call FUN for every heading between BEG and END."
4222 (let ((org-ignore-region t))
4223 (save-excursion
4224 (setq end (copy-marker end))
4225 (goto-char beg)
4226 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4227 (< (point) end))
4228 (funcall fun))
4229 (while (and (progn
4230 (outline-next-heading)
4231 (< (point) end))
4232 (not (eobp)))
4233 (funcall fun)))))
4235 (defun org-fixup-indentation (diff)
4236 "Change the indentation in the current entry by DIFF
4237 However, if any line in the current entry has no indentation, or if it
4238 would end up with no indentation after the change, nothing at all is done."
4239 (save-excursion
4240 (let ((end (save-excursion (outline-next-heading)
4241 (point-marker)))
4242 (prohibit (if (> diff 0)
4243 "^\\S-"
4244 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4245 col)
4246 (unless (save-excursion (re-search-forward prohibit end t))
4247 (while (re-search-forward "^[ \t]+" end t)
4248 (goto-char (match-end 0))
4249 (setq col (current-column))
4250 (if (< diff 0) (replace-match ""))
4251 (indent-to (+ diff col))))
4252 (move-marker end nil))))
4254 ;;; Vertical tree motion, cutting and pasting of subtrees
4256 (defun org-move-subtree-up (&optional arg)
4257 "Move the current subtree up past ARG headlines of the same level."
4258 (interactive "p")
4259 (org-move-subtree-down (- (prefix-numeric-value arg))))
4261 (defun org-move-subtree-down (&optional arg)
4262 "Move the current subtree down past ARG headlines of the same level."
4263 (interactive "p")
4264 (setq arg (prefix-numeric-value arg))
4265 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4266 'outline-get-last-sibling))
4267 (ins-point (make-marker))
4268 (cnt (abs arg))
4269 beg end txt folded)
4270 ;; Select the tree
4271 (org-back-to-heading)
4272 (setq beg (point))
4273 (save-match-data
4274 (save-excursion (outline-end-of-heading)
4275 (setq folded (org-invisible-p)))
4276 (outline-end-of-subtree))
4277 (outline-next-heading)
4278 (setq end (point))
4279 ;; Find insertion point, with error handling
4280 (goto-char beg)
4281 (while (> cnt 0)
4282 (or (and (funcall movfunc) (looking-at outline-regexp))
4283 (progn (goto-char beg)
4284 (error "Cannot move past superior level or buffer limit")))
4285 (setq cnt (1- cnt)))
4286 (if (> arg 0)
4287 ;; Moving forward - still need to move over subtree
4288 (progn (outline-end-of-subtree)
4289 (outline-next-heading)
4290 (if (not (or (looking-at (concat "^" outline-regexp))
4291 (bolp)))
4292 (newline))))
4293 (move-marker ins-point (point))
4294 (setq txt (buffer-substring beg end))
4295 (delete-region beg end)
4296 (insert txt)
4297 (goto-char ins-point)
4298 (if folded (hide-subtree))
4299 (move-marker ins-point nil)))
4301 (defvar org-subtree-clip ""
4302 "Clipboard for cut and paste of subtrees.
4303 This is actually only a copy of the kill, because we use the normal kill
4304 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4306 (defvar org-subtree-clip-folded nil
4307 "Was the last copied subtree folded?
4308 This is used to fold the tree back after pasting.")
4310 (defun org-cut-subtree ()
4311 "Cut the current subtree into the clipboard.
4312 This is a short-hand for marking the subtree and then cutting it."
4313 (interactive)
4314 (org-copy-subtree 'cut))
4316 (defun org-copy-subtree (&optional cut)
4317 "Cut the current subtree into the clipboard.
4318 This is a short-hand for marking the subtree and then copying it.
4319 If CUT is non-nil, actually cut the subtree."
4320 (interactive)
4321 (let (beg end folded)
4322 (org-back-to-heading)
4323 (setq beg (point))
4324 (save-match-data
4325 (save-excursion (outline-end-of-heading)
4326 (setq folded (org-invisible-p)))
4327 (outline-end-of-subtree))
4328 (if (equal (char-after) ?\n) (forward-char 1))
4329 (setq end (point))
4330 (goto-char beg)
4331 (when (> end beg)
4332 (setq org-subtree-clip-folded folded)
4333 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4334 (setq org-subtree-clip (current-kill 0))
4335 (message "%s: Subtree with %d characters"
4336 (if cut "Cut" "Copied")
4337 (length org-subtree-clip)))))
4339 (defun org-paste-subtree (&optional level tree)
4340 "Paste the clipboard as a subtree, with modification of headline level.
4341 The entire subtree is promoted or demoted in order to match a new headline
4342 level. By default, the new level is derived from the visible headings
4343 before and after the insertion point, and taken to be the inferior headline
4344 level of the two. So if the previous visible heading is level 3 and the
4345 next is level 4 (or vice versa), level 4 will be used for insertion.
4346 This makes sure that the subtree remains an independent subtree and does
4347 not swallow low level entries.
4349 You can also force a different level, either by using a numeric prefix
4350 argument, or by inserting the heading marker by hand. For example, if the
4351 cursor is after \"*****\", then the tree will be shifted to level 5.
4353 If you want to insert the tree as is, just use \\[yank].
4355 If optional TREE is given, use this text instead of the kill ring."
4356 (interactive "P")
4357 (unless (org-kill-is-subtree-p tree)
4358 (error
4359 (substitute-command-keys
4360 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4361 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4362 (^re (concat "^\\(" outline-regexp "\\)"))
4363 (re (concat "\\(" outline-regexp "\\)"))
4364 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4366 (old-level (if (string-match ^re txt)
4367 (- (match-end 0) (match-beginning 0))
4368 -1))
4369 (force-level (cond (level (prefix-numeric-value level))
4370 ((string-match
4371 ^re_ (buffer-substring (point-at-bol) (point)))
4372 (- (match-end 0) (match-beginning 0)))
4373 (t nil)))
4374 (previous-level (save-excursion
4375 (condition-case nil
4376 (progn
4377 (outline-previous-visible-heading 1)
4378 (if (looking-at re)
4379 (- (match-end 0) (match-beginning 0))
4381 (error 1))))
4382 (next-level (save-excursion
4383 (condition-case nil
4384 (progn
4385 (outline-next-visible-heading 1)
4386 (if (looking-at re)
4387 (- (match-end 0) (match-beginning 0))
4389 (error 1))))
4390 (new-level (or force-level (max previous-level next-level)))
4391 (shift (if (or (= old-level -1)
4392 (= new-level -1)
4393 (= old-level new-level))
4395 (- new-level old-level)))
4396 (shift1 shift)
4397 (delta (if (> shift 0) -1 1))
4398 (func (if (> shift 0) 'org-demote 'org-promote))
4399 (org-odd-levels-only nil)
4400 beg end)
4401 ;; Remove the forces level indicator
4402 (if force-level
4403 (delete-region (point-at-bol) (point)))
4404 ;; Make sure we start at the beginning of an empty line
4405 (if (not (bolp)) (insert "\n"))
4406 (if (not (looking-at "[ \t]*$"))
4407 (progn (insert "\n") (backward-char 1)))
4408 ;; Paste
4409 (setq beg (point))
4410 (if (string-match "[ \t\r\n]+\\'" txt)
4411 (setq txt (replace-match "\n" t t txt)))
4412 (insert txt)
4413 (setq end (point))
4414 (if (looking-at "[ \t\r\n]+")
4415 (replace-match "\n"))
4416 (goto-char beg)
4417 ;; Shift if necessary
4418 (if (= shift 0)
4419 (message "Pasted at level %d, without shift" new-level)
4420 (save-restriction
4421 (narrow-to-region beg end)
4422 (while (not (= shift 0))
4423 (org-map-region func (point-min) (point-max))
4424 (setq shift (+ delta shift)))
4425 (goto-char (point-min))
4426 (message "Pasted at level %d, with shift by %d levels"
4427 new-level shift1)))
4428 (if (and kill-ring
4429 (eq org-subtree-clip (current-kill 0))
4430 org-subtree-clip-folded)
4431 ;; The tree was folded before it was killed/copied
4432 (hide-subtree))))
4434 (defun org-kill-is-subtree-p (&optional txt)
4435 "Check if the current kill is an outline subtree, or a set of trees.
4436 Returns nil if kill does not start with a headline, or if the first
4437 headline level is not the largest headline level in the tree.
4438 So this will actually accept several entries of equal levels as well,
4439 which is OK for `org-paste-subtree'.
4440 If optional TXT is given, check this string instead of the current kill."
4441 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4442 (start-level (and kill
4443 (string-match (concat "\\`" outline-regexp) kill)
4444 (- (match-end 0) (match-beginning 0))))
4445 (re (concat "^" outline-regexp))
4446 (start 1))
4447 (if (not start-level)
4448 nil ;; does not even start with a heading
4449 (catch 'exit
4450 (while (setq start (string-match re kill (1+ start)))
4451 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4452 (throw 'exit nil)))
4453 t))))
4455 (defun org-narrow-to-subtree ()
4456 "Narrow buffer to the current subtree."
4457 (interactive)
4458 (save-excursion
4459 (narrow-to-region
4460 (progn (org-back-to-heading) (point))
4461 (progn (org-end-of-subtree t) (point)))))
4463 ;;; Plain list items
4465 (defun org-at-item-p ()
4466 "Is point in a line starting a hand-formatted item?"
4467 (let ((llt org-plain-list-ordered-item-terminator))
4468 (save-excursion
4469 (goto-char (point-at-bol))
4470 (looking-at
4471 (cond
4472 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4473 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4474 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4475 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4477 (defun org-at-item-checkbox-p ()
4478 "Is point at a line starting a plain-list item with a checklet?"
4479 (and (org-at-item-p)
4480 (save-excursion
4481 (goto-char (match-end 0))
4482 (skip-chars-forward " \t")
4483 (looking-at "\\[[ X]\\]"))))
4485 (defun org-toggle-checkbox (&optional arg)
4486 "Toggle the checkbox in the current line."
4487 (interactive "P")
4488 (catch 'exit
4489 (let (beg end status (firstnew 'unknown))
4490 (cond
4491 ((org-region-active-p)
4492 (setq beg (region-beginning) end (region-end)))
4493 ((org-on-heading-p)
4494 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4495 ((org-at-item-checkbox-p)
4496 (save-excursion
4497 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4498 (throw 'exit t))
4499 (t (error "Not at a checkbox or heading, and no active region")))
4500 (save-excursion
4501 (goto-char beg)
4502 (while (< (point) end)
4503 (when (org-at-item-checkbox-p)
4504 (setq status (equal (match-string 0) "[X]"))
4505 (when (eq firstnew 'unknown)
4506 (setq firstnew (not status)))
4507 (replace-match
4508 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4509 (beginning-of-line 2)))))
4510 (org-update-checkbox-count-maybe))
4512 (defun org-update-checkbox-count-maybe ()
4513 "Update checkbox statistics unless turned off by user."
4514 (when org-provide-checkbox-statistics
4515 (org-update-checkbox-count)))
4517 (defun org-update-checkbox-count (&optional all)
4518 "Update the checkbox statistics in the current section.
4519 This will find all statistic cookies like [57%] and [6/12] and update them
4520 with the current numbers. With optional prefix argument ALL, do this for
4521 the whole buffer."
4522 (interactive "P")
4523 (save-excursion
4524 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
4525 (beg (progn (outline-back-to-heading) (point)))
4526 (end (move-marker (make-marker)
4527 (progn (outline-next-heading) (point))))
4528 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
4529 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
4530 b1 e1 f1 c-on c-off lim (cstat 0))
4531 (when all
4532 (goto-char (point-min))
4533 (outline-next-heading)
4534 (setq beg (point) end (point-max)))
4535 (goto-char beg)
4536 (while (re-search-forward re end t)
4537 (setq cstat (1+ cstat)
4538 b1 (match-beginning 0)
4539 e1 (match-end 0)
4540 f1 (match-beginning 1)
4541 lim (cond
4542 ((org-on-heading-p) (outline-next-heading) (point))
4543 ((org-at-item-p) (org-end-of-item) (point))
4544 (t nil))
4545 c-on 0 c-off 0)
4546 (goto-char e1)
4547 (when lim
4548 (while (re-search-forward re-box lim t)
4549 (if (equal (match-string 2) "[ ]")
4550 (setq c-off (1+ c-off))
4551 (setq c-on (1+ c-on))))
4552 (delete-region b1 e1)
4553 (goto-char b1)
4554 (insert (if f1
4555 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
4556 (format "[%d/%d]" c-on (+ c-on c-off))))))
4557 (when (interactive-p)
4558 (message "Checkbox satistics updated %s (%d places)"
4559 (if all "in entire file" "in current outline entry") cstat)))))
4561 (defun org-get-checkbox-statistics-face ()
4562 "Select the face for checkbox statistics.
4563 The face will be `org-done' when all relevant boxes are checked. Otherwise
4564 it will be `org-todo'."
4565 (if (match-end 1)
4566 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
4567 (if (and (> (match-end 2) (match-beginning 2))
4568 (equal (match-string 2) (match-string 3)))
4569 'org-done
4570 'org-todo)))
4572 (defun org-get-indentation (&optional line)
4573 "Get the indentation of the current line, interpreting tabs.
4574 When LINE is given, assume it represents a line and compute its indentation."
4575 (if line
4576 (if (string-match "^ *" (org-remove-tabs line))
4577 (match-end 0))
4578 (save-excursion
4579 (beginning-of-line 1)
4580 (skip-chars-forward " \t")
4581 (current-column))))
4583 (defun org-remove-tabs (s &optional width)
4584 "Replace tabulators in S with spaces.
4585 Assumes that s is a single line, starting in column 0."
4586 (setq width (or width tab-width))
4587 (while (string-match "\t" s)
4588 (setq s (replace-match
4589 (make-string
4590 (- (* width (/ (+ (match-beginning 0) width) width))
4591 (match-beginning 0)) ?\ )
4592 t t s)))
4595 ;; FIXME: document properly.
4596 (defun org-fix-indentation (line ind)
4597 "If the current indenation is smaller than ind1, leave it alone.
4598 If it is larger than ind, reduce it by ind."
4599 (let* ((l (org-remove-tabs line))
4600 (i (org-get-indentation l))
4601 (i1 (car ind)) (i2 (cdr ind)))
4602 (if (>= i i2) (setq l (substring line i2)))
4603 (if (> i1 0)
4604 (concat (make-string i1 ?\ ) l)
4605 l)))
4607 (defun org-beginning-of-item ()
4608 "Go to the beginning of the current hand-formatted item.
4609 If the cursor is not in an item, throw an error."
4610 (interactive)
4611 (let ((pos (point))
4612 (limit (save-excursion (org-back-to-heading)
4613 (beginning-of-line 2) (point)))
4614 ind ind1)
4615 (if (org-at-item-p)
4616 (beginning-of-line 1)
4617 (beginning-of-line 1)
4618 (skip-chars-forward " \t")
4619 (setq ind (current-column))
4620 (if (catch 'exit
4621 (while t
4622 (beginning-of-line 0)
4623 (if (< (point) limit) (throw 'exit nil))
4624 (unless (looking-at "[ \t]*$")
4625 (skip-chars-forward " \t")
4626 (setq ind1 (current-column))
4627 (if (< ind1 ind)
4628 (throw 'exit (org-at-item-p))))))
4630 (goto-char pos)
4631 (error "Not in an item")))))
4633 (defun org-end-of-item ()
4634 "Go to the end of the current hand-formatted item.
4635 If the cursor is not in an item, throw an error."
4636 (interactive)
4637 (let ((pos (point))
4638 (limit (save-excursion (outline-next-heading) (point)))
4639 (ind (save-excursion
4640 (org-beginning-of-item)
4641 (skip-chars-forward " \t")
4642 (current-column)))
4643 ind1)
4644 (if (catch 'exit
4645 (while t
4646 (beginning-of-line 2)
4647 (if (>= (point) limit) (throw 'exit t))
4648 (unless (looking-at "[ \t]*$")
4649 (skip-chars-forward " \t")
4650 (setq ind1 (current-column))
4651 (if (<= ind1 ind) (throw 'exit t)))))
4652 (beginning-of-line 1)
4653 (goto-char pos)
4654 (error "Not in an item"))))
4656 (defun org-next-item ()
4657 "Move to the beginning of the next item in the current plain list.
4658 Error if not at a plain list, or if this is the last item in the list."
4659 (interactive)
4660 (let (ind ind1 (pos (point)))
4661 (org-beginning-of-item)
4662 (setq ind (org-get-indentation))
4663 (org-end-of-item)
4664 (setq ind1 (org-get-indentation))
4665 (unless (and (org-at-item-p) (= ind ind1))
4666 (goto-char pos)
4667 (error "On last item"))))
4669 (defun org-previous-item ()
4670 "Move to the beginning of the previous item in the current plain list.
4671 Error if not at a plain list, or if this is the last item in the list."
4672 (interactive)
4673 (let (beg ind (pos (point)))
4674 (org-beginning-of-item)
4675 (setq beg (point))
4676 (setq ind (org-get-indentation))
4677 (goto-char beg)
4678 (catch 'exit
4679 (while t
4680 (beginning-of-line 0)
4681 (if (looking-at "[ \t]*$")
4683 (if (<= (org-get-indentation) ind)
4684 (throw 'exit t)))))
4685 (condition-case nil
4686 (org-beginning-of-item)
4687 (error (goto-char pos)
4688 (error "On first item")))))
4690 (defun org-move-item-down ()
4691 "Move the plain list item at point down, i.e. swap with following item.
4692 Subitems (items with larger indentation) are considered part of the item,
4693 so this really moves item trees."
4694 (interactive)
4695 (let (beg end ind ind1 (pos (point)) txt)
4696 (org-beginning-of-item)
4697 (setq beg (point))
4698 (setq ind (org-get-indentation))
4699 (org-end-of-item)
4700 (setq end (point))
4701 (setq ind1 (org-get-indentation))
4702 (if (and (org-at-item-p) (= ind ind1))
4703 (progn
4704 (org-end-of-item)
4705 (setq txt (buffer-substring beg end))
4706 (save-excursion
4707 (delete-region beg end))
4708 (setq pos (point))
4709 (insert txt)
4710 (goto-char pos)
4711 (org-maybe-renumber-ordered-list))
4712 (goto-char pos)
4713 (error "Cannot move this item further down"))))
4715 (defun org-move-item-up (arg)
4716 "Move the plain list item at point up, i.e. swap with previous item.
4717 Subitems (items with larger indentation) are considered part of the item,
4718 so this really moves item trees."
4719 (interactive "p")
4720 (let (beg end ind ind1 (pos (point)) txt)
4721 (org-beginning-of-item)
4722 (setq beg (point))
4723 (setq ind (org-get-indentation))
4724 (org-end-of-item)
4725 (setq end (point))
4726 (goto-char beg)
4727 (catch 'exit
4728 (while t
4729 (beginning-of-line 0)
4730 (if (looking-at "[ \t]*$")
4732 (if (<= (setq ind1 (org-get-indentation)) ind)
4733 (throw 'exit t)))))
4734 (condition-case nil
4735 (org-beginning-of-item)
4736 (error (goto-char beg)
4737 (error "Cannot move this item further up")))
4738 (setq ind1 (org-get-indentation))
4739 (if (and (org-at-item-p) (= ind ind1))
4740 (progn
4741 (setq txt (buffer-substring beg end))
4742 (save-excursion
4743 (delete-region beg end))
4744 (setq pos (point))
4745 (insert txt)
4746 (goto-char pos)
4747 (org-maybe-renumber-ordered-list))
4748 (goto-char pos)
4749 (error "Cannot move this item further up"))))
4751 (defun org-maybe-renumber-ordered-list ()
4752 "Renumber the ordered list at point if setup allows it.
4753 This tests the user option `org-auto-renumber-ordered-lists' before
4754 doing the renumbering."
4755 (and org-auto-renumber-ordered-lists
4756 (org-at-item-p)
4757 (match-beginning 3)
4758 (org-renumber-ordered-list 1)))
4760 (defun org-get-string-indentation (s)
4761 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4762 (let ((n -1) (i 0) (w tab-width) c)
4763 (catch 'exit
4764 (while (< (setq n (1+ n)) (length s))
4765 (setq c (aref s n))
4766 (cond ((= c ?\ ) (setq i (1+ i)))
4767 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4768 (t (throw 'exit t)))))
4771 (defun org-renumber-ordered-list (arg)
4772 "Renumber an ordered plain list.
4773 Cursor needs to be in the first line of an item, the line that starts
4774 with something like \"1.\" or \"2)\"."
4775 (interactive "p")
4776 (unless (and (org-at-item-p)
4777 (match-beginning 3))
4778 (error "This is not an ordered list"))
4779 (let ((line (org-current-line))
4780 (col (current-column))
4781 (ind (org-get-string-indentation
4782 (buffer-substring (point-at-bol) (match-beginning 3))))
4783 ;; (term (substring (match-string 3) -1))
4784 ind1 (n (1- arg)))
4785 ;; find where this list begins
4786 (catch 'exit
4787 (while t
4788 (catch 'next
4789 (beginning-of-line 0)
4790 (if (looking-at "[ \t]*$") (throw 'next t))
4791 (skip-chars-forward " \t") (setq ind1 (current-column))
4792 (if (or (< ind1 ind)
4793 (and (= ind1 ind)
4794 (not (org-at-item-p))))
4795 (throw 'exit t)))))
4796 ;; Walk forward and replace these numbers
4797 (catch 'exit
4798 (while t
4799 (catch 'next
4800 (beginning-of-line 2)
4801 (if (eobp) (throw 'exit nil))
4802 (if (looking-at "[ \t]*$") (throw 'next nil))
4803 (skip-chars-forward " \t") (setq ind1 (current-column))
4804 (if (> ind1 ind) (throw 'next t))
4805 (if (< ind1 ind) (throw 'exit t))
4806 (if (not (org-at-item-p)) (throw 'exit nil))
4807 (if (not (match-beginning 3))
4808 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4809 (delete-region (match-beginning 3) (1- (match-end 3)))
4810 (goto-char (match-beginning 3))
4811 (insert (format "%d" (setq n (1+ n)))))))
4812 (goto-line line)
4813 (move-to-column col)))
4815 (defvar org-last-indent-begin-marker (make-marker))
4816 (defvar org-last-indent-end-marker (make-marker))
4818 (defun org-outdent-item (arg)
4819 "Outdent a local list item."
4820 (interactive "p")
4821 (org-indent-item (- arg)))
4823 (defun org-indent-item (arg)
4824 "Indent a local list item."
4825 (interactive "p")
4826 (unless (org-at-item-p)
4827 (error "Not on an item"))
4828 (save-excursion
4829 (let (beg end ind ind1)
4830 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4831 (setq beg org-last-indent-begin-marker
4832 end org-last-indent-end-marker)
4833 (org-beginning-of-item)
4834 (setq beg (move-marker org-last-indent-begin-marker (point)))
4835 (org-end-of-item)
4836 (setq end (move-marker org-last-indent-end-marker (point))))
4837 (goto-char beg)
4838 (skip-chars-forward " \t") (setq ind (current-column))
4839 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4840 (while (< (point) end)
4841 (beginning-of-line 1)
4842 (skip-chars-forward " \t") (setq ind1 (current-column))
4843 (delete-region (point-at-bol) (point))
4844 (indent-to-column (+ ind1 arg))
4845 (beginning-of-line 2)))))
4847 ;;; Archiving
4849 (defun org-archive-subtree (&optional find-done)
4850 "Move the current subtree to the archive.
4851 The archive can be a certain top-level heading in the current file, or in
4852 a different file. The tree will be moved to that location, the subtree
4853 heading be marked DONE, and the current time will be added.
4855 When called with prefix argument FIND-DONE, find whole trees without any
4856 open TODO items and archive them (after getting confirmation from the user).
4857 If the cursor is not at a headline when this comand is called, try all level
4858 1 trees. If the cursor is on a headline, only try the direct children of
4859 this heading. "
4860 (interactive "P")
4861 (if find-done
4862 (org-archive-all-done)
4863 ;; Save all relevant TODO keyword-relatex variables
4865 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4866 (tr-org-todo-keywords org-todo-keywords)
4867 (tr-org-todo-interpretation org-todo-interpretation)
4868 (tr-org-done-string org-done-string)
4869 (tr-org-todo-regexp org-todo-regexp)
4870 (tr-org-todo-line-regexp org-todo-line-regexp)
4871 (this-buffer (current-buffer))
4872 file heading buffer level newfile-p)
4873 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4874 (progn
4875 (setq file (format (match-string 1 org-archive-location)
4876 (file-name-nondirectory buffer-file-name))
4877 heading (match-string 2 org-archive-location)))
4878 (error "Invalid `org-archive-location'"))
4879 (if (> (length file) 0)
4880 (setq newfile-p (not (file-exists-p file))
4881 buffer (find-file-noselect file))
4882 (setq buffer (current-buffer)))
4883 (unless buffer
4884 (error "Cannot access file \"%s\"" file))
4885 (if (and (> (length heading) 0)
4886 (string-match "^\\*+" heading))
4887 (setq level (match-end 0))
4888 (setq heading nil level 0))
4889 (save-excursion
4890 ;; We first only copy, in case something goes wrong
4891 ;; we need to protect this-command, to avoid kill-region sets it,
4892 ;; which would lead to duplication of subtrees
4893 (let (this-command) (org-copy-subtree))
4894 (set-buffer buffer)
4895 ;; Enforce org-mode for the archive buffer
4896 (if (not (org-mode-p))
4897 ;; Force the mode for future visits.
4898 (let ((org-insert-mode-line-in-empty-file t))
4899 (call-interactively 'org-mode)))
4900 (when newfile-p
4901 (goto-char (point-max))
4902 (insert (format "\nArchived entries from file %s\n\n"
4903 (buffer-file-name this-buffer))))
4904 ;; Force the TODO keywords of the original buffer
4905 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4906 (org-todo-keywords tr-org-todo-keywords)
4907 (org-todo-interpretation tr-org-todo-interpretation)
4908 (org-done-string tr-org-done-string)
4909 (org-todo-regexp tr-org-todo-regexp)
4910 (org-todo-line-regexp tr-org-todo-line-regexp))
4911 (goto-char (point-min))
4912 (if heading
4913 (progn
4914 (if (re-search-forward
4915 (concat "\\(^\\|\r\\)"
4916 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4917 nil t)
4918 (goto-char (match-end 0))
4919 ;; Heading not found, just insert it at the end
4920 (goto-char (point-max))
4921 (or (bolp) (insert "\n"))
4922 (insert "\n" heading "\n")
4923 (end-of-line 0))
4924 ;; Make the subtree visible
4925 (show-subtree)
4926 (org-end-of-subtree t)
4927 (skip-chars-backward " \t\r\n")
4928 (and (looking-at "[ \t\r\n]*")
4929 (replace-match "\n\n")))
4930 ;; No specific heading, just go to end of file.
4931 (goto-char (point-max)) (insert "\n"))
4932 ;; Paste
4933 (org-paste-subtree (1+ level))
4934 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4935 (if org-archive-mark-done
4936 (org-todo (length org-todo-keywords)))
4937 ;; Move cursor to right after the TODO keyword
4938 (when org-archive-stamp-time
4939 (beginning-of-line 1)
4940 (looking-at org-todo-line-regexp)
4941 (goto-char (or (match-end 2) (match-beginning 3)))
4942 (org-insert-time-stamp (org-current-time) t t "(" ")"))
4943 ;; Save the buffer, if it is not the same buffer.
4944 (if (not (eq this-buffer buffer)) (save-buffer))))
4945 ;; Here we are back in the original buffer. Everything seems to have
4946 ;; worked. So now cut the tree and finish up.
4947 (let (this-command) (org-cut-subtree))
4948 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4949 (message "Subtree archived %s"
4950 (if (eq this-buffer buffer)
4951 (concat "under heading: " heading)
4952 (concat "in file: " (abbreviate-file-name file)))))))
4954 (defun org-archive-all-done (&optional tag)
4955 "Archive sublevels of the current tree without open TODO items.
4956 If the cursor is not on a headline, try all level 1 trees. If
4957 it is on a headline, try all direct children.
4958 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4959 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4960 (rea (concat ".*:" org-archive-tag ":"))
4961 (begm (make-marker))
4962 (endm (make-marker))
4963 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4964 "Move subtree to archive (no open TODO items)? "))
4965 beg end (cntarch 0))
4966 (if (org-on-heading-p)
4967 (progn
4968 (setq re1 (concat "^" (regexp-quote
4969 (make-string
4970 (1+ (- (match-end 0) (match-beginning 0)))
4971 ?*))
4972 " "))
4973 (move-marker begm (point))
4974 (move-marker endm (org-end-of-subtree t)))
4975 (setq re1 "^* ")
4976 (move-marker begm (point-min))
4977 (move-marker endm (point-max)))
4978 (save-excursion
4979 (goto-char begm)
4980 (while (re-search-forward re1 endm t)
4981 (setq beg (match-beginning 0)
4982 end (save-excursion (org-end-of-subtree t) (point)))
4983 (goto-char beg)
4984 (if (re-search-forward re end t)
4985 (goto-char end)
4986 (goto-char beg)
4987 (if (and (or (not tag) (not (looking-at rea)))
4988 (y-or-n-p question))
4989 (progn
4990 (if tag
4991 (org-toggle-tag org-archive-tag 'on)
4992 (org-archive-subtree))
4993 (setq cntarch (1+ cntarch)))
4994 (goto-char end)))))
4995 (message "%d trees archived" cntarch)))
4997 (defun org-cycle-hide-archived-subtrees (state)
4998 "Re-hide all archived subtrees after a visibility state change."
4999 (when (and (not org-cycle-open-archived-trees)
5000 (not (memq state '(overview folded))))
5001 (save-excursion
5002 (let* ((globalp (memq state '(contents all)))
5003 (beg (if globalp (point-min) (point)))
5004 (end (if globalp (point-max) (org-end-of-subtree t))))
5005 (org-hide-archived-subtrees beg end)
5006 (goto-char beg)
5007 (if (looking-at (concat ".*:" org-archive-tag ":"))
5008 (message (substitute-command-keys
5009 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5011 (defun org-force-cycle-archived ()
5012 "Cycle subtree even if it is archived."
5013 (interactive)
5014 (setq this-command 'org-cycle)
5015 (let ((org-cycle-open-archived-trees t))
5016 (call-interactively 'org-cycle)))
5018 (defun org-hide-archived-subtrees (beg end)
5019 "Re-hide all archived subtrees after a visibility state change."
5020 (save-excursion
5021 (let* ((re (concat ":" org-archive-tag ":")))
5022 (goto-char beg)
5023 (while (re-search-forward re end t)
5024 (and (org-on-heading-p) (hide-subtree))
5025 (org-end-of-subtree t)))))
5027 (defun org-toggle-tag (tag &optional onoff)
5028 "Toggle the tag TAG for the current line.
5029 If ONOFF is `on' or `off', don't toggle but set to this state."
5030 (unless (org-on-heading-p) (error "Not on headling"))
5031 (let (res current)
5032 (save-excursion
5033 (beginning-of-line)
5034 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5035 (point-at-eol) t)
5036 (progn
5037 (setq current (match-string 1))
5038 (replace-match ""))
5039 (setq current ""))
5040 (setq current (nreverse (org-split-string current ":")))
5041 (cond
5042 ((eq onoff 'on)
5043 (setq res t)
5044 (or (member tag current) (push tag current)))
5045 ((eq onoff 'off)
5046 (or (not (member tag current)) (setq current (delete tag current))))
5047 (t (if (member tag current)
5048 (setq current (delete tag current))
5049 (setq res t)
5050 (push tag current))))
5051 (end-of-line 1)
5052 (when current
5053 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5054 (org-set-tags nil t))
5055 res))
5057 (defun org-toggle-archive-tag (&optional arg)
5058 "Toggle the archive tag for the current headline.
5059 With prefix ARG, check all children of current headline and offer tagging
5060 the children that do not contain any open TODO items."
5061 (interactive "P")
5062 (if arg
5063 (org-archive-all-done 'tag)
5064 (let (set)
5065 (save-excursion
5066 (org-back-to-heading t)
5067 (setq set (org-toggle-tag org-archive-tag))
5068 (when set (hide-subtree)))
5069 (and set (beginning-of-line 1))
5070 (message "Subtree %s" (if set "archived" "unarchived")))))
5072 (defvar org-agenda-multi nil) ; dynammically scoped
5073 (defvar org-agenda-buffer-name "*Org Agenda*")
5074 (defvar org-pre-agenda-window-conf nil)
5075 (defun org-prepare-agenda ()
5076 (if org-agenda-multi
5077 (progn
5078 (setq buffer-read-only nil)
5079 (goto-char (point-max))
5080 (unless (= (point) 1)
5081 (insert "\n" (make-string (window-width) ?=) "\n"))
5082 (narrow-to-region (point) (point-max)))
5083 (org-agenda-maybe-reset-markers 'force)
5084 (org-prepare-agenda-buffers (org-agenda-files))
5085 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
5086 (awin (get-buffer-window abuf)))
5087 (cond
5088 ((equal (current-buffer) abuf) nil)
5089 (awin (select-window awin))
5090 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
5091 ((equal org-agenda-window-setup 'current-window)
5092 (switch-to-buffer abuf))
5093 ((equal org-agenda-window-setup 'other-window)
5094 (switch-to-buffer-other-window abuf))
5095 ((equal org-agenda-window-setup 'other-frame)
5096 (switch-to-buffer-other-frame abuf))
5097 ((equal org-agenda-window-setup 'reorganize-frame)
5098 (delete-other-windows)
5099 (switch-to-buffer-other-window abuf))))
5100 (setq buffer-read-only nil)
5101 (erase-buffer)
5102 (org-agenda-mode))
5103 (setq buffer-read-only nil))
5105 (defun org-finalize-agenda ()
5106 "Finishing touch for the agenda buffer, called just before displaying it."
5107 (unless org-agenda-multi
5108 (org-agenda-align-tags)
5109 (save-excursion
5110 (let ((buffer-read-only))
5111 (goto-char (point-min))
5112 (while (org-activate-bracket-links (point-max))
5113 (add-text-properties (match-beginning 0) (match-end 0)
5114 '(face org-link))))
5115 (run-hooks 'org-finalize-agenda-hook))))
5117 (defun org-prepare-agenda-buffers (files)
5118 "Create buffers for all agenda files, protect archived trees and comments."
5119 (interactive)
5120 (let ((pa '(:org-archived t))
5121 (pc '(:org-comment t))
5122 (pall '(:org-archived t :org-comment t))
5123 (rea (concat ":" org-archive-tag ":"))
5124 bmp file re)
5125 (save-excursion
5126 (while (setq file (pop files))
5127 (org-check-agenda-file file)
5128 (set-buffer (org-get-agenda-file-buffer file))
5129 (widen)
5130 (setq bmp (buffer-modified-p))
5131 (save-excursion
5132 (remove-text-properties (point-min) (point-max) pall)
5133 (when org-agenda-skip-archived-trees
5134 (goto-char (point-min))
5135 (while (re-search-forward rea nil t)
5136 (if (org-on-heading-p)
5137 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
5138 (goto-char (point-min))
5139 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
5140 (while (re-search-forward re nil t)
5141 (add-text-properties
5142 (match-beginning 0) (org-end-of-subtree t) pc)))
5143 (set-buffer-modified-p bmp)))))
5145 (defun org-agenda-skip ()
5146 "Throw to `:skip' in places that should be skipped."
5147 (let ((p (point-at-bol)))
5148 (and org-agenda-skip-archived-trees
5149 (get-text-property p :org-archived)
5150 (org-end-of-subtree t)
5151 (throw :skip t))
5152 (and (get-text-property p :org-comment)
5153 (org-end-of-subtree t)
5154 (throw :skip t))
5155 (if (equal (char-after p) ?#) (throw :skip t))))
5157 (defun org-agenda-toggle-archive-tag ()
5158 "Toggle the archive tag for the current entry."
5159 (interactive)
5160 (org-agenda-check-no-diary)
5161 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
5162 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
5163 (org-agenda-error)))
5164 (buffer (marker-buffer hdmarker))
5165 (pos (marker-position hdmarker))
5166 (buffer-read-only nil)
5167 newhead)
5168 (with-current-buffer buffer
5169 (widen)
5170 (goto-char pos)
5171 (org-show-context 'agenda)
5172 (save-excursion
5173 (and (outline-next-heading)
5174 (org-flag-heading nil))) ; show the next heading
5175 (call-interactively 'org-toggle-archive-tag)
5176 (end-of-line 1)
5177 (setq newhead (org-get-heading)))
5178 (org-agenda-change-all-lines newhead hdmarker)
5179 (beginning-of-line 1)))
5181 ;;; Dynamic blocks
5183 (defun org-find-dblock (name)
5184 "Find the first dynamic block with name NAME in the buffer.
5185 If not found, stay at current position and return nil."
5186 (let (pos)
5187 (save-excursion
5188 (goto-char (point-min))
5189 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
5190 nil t)
5191 (match-beginning 0))))
5192 (if pos (goto-char pos))
5193 pos))
5195 (defconst org-dblock-start-re
5196 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
5197 "Matches the startline of a dynamic block, with parameters.")
5199 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
5200 "Matches the end of a dyhamic block.")
5202 (defun org-create-dblock (plist)
5203 "Create a dynamic block section, with parameters taken from PLIST.
5204 PLIST must containe a :name entry which is used as name of the block."
5205 (unless (bolp) (newline))
5206 (let ((name (plist-get plist :name)))
5207 (insert "#+BEGIN: " name)
5208 (while plist
5209 (if (eq (car plist) :name)
5210 (setq plist (cddr plist))
5211 (insert " " (prin1-to-string (pop plist)))))
5212 (insert "\n\n#+END:\n")
5213 (beginning-of-line -2)))
5215 (defun org-prepare-dblock ()
5216 "Prepare dynamic block for refresh.
5217 This empties the block, puts the cursor at the insert position and returns
5218 the property list including an extra property :name with the block name."
5219 (unless (looking-at org-dblock-start-re)
5220 (error "Not at a dynamic block"))
5221 (let* ((begdel (1+ (match-end 0)))
5222 (name (match-string 1))
5223 (params (append (list :name name)
5224 (read (concat "(" (match-string 3) ")")))))
5225 (unless (re-search-forward org-dblock-end-re nil t)
5226 (error "Dynamic block not terminated"))
5227 (delete-region begdel (match-beginning 0))
5228 (goto-char begdel)
5229 (open-line 1)
5230 params))
5232 (defun org-map-dblocks (&optional command)
5233 "Apply COMMAND to all dynamic blocks in the current buffer.
5234 If COMMAND is not given, use `org-update-dblock'."
5235 (let ((cmd (or command 'org-update-dblock))
5236 pos)
5237 (save-excursion
5238 (goto-char (point-min))
5239 (while (re-search-forward org-dblock-start-re nil t)
5240 (goto-char (setq pos (match-beginning 0)))
5241 (condition-case nil
5242 (funcall cmd)
5243 (error (message "Error during update of dynamic block")))
5244 (goto-char pos)
5245 (unless (re-search-forward org-dblock-end-re nil t)
5246 (error "Dynamic block not terminated"))))))
5248 (defun org-dblock-update (&optional arg)
5249 "User command for updating dynamic blocks.
5250 Update the dynamic block at point. With prefix ARG, update all dynamic
5251 blocks in the buffer."
5252 (interactive "P")
5253 (if arg
5254 (org-update-all-dblocks)
5255 (or (looking-at org-dblock-start-re)
5256 (org-beginning-of-dblock))
5257 (org-update-dblock)))
5259 (defun org-update-dblock ()
5260 "Update the dynamic block at point
5261 This means to empty the block, parse for parameters and then call
5262 the correct writing function."
5263 (let* ((pos (point))
5264 (params (org-prepare-dblock))
5265 (name (plist-get params :name))
5266 (cmd (intern (concat "org-dblock-write:" name))))
5267 (funcall cmd params)
5268 (goto-char pos)))
5270 (defun org-beginning-of-dblock ()
5271 "Find the beginning of the dynamic block at point.
5272 Error if there is no scuh block at point."
5273 (let ((pos (point))
5274 beg)
5275 (end-of-line 1)
5276 (if (and (re-search-backward org-dblock-start-re nil t)
5277 (setq beg (match-beginning 0))
5278 (re-search-forward org-dblock-end-re nil t)
5279 (> (match-end 0) pos))
5280 (goto-char beg)
5281 (goto-char pos)
5282 (error "Not in a dynamic block"))))
5284 (defun org-update-all-dblocks ()
5285 "Update all dynamic blocks in the buffer.
5286 This function can be used in a hook."
5287 (when (org-mode-p)
5288 (org-map-dblocks 'org-update-dblock)))
5291 ;;; Completion
5293 (defun org-complete (&optional arg)
5294 "Perform completion on word at point.
5295 At the beginning of a headline, this completes TODO keywords as given in
5296 `org-todo-keywords'.
5297 If the current word is preceded by a backslash, completes the TeX symbols
5298 that are supported for HTML support.
5299 If the current word is preceded by \"#+\", completes special words for
5300 setting file options.
5301 In the line after \"#+STARTUP:, complete valid keywords.\"
5302 At all other locations, this simply calls `ispell-complete-word'."
5303 (interactive "P")
5304 (catch 'exit
5305 (let* ((end (point))
5306 (beg1 (save-excursion
5307 (skip-chars-backward "a-zA-Z_@0-9")
5308 (point)))
5309 (beg (save-excursion
5310 (skip-chars-backward "a-zA-Z0-9_:$")
5311 (point)))
5312 (confirm (lambda (x) (stringp (car x))))
5313 (camel (equal (char-before beg) ?*))
5314 (tag (equal (char-before beg1) ?:))
5315 (texp (equal (char-before beg) ?\\))
5316 (link (equal (char-before beg) ?\[))
5317 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
5318 beg)
5319 "#+"))
5320 (startup (string-match "^#\\+STARTUP:.*"
5321 (buffer-substring (point-at-bol) (point))))
5322 (completion-ignore-case opt)
5323 (type nil)
5324 (tbl nil)
5325 (table (cond
5326 (opt
5327 (setq type :opt)
5328 (mapcar (lambda (x)
5329 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
5330 (cons (match-string 2 x) (match-string 1 x)))
5331 (org-split-string (org-get-current-options) "\n")))
5332 (startup
5333 (setq type :startup)
5334 org-startup-options)
5335 (link (append org-link-abbrev-alist-local
5336 org-link-abbrev-alist))
5337 (texp
5338 (setq type :tex)
5339 org-html-entities)
5340 ((string-match "\\`\\*+[ \t]*\\'"
5341 (buffer-substring (point-at-bol) beg))
5342 (setq type :todo)
5343 (mapcar 'list org-todo-keywords))
5344 (camel
5345 (setq type :camel)
5346 (save-excursion
5347 (goto-char (point-min))
5348 (while (re-search-forward org-todo-line-regexp nil t)
5349 (push (list
5350 (if org-file-link-context-use-camel-case
5351 (org-make-org-heading-camel (match-string 3) t)
5352 (org-make-org-heading-search-string
5353 (match-string 3) t)))
5354 tbl)))
5355 tbl)
5356 (tag (setq type :tag beg beg1)
5357 (or org-tag-alist (org-get-buffer-tags)))
5358 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
5359 (pattern (buffer-substring-no-properties beg end))
5360 (completion (try-completion pattern table confirm)))
5361 (cond ((eq completion t)
5362 (if (equal type :opt)
5363 (insert (substring (cdr (assoc (upcase pattern) table))
5364 (length pattern)))))
5365 ((null completion)
5366 (message "Can't find completion for \"%s\"" pattern)
5367 (ding))
5368 ((not (string= pattern completion))
5369 (delete-region beg end)
5370 (if (string-match " +$" completion)
5371 (setq completion (replace-match "" t t completion)))
5372 (insert completion)
5373 (if (get-buffer-window "*Completions*")
5374 (delete-window (get-buffer-window "*Completions*")))
5375 (if (assoc completion table)
5376 (if (eq type :todo) (insert " ")
5377 (if (eq type :tag) (insert ":"))))
5378 (if (and (equal type :opt) (assoc completion table))
5379 (message "%s" (substitute-command-keys
5380 "Press \\[org-complete] again to insert example settings"))))
5382 (message "Making completion list...")
5383 (let ((list (sort (all-completions pattern table confirm)
5384 'string<)))
5385 (with-output-to-temp-buffer "*Completions*"
5386 (condition-case nil
5387 ;; Protection needed for XEmacs and emacs 21
5388 (display-completion-list list pattern)
5389 (error (display-completion-list list)))))
5390 (message "Making completion list...%s" "done"))))))
5392 ;;; Comments, TODO and DEADLINE
5394 (defun org-toggle-comment ()
5395 "Change the COMMENT state of an entry."
5396 (interactive)
5397 (save-excursion
5398 (org-back-to-heading)
5399 (if (looking-at (concat outline-regexp
5400 "\\( +\\<" org-comment-string "\\>\\)"))
5401 (replace-match "" t t nil 1)
5402 (if (looking-at outline-regexp)
5403 (progn
5404 (goto-char (match-end 0))
5405 (insert " " org-comment-string))))))
5407 (defvar org-last-todo-state-is-todo nil
5408 "This is non-nil when the last TODO state change led to a TODO state.
5409 If the last change removed the TODO tag or switched to DONE, then
5410 this is nil.")
5412 (defun org-todo (&optional arg)
5413 "Change the TODO state of an item.
5414 The state of an item is given by a keyword at the start of the heading,
5415 like
5416 *** TODO Write paper
5417 *** DONE Call mom
5419 The different keywords are specified in the variable `org-todo-keywords'.
5420 By default the available states are \"TODO\" and \"DONE\".
5421 So for this example: when the item starts with TODO, it is changed to DONE.
5422 When it starts with DONE, the DONE is removed. And when neither TODO nor
5423 DONE are present, add TODO at the beginning of the heading.
5425 With prefix arg, use completion to determine the new state. With numeric
5426 prefix arg, switch to that state."
5427 (interactive "P")
5428 (save-excursion
5429 (org-back-to-heading)
5430 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5431 (or (looking-at (concat " +" org-todo-regexp " *"))
5432 (looking-at " *"))
5433 (let* ((this (match-string 1))
5434 (completion-ignore-case t)
5435 (member (member this org-todo-keywords))
5436 (tail (cdr member))
5437 (state (cond
5438 ((equal arg '(4))
5439 ;; Read a state with completion
5440 (completing-read "State: " (mapcar (lambda(x) (list x))
5441 org-todo-keywords)
5442 nil t))
5443 ((eq arg 'right)
5444 (if this
5445 (if tail (car tail) nil)
5446 (car org-todo-keywords)))
5447 ((eq arg 'left)
5448 (if (equal member org-todo-keywords)
5450 (if this
5451 (nth (- (length org-todo-keywords) (length tail) 2)
5452 org-todo-keywords)
5453 org-done-string)))
5454 (arg
5455 ;; user requests a specific state
5456 (nth (1- (prefix-numeric-value arg))
5457 org-todo-keywords))
5458 ((null member) (car org-todo-keywords))
5459 ((null tail) nil) ;; -> first entry
5460 ((eq org-todo-interpretation 'sequence)
5461 (car tail))
5462 ((memq org-todo-interpretation '(type priority))
5463 (if (eq this-command last-command)
5464 (car tail)
5465 (if (> (length tail) 0) org-done-string nil)))
5466 (t nil)))
5467 (next (if state (concat " " state " ") " ")))
5468 (replace-match next t t)
5469 (setq org-last-todo-state-is-todo
5470 (not (equal state org-done-string)))
5471 (when org-log-done
5472 (if (equal state org-done-string)
5473 (org-add-planning-info 'closed (org-current-time) 'scheduled)
5474 (if (not this)
5475 (org-add-planning-info nil nil 'closed))))
5476 ;; Fixup tag positioning
5477 (and org-auto-align-tags (org-set-tags nil t))
5478 (run-hooks 'org-after-todo-state-change-hook)))
5479 ;; Fixup cursor location if close to the keyword
5480 (if (and (outline-on-heading-p)
5481 (not (bolp))
5482 (save-excursion (beginning-of-line 1)
5483 (looking-at org-todo-line-regexp))
5484 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5485 (progn
5486 (goto-char (or (match-end 2) (match-end 1)))
5487 (just-one-space))))
5489 (defun org-show-todo-tree (arg)
5490 "Make a compact tree which shows all headlines marked with TODO.
5491 The tree will show the lines where the regexp matches, and all higher
5492 headlines above the match.
5493 With \\[universal-argument] prefix, also show the DONE entries.
5494 With a numeric prefix N, construct a sparse tree for the Nth element
5495 of `org-todo-keywords'."
5496 (interactive "P")
5497 (let ((case-fold-search nil)
5498 (kwd-re
5499 (cond ((null arg) org-not-done-regexp)
5500 ((equal arg '(4)) org-todo-regexp)
5501 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5502 (regexp-quote (nth (1- (prefix-numeric-value arg))
5503 org-todo-keywords)))
5504 (t (error "Invalid prefix argument: %s" arg)))))
5505 (message "%d TODO entries found"
5506 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5508 (defun org-deadline ()
5509 "Insert the DEADLINE: string to make a deadline.
5510 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5511 to modify it to the correct date."
5512 (interactive)
5513 (org-add-planning-info 'deadline nil 'closed))
5515 (defun org-schedule ()
5516 "Insert the SCHEDULED: string to schedule a TODO item.
5517 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5518 to modify it to the correct date."
5519 (interactive)
5520 (org-add-planning-info 'scheduled nil 'closed))
5522 (defun org-add-planning-info (what &optional time &rest remove)
5523 "Insert new timestamp with keyword in the line directly after the headline.
5524 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5525 If non is given, the user is prompted for a date.
5526 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5527 be removed."
5528 (interactive)
5529 (when what (setq time (or time (org-read-date nil 'to-time))))
5530 (when (and org-insert-labeled-timestamps-at-point
5531 (member what '(scheduled deadline)))
5532 (insert
5533 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
5534 (org-insert-time-stamp time)
5535 (setq what nil))
5536 (save-excursion
5537 (save-restriction
5538 (let (col list elt ts buffer-invisibility-spec)
5539 (org-back-to-heading t)
5540 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5541 (goto-char (match-end 1))
5542 (setq col (current-column))
5543 (goto-char (1+ (match-end 0)))
5544 (if (and (not (looking-at outline-regexp))
5545 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5546 "[^\r\n]*"))
5547 (not (equal (match-string 1) org-clock-string)))
5548 (narrow-to-region (match-beginning 0) (match-end 0))
5549 (insert "\n")
5550 (backward-char 1)
5551 (narrow-to-region (point) (point))
5552 (indent-to-column col))
5553 ;; Check if we have to remove something.
5554 (setq list (cons what remove))
5555 (while list
5556 (setq elt (pop list))
5557 (goto-char (point-min))
5558 (when (or (and (eq elt 'scheduled)
5559 (re-search-forward org-scheduled-time-regexp nil t))
5560 (and (eq elt 'deadline)
5561 (re-search-forward org-deadline-time-regexp nil t))
5562 (and (eq elt 'closed)
5563 (re-search-forward org-closed-time-regexp nil t)))
5564 (replace-match "")
5565 (if (looking-at " +") (replace-match ""))))
5566 (goto-char (point-max))
5567 (when what
5568 (insert
5569 (if (not (equal (char-before) ?\ )) " " "")
5570 (cond ((eq what 'scheduled) org-scheduled-string)
5571 ((eq what 'deadline) org-deadline-string)
5572 ((eq what 'closed) org-closed-string))
5573 " ")
5574 (org-insert-time-stamp time nil (eq what 'closed))
5575 (end-of-line 1)
5576 (org-add-log-maybe 'done))
5577 (goto-char (point-min))
5578 (widen)
5579 (if (looking-at "[ \t]+\r?\n")
5580 (replace-match ""))
5581 ts))))
5583 (defvar org-log-note-marker (make-marker))
5584 (defvar org-log-note-purpose nil)
5585 (defvar org-log-note-window-configuration nil)
5587 (defun org-add-log-maybe (&optional purpose)
5588 (when (and (listp org-log-done)
5589 (memq purpose org-log-done))
5590 (move-marker org-log-note-marker (point))
5591 (setq org-log-note-purpose purpose)
5592 (add-hook 'post-command-hook 'org-add-log-note 'append)))
5594 (defun org-add-log-note (&optional purpose)
5595 "Pop up a window for taking a note, and add this note later at point."
5596 (remove-hook 'post-command-hook 'org-add-log-note)
5597 (setq org-log-note-window-configuration (current-window-configuration))
5598 (delete-other-windows)
5599 (switch-to-buffer (marker-buffer org-log-note-marker))
5600 (goto-char org-log-note-marker)
5601 (switch-to-buffer-other-window "*Org Note*")
5602 (erase-buffer)
5603 (org-mode)
5604 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
5605 (cond
5606 ((eq org-log-note-purpose 'clock-out) "stopped clock")
5607 ((eq org-log-note-purpose 'done) "closed todo item")
5608 (t (error "This should not happen")))))
5609 (org-set-local 'org-finish-function 'org-store-log-note))
5611 (defun org-store-log-note ()
5612 "Finish taking a log note, and insert it to where it belongs."
5613 (let ((txt (buffer-string))
5614 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
5615 lines ind)
5616 (kill-buffer (current-buffer))
5617 (if (string-match "^#.*\n[ \t\\n]*" txt)
5618 (setq txt (replace-match "" t t txt)))
5619 (when (string-match "\\S-" txt)
5620 (if (string-match "\\s-+\\'" txt)
5621 (setq txt (replace-match "" t t txt)))
5622 (setq lines (org-split-string txt "\n"))
5623 (and note (string-match "\\S-" note) (push note lines))
5624 (save-excursion
5625 (set-buffer (marker-buffer org-log-note-marker))
5626 (save-excursion
5627 (goto-char org-log-note-marker)
5628 (if (not (bolp)) (newline))
5629 (indent-relative t)
5630 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
5631 (insert " - " (pop lines))
5632 (while lines
5633 (insert "\n" ind (pop lines))))))
5634 (set-window-configuration org-log-note-window-configuration)))
5636 (defvar org-occur-highlights nil)
5637 (make-variable-buffer-local 'org-occur-highlights)
5639 (defun org-occur (regexp &optional keep-previous callback)
5640 "Make a compact tree which shows all matches of REGEXP.
5641 The tree will show the lines where the regexp matches, and all higher
5642 headlines above the match. It will also show the heading after the match,
5643 to make sure editing the matching entry is easy.
5644 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
5645 call to `org-occur' will be kept, to allow stacking of calls to this
5646 command.
5647 If CALLBACK is non-nil, it is a function which is called to confirm
5648 that the match should indeed be shown."
5649 (interactive "sRegexp: \nP")
5650 (or keep-previous (org-remove-occur-highlights nil nil t))
5651 (let ((cnt 0))
5652 (save-excursion
5653 (goto-char (point-min))
5654 (if (or (not keep-previous) ; do not want to keep
5655 (not org-occur-highlights)) ; no previous matches
5656 ;; hide everything
5657 (org-overview))
5658 (while (re-search-forward regexp nil t)
5659 (when (or (not callback)
5660 (save-match-data (funcall callback)))
5661 (setq cnt (1+ cnt))
5662 (org-highlight-new-match (match-beginning 0) (match-end 0))
5663 (org-show-context 'occur-tree))))
5664 (when org-remove-highlights-with-change
5665 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5666 nil 'local))
5667 (unless org-sparse-tree-open-archived-trees
5668 (org-hide-archived-subtrees (point-min) (point-max)))
5669 (run-hooks 'org-occur-hook)
5670 (if (interactive-p)
5671 (message "%d match(es) for regexp %s" cnt regexp))
5672 cnt))
5674 (defun org-show-context (&optional key siblings)
5675 "Make sure point and context and visible.
5676 How much context is shown depends upon the variables
5677 `org-show-hierarchy-above' and `org-show-following-heading'.
5678 When SIBLINGS is non-nil, show all siblings on each hierarchy level."
5679 (let ((heading-p (org-on-heading-p t))
5680 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
5681 (following-p (org-get-alist-option org-show-following-heading key)))
5682 (catch 'exit
5683 ;; Show heading or entry text
5684 (if heading-p
5685 (org-flag-heading nil) ; only show the heading
5686 (and (or (org-invisible-p) (org-invisible-p2))
5687 (org-show-hidden-entry))) ; show entire entry
5688 (when following-p
5689 ;; Show next sibling, or heading below text
5690 (save-excursion
5691 (and (if heading-p (org-goto-sibling) (outline-next-heading))
5692 (org-flag-heading nil))))
5693 (when hierarchy-p
5694 ;; show all higher headings, possibly with siblings
5695 (save-excursion
5696 (while (and (condition-case nil
5697 (progn (org-up-heading-all 1) t)
5698 (error nil))
5699 (not (bobp)))
5700 (org-flag-heading nil)
5701 (when siblings
5702 (save-excursion
5703 (while (org-goto-sibling) (org-flag-heading nil)))
5704 (save-excursion
5705 (while (org-goto-sibling 'previous)
5706 (org-flag-heading nil))))))))))
5708 (defun org-reveal (&optional siblings)
5709 "Show current entry, hierarchy above it, and the following headline.
5710 This can be used to show a consistent set of context around locations
5711 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
5712 not t for the search context.
5714 With optional argument SIBLINGS, on each level of the hierarchy all
5715 siblings are shown. This repairs the tree structure so what it would
5716 look like when opend with successive calls to `org-cycle'."
5717 (interactive "P")
5718 (let ((org-show-hierarchy-above t)
5719 (org-show-following-heading t))
5720 (org-show-context nil siblings)))
5722 ;; Overlay compatibility functions
5723 (defun org-make-overlay (beg end &optional buffer)
5724 (if (featurep 'xemacs)
5725 (make-extent beg end buffer)
5726 (make-overlay beg end buffer)))
5727 (defun org-delete-overlay (ovl)
5728 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5729 (defun org-detach-overlay (ovl)
5730 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5731 (defun org-move-overlay (ovl beg end &optional buffer)
5732 (if (featurep 'xemacs)
5733 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
5734 (move-overlay ovl beg end buffer)))
5735 (defun org-overlay-put (ovl prop value)
5736 (if (featurep 'xemacs)
5737 (set-extent-property ovl prop value)
5738 (overlay-put ovl prop value)))
5739 (defun org-overlay-display (ovl text &optional face)
5740 "Make overlay OVL display TEXT with face FACE."
5741 (if (featurep 'xemacs)
5742 (let ((gl (make-glyph text)))
5743 (and face (set-glyph-face gl face))
5744 (set-extent-property ovl 'invisible t)
5745 (set-extent-property ovl 'end-glyph gl))
5746 (overlay-put ovl 'display text)
5747 (if face (overlay-put ovl 'face face))))
5748 (defun org-overlay-get (ovl prop)
5749 (if (featurep 'xemacs)
5750 (extent-property ovl prop)
5751 (overlay-get ovl prop)))
5752 (defun org-overlays-at (pos)
5753 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5754 (defun org-overlays-in (&optional start end)
5755 (if (featurep 'xemacs)
5756 (extent-list nil start end)
5757 (overlays-in start end)))
5758 (defun org-overlay-start (o)
5759 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5760 (defun org-overlay-end (o)
5761 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5763 (defun org-highlight-new-match (beg end)
5764 "Highlight from BEG to END and mark the highlight is an occur headline."
5765 (let ((ov (org-make-overlay beg end)))
5766 (org-overlay-put ov 'face 'secondary-selection)
5767 (push ov org-occur-highlights)))
5769 (defvar org-inhibit-highlight-removal nil)
5770 (defun org-remove-occur-highlights (&optional beg end noremove)
5771 "Remove the occur highlights from the buffer.
5772 BEG and END are ignored. If NOREMOVE is nil, remove this function
5773 from the `before-change-functions' in the current buffer."
5774 (interactive)
5775 (unless org-inhibit-highlight-removal
5776 (mapc 'org-delete-overlay org-occur-highlights)
5777 (setq org-occur-highlights nil)
5778 (unless noremove
5779 (remove-hook 'before-change-functions
5780 'org-remove-occur-highlights 'local))))
5782 ;;; Priorities
5784 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5785 "Regular expression matching the priority indicator.")
5787 (defvar org-remove-priority-next-time nil)
5789 (defun org-priority-up ()
5790 "Increase the priority of the current item."
5791 (interactive)
5792 (org-priority 'up))
5794 (defun org-priority-down ()
5795 "Decrease the priority of the current item."
5796 (interactive)
5797 (org-priority 'down))
5799 (defun org-priority (&optional action)
5800 "Change the priority of an item by ARG.
5801 ACTION can be set, up, or down."
5802 (interactive)
5803 (setq action (or action 'set))
5804 (let (current new news have remove)
5805 (save-excursion
5806 (org-back-to-heading)
5807 (if (looking-at org-priority-regexp)
5808 (setq current (string-to-char (match-string 2))
5809 have t)
5810 (setq current org-default-priority))
5811 (cond
5812 ((eq action 'set)
5813 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5814 (setq new (read-char-exclusive))
5815 (cond ((equal new ?\ ) (setq remove t))
5816 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5817 (error "Priority must be between `%c' and `%c'"
5818 ?A org-lowest-priority))))
5819 ((eq action 'up)
5820 (setq new (1- current)))
5821 ((eq action 'down)
5822 (setq new (1+ current)))
5823 (t (error "Invalid action")))
5824 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5825 (setq news (format "%c" new))
5826 (if have
5827 (if remove
5828 (replace-match "" t t nil 1)
5829 (replace-match news t t nil 2))
5830 (if remove
5831 (error "No priority cookie found in line")
5832 (looking-at org-todo-line-regexp)
5833 (if (match-end 2)
5834 (progn
5835 (goto-char (match-end 2))
5836 (insert " [#" news "]"))
5837 (goto-char (match-beginning 3))
5838 (insert "[#" news "] ")))))
5839 (if remove
5840 (message "Priority removed")
5841 (message "Priority of current item set to %s" news))))
5844 (defun org-get-priority (s)
5845 "Find priority cookie and return priority."
5846 (save-match-data
5847 (if (not (string-match org-priority-regexp s))
5848 (* 1000 (- org-lowest-priority org-default-priority))
5849 (* 1000 (- org-lowest-priority
5850 (string-to-char (match-string 2 s)))))))
5852 ;;; Timestamps
5854 (defvar org-last-changed-timestamp nil)
5856 (defun org-time-stamp (arg)
5857 "Prompt for a date/time and insert a time stamp.
5858 If the user specifies a time like HH:MM, or if this command is called
5859 with a prefix argument, the time stamp will contain date and time.
5860 Otherwise, only the date will be included. All parts of a date not
5861 specified by the user will be filled in from the current date/time.
5862 So if you press just return without typing anything, the time stamp
5863 will represent the current date/time. If there is already a timestamp
5864 at the cursor, it will be modified."
5865 (interactive "P")
5866 (let (org-time-was-given time)
5867 (cond
5868 ((and (org-at-timestamp-p)
5869 (eq last-command 'org-time-stamp)
5870 (eq this-command 'org-time-stamp))
5871 (insert "--")
5872 (setq time (let ((this-command this-command))
5873 (org-read-date arg 'totime)))
5874 (org-insert-time-stamp time (or org-time-was-given arg)))
5875 ((org-at-timestamp-p)
5876 (setq time (let ((this-command this-command))
5877 (org-read-date arg 'totime)))
5878 (when (org-at-timestamp-p) ; just to get the match data
5879 (replace-match "")
5880 (setq org-last-changed-timestamp
5881 (org-insert-time-stamp time (or org-time-was-given arg))))
5882 (message "Timestamp updated"))
5884 (setq time (let ((this-command this-command))
5885 (org-read-date arg 'totime)))
5886 (org-insert-time-stamp time (or org-time-was-given arg))))))
5888 (defun org-time-stamp-inactive (&optional arg)
5889 "Insert an inactive time stamp.
5890 An inactive time stamp is enclosed in square brackets instead of angle
5891 brackets. It is inactive in the sense that it does not trigger agenda entries,
5892 does not link to the calendar and cannot be changed with the S-cursor keys.
5893 So these are more for recording a certain time/date."
5894 (interactive "P")
5895 (let (org-time-was-given time)
5896 (setq time (org-read-date arg 'totime))
5897 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
5899 (defvar org-date-ovl (org-make-overlay 1 1))
5900 (org-overlay-put org-date-ovl 'face 'org-warning)
5901 (org-detach-overlay org-date-ovl)
5903 (defun org-read-date (&optional with-time to-time from-string)
5904 "Read a date and make things smooth for the user.
5905 The prompt will suggest to enter an ISO date, but you can also enter anything
5906 which will at least partially be understood by `parse-time-string'.
5907 Unrecognized parts of the date will default to the current day, month, year,
5908 hour and minute. For example,
5909 3-2-5 --> 2003-02-05
5910 feb 15 --> currentyear-02-15
5911 sep 12 9 --> 2009-09-12
5912 12:45 --> today 12:45
5913 22 sept 0:34 --> currentyear-09-22 0:34
5914 12 --> currentyear-currentmonth-12
5915 Fri --> nearest Friday (today or later)
5916 etc.
5917 The function understands only English month and weekday abbreviations,
5918 but this can be configured with the variables `parse-time-months' and
5919 `parse-time-weekdays'.
5921 While prompting, a calendar is popped up - you can also select the
5922 date with the mouse (button 1). The calendar shows a period of three
5923 months. To scroll it to other months, use the keys `>' and `<'.
5924 If you don't like the calendar, turn it off with
5925 \(setq org-popup-calendar-for-date-prompt nil)
5927 With optional argument TO-TIME, the date will immediately be converted
5928 to an internal time.
5929 With an optional argument WITH-TIME, the prompt will suggest to also
5930 insert a time. Note that when WITH-TIME is not set, you can still
5931 enter a time, and this function will inform the calling routine about
5932 this change. The calling routine may then choose to change the format
5933 used to insert the time stamp into the buffer to include the time."
5934 (require 'parse-time)
5935 (let* ((org-time-stamp-rounding-minutes
5936 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5937 (ct (org-current-time))
5938 (default-time
5939 ;; Default time is either today, or, when entering a range,
5940 ;; the range start.
5941 (if (save-excursion
5942 (re-search-backward
5943 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5944 (- (point) 20) t))
5945 (apply
5946 'encode-time
5947 (mapcar (lambda(x) (or x 0))
5948 (parse-time-string (match-string 1))))
5949 ct))
5950 (calendar-move-hook nil)
5951 (view-diary-entries-initially nil)
5952 (view-calendar-holidays-initially nil)
5953 (timestr (format-time-string
5954 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5955 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5956 ans ans1 ans2
5957 second minute hour day month year tl wday wday1)
5959 (cond
5960 (from-string (setq ans from-string))
5961 (org-popup-calendar-for-date-prompt
5962 (save-excursion
5963 (save-window-excursion
5964 (calendar)
5965 (calendar-forward-day (- (time-to-days default-time)
5966 (calendar-absolute-from-gregorian
5967 (calendar-current-date))))
5968 (org-eval-in-calendar nil)
5969 (let* ((old-map (current-local-map))
5970 (map (copy-keymap calendar-mode-map))
5971 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5972 (define-key map (kbd "RET") 'org-calendar-select)
5973 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5974 'org-calendar-select-mouse)
5975 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5976 'org-calendar-select-mouse)
5977 (define-key minibuffer-local-map [(meta shift left)]
5978 (lambda () (interactive)
5979 (org-eval-in-calendar '(calendar-backward-month 1))))
5980 (define-key minibuffer-local-map [(meta shift right)]
5981 (lambda () (interactive)
5982 (org-eval-in-calendar '(calendar-forward-month 1))))
5983 (define-key minibuffer-local-map [(shift up)]
5984 (lambda () (interactive)
5985 (org-eval-in-calendar '(calendar-backward-week 1))))
5986 (define-key minibuffer-local-map [(shift down)]
5987 (lambda () (interactive)
5988 (org-eval-in-calendar '(calendar-forward-week 1))))
5989 (define-key minibuffer-local-map [(shift left)]
5990 (lambda () (interactive)
5991 (org-eval-in-calendar '(calendar-backward-day 1))))
5992 (define-key minibuffer-local-map [(shift right)]
5993 (lambda () (interactive)
5994 (org-eval-in-calendar '(calendar-forward-day 1))))
5995 (define-key minibuffer-local-map ">"
5996 (lambda () (interactive)
5997 (org-eval-in-calendar '(scroll-calendar-left 1))))
5998 (define-key minibuffer-local-map "<"
5999 (lambda () (interactive)
6000 (org-eval-in-calendar '(scroll-calendar-right 1))))
6001 (unwind-protect
6002 (progn
6003 (use-local-map map)
6004 (setq ans (read-string prompt "" nil nil))
6005 (if (not (string-match "\\S-" ans)) (setq ans nil))
6006 (setq ans (or ans1 ans ans2)))
6007 (use-local-map old-map))))))
6008 (t ; Naked prompt only
6009 (setq ans (read-string prompt "" nil timestr))))
6010 (org-detach-overlay org-date-ovl)
6012 (if (string-match
6013 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
6014 (progn
6015 (setq year (if (match-end 2)
6016 (string-to-number (match-string 2 ans))
6017 (string-to-number (format-time-string "%Y")))
6018 month (string-to-number (match-string 3 ans))
6019 day (string-to-number (match-string 4 ans)))
6020 (if (< year 100) (setq year (+ 2000 year)))
6021 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
6022 t nil ans))))
6023 (setq tl (parse-time-string ans)
6024 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
6025 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
6026 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
6027 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
6028 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
6029 second (or (nth 0 tl) 0)
6030 wday (nth 6 tl))
6031 (when (and wday (not (nth 3 tl)))
6032 ;; Weekday was given, but no day, so pick that day in the week
6033 ;; on or after the derived date.
6034 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
6035 (unless (equal wday wday1)
6036 (setq day (+ day (% (- wday wday1 -7) 7)))))
6037 (if (and (boundp 'org-time-was-given)
6038 (nth 2 tl))
6039 (setq org-time-was-given t))
6040 (if (< year 100) (setq year (+ 2000 year)))
6041 (if to-time
6042 (encode-time second minute hour day month year)
6043 (if (or (nth 1 tl) (nth 2 tl))
6044 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
6045 (format "%04d-%02d-%02d" year month day)))))
6047 (defun org-eval-in-calendar (form)
6048 "Eval FORM in the calendar window and return to current window.
6049 Also, store the cursor date in variable ans2."
6050 (let ((sw (selected-window)))
6051 (select-window (get-buffer-window "*Calendar*"))
6052 (eval form)
6053 (when (calendar-cursor-to-date)
6054 (let* ((date (calendar-cursor-to-date))
6055 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6056 (setq ans2 (format-time-string "%Y-%m-%d" time))))
6057 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
6058 (select-window sw)))
6060 (defun org-calendar-select ()
6061 "Return to `org-read-date' with the date currently selected.
6062 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6063 (interactive)
6064 (when (calendar-cursor-to-date)
6065 (let* ((date (calendar-cursor-to-date))
6066 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6067 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6068 (if (active-minibuffer-window) (exit-minibuffer))))
6070 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
6071 "Insert a date stamp for the date given by the internal TIME.
6072 WITH-HM means, use the stamp format that includes the time of the day.
6073 INACTIVE means use square brackets instead of angular ones, so that the
6074 stamp will not contribute to the agenda.
6075 PRE and POST are optional strings to be inserted before and after the
6076 stamp.
6077 The command returns the inserted time stamp."
6078 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
6079 stamp)
6080 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
6081 (insert (or pre ""))
6082 (insert (setq stamp (format-time-string fmt time)))
6083 (insert (or post ""))
6084 stamp))
6086 (defun org-toggle-time-stamp-overlays ()
6087 "Toggle the use of custom time stamp formats."
6088 (interactive)
6089 (setq org-display-custom-times (not org-display-custom-times))
6090 (unless org-display-custom-times
6091 (let ((p (point-min)) (bmp (buffer-modified-p)))
6092 (while (setq p (next-single-property-change p 'display))
6093 (if (and (get-text-property p 'display)
6094 (eq (get-text-property p 'face) 'org-date))
6095 (remove-text-properties
6096 p (setq p (next-single-property-change p 'display))
6097 '(display t))))
6098 (set-buffer-modified-p bmp)))
6099 (if (featurep 'xemacs)
6100 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
6101 (org-restart-font-lock)
6102 (setq org-table-may-need-update t)
6103 (if org-display-custom-times
6104 (message "Time stamps are overlayed with custom format")
6105 (message "Time stamp overlays removed")))
6107 (defun org-display-custom-time (beg end)
6108 "Overlay modified time stamp format over timestamp between BED and END."
6109 (let* ((t1 (save-match-data
6110 (org-parse-time-string (buffer-substring beg end) t)))
6111 (w1 (- end beg))
6112 (with-hm (and (nth 1 t1) (nth 2 t1)))
6113 (inactive (= (char-before (1- beg)) ?\[))
6114 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
6115 (time (mapcar (lambda (x) (or x 0)) t1))
6116 (str (org-add-props
6117 (format-time-string
6118 (substring tf 1 -1) (apply 'encode-time time))
6119 nil 'mouse-face 'highlight))
6120 (w2 (length str)))
6121 (if (not (= w2 w1))
6122 (add-text-properties (1+ beg) (+ 2 beg)
6123 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
6124 (if (featurep 'xemacs)
6125 (progn
6126 (put-text-property beg end 'invisible t)
6127 (put-text-property beg end 'end-glyph (make-glyph str)))
6128 (put-text-property beg end 'display str))))
6130 (defun org-days-to-time (timestamp-string)
6131 "Difference between TIMESTAMP-STRING and now in days."
6132 (- (time-to-days (org-time-string-to-time timestamp-string))
6133 (time-to-days (current-time))))
6135 (defun org-deadline-close (timestamp-string &optional ndays)
6136 "Is the time in TIMESTAMP-STRING close to the current date?"
6137 (and (< (org-days-to-time timestamp-string)
6138 (or ndays org-deadline-warning-days))
6139 (not (org-entry-is-done-p))))
6141 (defun org-calendar-select-mouse (ev)
6142 "Return to `org-read-date' with the date currently selected.
6143 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6144 (interactive "e")
6145 (mouse-set-point ev)
6146 (when (calendar-cursor-to-date)
6147 (let* ((date (calendar-cursor-to-date))
6148 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6149 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6150 (if (active-minibuffer-window) (exit-minibuffer))))
6152 (defun org-check-deadlines (ndays)
6153 "Check if there are any deadlines due or past due.
6154 A deadline is considered due if it happens within `org-deadline-warning-days'
6155 days from today's date. If the deadline appears in an entry marked DONE,
6156 it is not shown. The prefix arg NDAYS can be used to test that many
6157 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
6158 (interactive "P")
6159 (let* ((org-warn-days
6160 (cond
6161 ((equal ndays '(4)) 100000)
6162 (ndays (prefix-numeric-value ndays))
6163 (t org-deadline-warning-days)))
6164 (case-fold-search nil)
6165 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
6166 (callback
6167 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
6169 (message "%d deadlines past-due or due within %d days"
6170 (org-occur regexp nil callback)
6171 org-warn-days)))
6173 (defun org-evaluate-time-range (&optional to-buffer)
6174 "Evaluate a time range by computing the difference between start and end.
6175 Normally the result is just printed in the echo area, but with prefix arg
6176 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
6177 If the time range is actually in a table, the result is inserted into the
6178 next column.
6179 For time difference computation, a year is assumed to be exactly 365
6180 days in order to avoid rounding problems."
6181 (interactive "P")
6183 (org-clock-update-time-maybe)
6184 (save-excursion
6185 (unless (org-at-date-range-p)
6186 (goto-char (point-at-bol))
6187 (re-search-forward org-tr-regexp (point-at-eol) t))
6188 (if (not (org-at-date-range-p))
6189 (error "Not at a time-stamp range, and none found in current line")))
6190 (let* ((ts1 (match-string 1))
6191 (ts2 (match-string 2))
6192 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
6193 (match-end (match-end 0))
6194 (time1 (org-time-string-to-time ts1))
6195 (time2 (org-time-string-to-time ts2))
6196 (t1 (time-to-seconds time1))
6197 (t2 (time-to-seconds time2))
6198 (diff (abs (- t2 t1)))
6199 (negative (< (- t2 t1) 0))
6200 ;; (ys (floor (* 365 24 60 60)))
6201 (ds (* 24 60 60))
6202 (hs (* 60 60))
6203 (fy "%dy %dd %02d:%02d")
6204 (fy1 "%dy %dd")
6205 (fd "%dd %02d:%02d")
6206 (fd1 "%dd")
6207 (fh "%02d:%02d")
6208 y d h m align)
6209 (if havetime
6210 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6212 d (floor (/ diff ds)) diff (mod diff ds)
6213 h (floor (/ diff hs)) diff (mod diff hs)
6214 m (floor (/ diff 60)))
6215 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6217 d (floor (+ (/ diff ds) 0.5))
6218 h 0 m 0))
6219 (if (not to-buffer)
6220 (message (org-make-tdiff-string y d h m))
6221 (when (org-at-table-p)
6222 (goto-char match-end)
6223 (setq align t)
6224 (and (looking-at " *|") (goto-char (match-end 0))))
6225 (if (looking-at
6226 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
6227 (replace-match ""))
6228 (if negative (insert " -"))
6229 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
6230 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
6231 (insert " " (format fh h m))))
6232 (if align (org-table-align))
6233 (message "Time difference inserted")))))
6235 (defun org-make-tdiff-string (y d h m)
6236 (let ((fmt "")
6237 (l nil))
6238 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
6239 l (push y l)))
6240 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
6241 l (push d l)))
6242 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
6243 l (push h l)))
6244 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
6245 l (push m l)))
6246 (apply 'format fmt (nreverse l))))
6248 (defun org-time-string-to-time (s)
6249 (apply 'encode-time (org-parse-time-string s)))
6251 (defun org-parse-time-string (s &optional nodefault)
6252 "Parse the standard Org-mode time string.
6253 This should be a lot faster than the normal `parse-time-string'.
6254 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
6255 hour and minute fields will be nil if not given."
6256 (if (string-match org-ts-regexp1 s)
6257 (list 0
6258 (if (or (match-beginning 8) (not nodefault))
6259 (string-to-number (or (match-string 8 s) "0")))
6260 (if (or (match-beginning 7) (not nodefault))
6261 (string-to-number (or (match-string 7 s) "0")))
6262 (string-to-number (match-string 4 s))
6263 (string-to-number (match-string 3 s))
6264 (string-to-number (match-string 2 s))
6265 nil nil nil)
6266 (make-list 9 0)))
6268 (defun org-timestamp-up (&optional arg)
6269 "Increase the date item at the cursor by one.
6270 If the cursor is on the year, change the year. If it is on the month or
6271 the day, change that.
6272 With prefix ARG, change by that many units."
6273 (interactive "p")
6274 (org-timestamp-change (prefix-numeric-value arg)))
6276 (defun org-timestamp-down (&optional arg)
6277 "Decrease the date item at the cursor by one.
6278 If the cursor is on the year, change the year. If it is on the month or
6279 the day, change that.
6280 With prefix ARG, change by that many units."
6281 (interactive "p")
6282 (org-timestamp-change (- (prefix-numeric-value arg))))
6284 (defun org-timestamp-up-day (&optional arg)
6285 "Increase the date in the time stamp by one day.
6286 With prefix ARG, change that many days."
6287 (interactive "p")
6288 (if (and (not (org-at-timestamp-p t))
6289 (org-on-heading-p))
6290 (org-todo 'up)
6291 (org-timestamp-change (prefix-numeric-value arg) 'day)))
6293 (defun org-timestamp-down-day (&optional arg)
6294 "Decrease the date in the time stamp by one day.
6295 With prefix ARG, change that many days."
6296 (interactive "p")
6297 (if (and (not (org-at-timestamp-p t))
6298 (org-on-heading-p))
6299 (org-todo 'down)
6300 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
6302 (defsubst org-pos-in-match-range (pos n)
6303 (and (match-beginning n)
6304 (<= (match-beginning n) pos)
6305 (>= (match-end n) pos)))
6307 (defun org-at-timestamp-p (&optional inactive-ok)
6308 "Determine if the cursor is in or at a timestamp."
6309 (interactive)
6310 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
6311 (pos (point))
6312 (ans (or (looking-at tsr)
6313 (save-excursion
6314 (skip-chars-backward "^[<\n\r\t")
6315 (if (> (point) 1) (backward-char 1))
6316 (and (looking-at tsr)
6317 (> (- (match-end 0) pos) -1))))))
6318 (and (boundp 'org-ts-what)
6319 (setq org-ts-what
6320 (cond
6321 ((org-pos-in-match-range pos 2) 'year)
6322 ((org-pos-in-match-range pos 3) 'month)
6323 ((org-pos-in-match-range pos 7) 'hour)
6324 ((org-pos-in-match-range pos 8) 'minute)
6325 ((or (org-pos-in-match-range pos 4)
6326 (org-pos-in-match-range pos 5)) 'day)
6327 (t 'day))))
6328 ans))
6330 (defun org-timestamp-change (n &optional what)
6331 "Change the date in the time stamp at point.
6332 The date will be changed by N times WHAT. WHAT can be `day', `month',
6333 `year', `minute', `second'. If WHAT is not given, the cursor position
6334 in the timestamp determines what will be changed."
6335 (let ((pos (point))
6336 with-hm inactive
6337 org-ts-what
6338 ts time time0)
6339 (if (not (org-at-timestamp-p t))
6340 (error "Not at a timestamp"))
6341 (if (and (not what) (not (eq org-ts-what 'day))
6342 org-display-custom-times
6343 (get-text-property (point) 'display)
6344 (not (get-text-property (1- (point)) 'display)))
6345 (setq org-ts-what 'day))
6346 (setq org-ts-what (or what org-ts-what)
6347 with-hm (<= (abs (- (cdr org-ts-lengths)
6348 (- (match-end 0) (match-beginning 0))))
6350 inactive (= (char-after (match-beginning 0)) ?\[)
6351 ts (match-string 0))
6352 (replace-match "")
6353 (setq time0 (org-parse-time-string ts))
6354 (setq time
6355 (apply 'encode-time
6356 (append
6357 (list (or (car time0) 0))
6358 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
6359 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
6360 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
6361 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
6362 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
6363 (nthcdr 6 time0))))
6364 (if (eq what 'calendar)
6365 (let ((cal-date
6366 (save-excursion
6367 (save-match-data
6368 (set-buffer "*Calendar*")
6369 (calendar-cursor-to-date)))))
6370 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
6371 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
6372 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
6373 (setcar time0 (or (car time0) 0))
6374 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
6375 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
6376 (setq time (apply 'encode-time time0))))
6377 (setq org-last-changed-timestamp
6378 (org-insert-time-stamp time with-hm inactive))
6379 (org-clock-update-time-maybe)
6380 (goto-char pos)
6381 ;; Try to recenter the calendar window, if any
6382 (if (and org-calendar-follow-timestamp-change
6383 (get-buffer-window "*Calendar*" t)
6384 (memq org-ts-what '(day month year)))
6385 (org-recenter-calendar (time-to-days time)))))
6387 (defun org-recenter-calendar (date)
6388 "If the calendar is visible, recenter it to DATE."
6389 (let* ((win (selected-window))
6390 (cwin (get-buffer-window "*Calendar*" t))
6391 (calendar-move-hook nil))
6392 (when cwin
6393 (select-window cwin)
6394 (calendar-goto-date (if (listp date) date
6395 (calendar-gregorian-from-absolute date)))
6396 (select-window win))))
6398 (defun org-goto-calendar (&optional arg)
6399 "Go to the Emacs calendar at the current date.
6400 If there is a time stamp in the current line, go to that date.
6401 A prefix ARG can be used to force the current date."
6402 (interactive "P")
6403 (let ((tsr org-ts-regexp) diff
6404 (calendar-move-hook nil)
6405 (view-calendar-holidays-initially nil)
6406 (view-diary-entries-initially nil))
6407 (if (or (org-at-timestamp-p)
6408 (save-excursion
6409 (beginning-of-line 1)
6410 (looking-at (concat ".*" tsr))))
6411 (let ((d1 (time-to-days (current-time)))
6412 (d2 (time-to-days
6413 (org-time-string-to-time (match-string 1)))))
6414 (setq diff (- d2 d1))))
6415 (calendar)
6416 (calendar-goto-today)
6417 (if (and diff (not arg)) (calendar-forward-day diff))))
6419 (defun org-date-from-calendar ()
6420 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
6421 If there is already a time stamp at the cursor position, update it."
6422 (interactive)
6423 (org-timestamp-change 0 'calendar))
6425 ;;; The clock for measuring work time.
6427 (defvar org-clock-marker (make-marker)
6428 "Marker recording the last clock-in.")
6430 (defun org-clock-in ()
6431 "Start the clock on the current item.
6432 If necessary, clock-out of the currently active clock."
6433 (interactive)
6434 (org-clock-out t)
6435 (let (ts)
6436 (save-excursion
6437 (org-back-to-heading t)
6438 (beginning-of-line 2)
6439 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6440 (not (equal (match-string 1) org-clock-string)))
6441 (beginning-of-line 1))
6442 (insert "\n") (backward-char 1)
6443 (indent-relative)
6444 (insert org-clock-string " ")
6445 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6446 (move-marker org-clock-marker (point))
6447 (message "Clock started at %s" ts))))
6449 (defun org-clock-out (&optional fail-quietly)
6450 "Stop the currently running clock.
6451 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
6452 (interactive)
6453 (catch 'exit
6454 (if (not (marker-buffer org-clock-marker))
6455 (if fail-quietly (throw 'exit t) (error "No active clock")))
6456 (let (ts te s h m)
6457 (save-excursion
6458 (set-buffer (marker-buffer org-clock-marker))
6459 (goto-char org-clock-marker)
6460 (beginning-of-line 1)
6461 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6462 (equal (match-string 1) org-clock-string))
6463 (setq ts (match-string 2))
6464 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
6465 (goto-char org-clock-marker)
6466 (insert "--")
6467 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6468 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
6469 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
6470 h (floor (/ s 3600))
6471 s (- s (* 3600 h))
6472 m (floor (/ s 60))
6473 s (- s (* 60 s)))
6474 (insert " => " (format "%2d:%02d" h m))
6475 (move-marker org-clock-marker nil)
6476 (org-add-log-maybe 'clock-out)
6477 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
6479 (defun org-clock-cancel ()
6480 "Cancel the running clock be removing the start timestamp."
6481 (interactive)
6482 (if (not (marker-buffer org-clock-marker))
6483 (error "No active clock"))
6484 (save-excursion
6485 (set-buffer (marker-buffer org-clock-marker))
6486 (goto-char org-clock-marker)
6487 (delete-region (1- (point-at-bol)) (point-at-eol)))
6488 (message "Clock canceled"))
6490 (defvar org-clock-file-total-minutes nil
6491 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
6492 (make-variable-buffer-local 'org-clock-file-total-minutes)
6494 (defun org-clock-sum (&optional tstart tend)
6495 "Sum the times for each subtree.
6496 Puts the resulting times in minutes as a text property on each headline."
6497 (interactive)
6498 (let* ((bmp (buffer-modified-p))
6499 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
6500 org-clock-string
6501 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
6502 (lmax 30)
6503 (ltimes (make-vector lmax 0))
6504 (t1 0)
6505 (level 0)
6506 ts te dt
6507 time)
6508 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
6509 (save-excursion
6510 (goto-char (point-max))
6511 (while (re-search-backward re nil t)
6512 (if (match-end 2)
6513 ;; A time
6514 (setq ts (match-string 2)
6515 te (match-string 3)
6516 ts (time-to-seconds
6517 (apply 'encode-time (org-parse-time-string ts)))
6518 te (time-to-seconds
6519 (apply 'encode-time (org-parse-time-string te)))
6520 ts (if tstart (max ts tstart) ts)
6521 te (if tend (min te tend) te)
6522 dt (- te ts)
6523 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
6524 ;; A headline
6525 (setq level (- (match-end 1) (match-beginning 1)))
6526 (when (or (> t1 0) (> (aref ltimes level) 0))
6527 (loop for l from 0 to level do
6528 (aset ltimes l (+ (aref ltimes l) t1)))
6529 (setq t1 0 time (aref ltimes level))
6530 (loop for l from level to (1- lmax) do
6531 (aset ltimes l 0))
6532 (goto-char (match-beginning 0))
6533 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
6534 (setq org-clock-file-total-minutes (aref ltimes 0)))
6535 (set-buffer-modified-p bmp)))
6537 (defun org-clock-display (&optional total-only)
6538 "Show subtree times in the entire buffer.
6539 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6540 in the echo area."
6541 (interactive)
6542 (org-remove-clock-overlays)
6543 (let (time h m p)
6544 (org-clock-sum)
6545 (unless total-only
6546 (save-excursion
6547 (goto-char (point-min))
6548 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6549 (goto-char p)
6550 (when (setq time (get-text-property p :org-clock-minutes))
6551 (org-put-clock-overlay time (funcall outline-level))))
6552 (setq h (/ org-clock-file-total-minutes 60)
6553 m (- org-clock-file-total-minutes (* 60 h)))
6554 ;; Arrange to remove the overlays upon next change.
6555 (when org-remove-highlights-with-change
6556 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6557 nil 'local))))
6558 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6560 (defvar org-clock-overlays nil)
6561 (make-variable-buffer-local 'org-clock-overlays)
6563 (defun org-put-clock-overlay (time &optional level)
6564 "Put an overlays on the current line, displaying TIME.
6565 If LEVEL is given, prefix time with a corresponding number of stars.
6566 This creates a new overlay and stores it in `org-clock-overlays', so that it
6567 will be easy to remove."
6568 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6569 (l (if level (org-get-legal-level level 0) 0))
6570 (off 0)
6571 ov tx)
6572 (move-to-column c)
6573 (unless (eolp) (skip-chars-backward "^ \t"))
6574 (skip-chars-backward " \t")
6575 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6576 tx (concat (buffer-substring (1- (point)) (point))
6577 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6578 (org-add-props (format "%s %2d:%02d%s"
6579 (make-string l ?*) h m
6580 (make-string (- 10 l) ?\ ))
6581 '(face secondary-selection))
6582 ""))
6583 (if (not (featurep 'xemacs))
6584 (org-overlay-put ov 'display tx)
6585 (org-overlay-put ov 'invisible t)
6586 (org-overlay-put ov 'end-glyph (make-glyph tx)))
6587 (push ov org-clock-overlays)))
6589 (defun org-remove-clock-overlays (&optional beg end noremove)
6590 "Remove the occur highlights from the buffer.
6591 BEG and END are ignored. If NOREMOVE is nil, remove this function
6592 from the `before-change-functions' in the current buffer."
6593 (interactive)
6594 (unless org-inhibit-highlight-removal
6595 (mapc 'org-delete-overlay org-clock-overlays)
6596 (setq org-clock-overlays nil)
6597 (unless noremove
6598 (remove-hook 'before-change-functions
6599 'org-remove-clock-overlays 'local))))
6601 (defun org-clock-out-if-current ()
6602 "Clock out if the current entry contains the running clock.
6603 This is used to stop the clock after a TODO entry is marked DONE."
6604 (when (and (equal state org-done-string)
6605 (equal (marker-buffer org-clock-marker) (current-buffer))
6606 (< (point) org-clock-marker)
6607 (> (save-excursion (outline-next-heading) (point))
6608 org-clock-marker))
6609 ;; Clock out, but don't accept a logging message for this.
6610 (let ((org-log-done (if (and (listp org-log-done)
6611 (member 'clock-out org-log-done))
6612 '(done)
6613 org-log-done)))
6614 (org-clock-out))))
6616 (add-hook 'org-after-todo-state-change-hook
6617 'org-clock-out-if-current)
6619 (defun org-check-running-clock ()
6620 "Check if the current buffer contains the running clock.
6621 If yes, offer to stop it and to save the buffer with the changes."
6622 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6623 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6624 (buffer-name))))
6625 (org-clock-out)
6626 (when (y-or-n-p "Save changed buffer?")
6627 (save-buffer))))
6629 (defun org-clock-report ()
6630 "Create a table containing a report about clocked time.
6631 If the buffer contains lines
6632 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6634 #+END: clocktable
6635 then the table will be inserted between these lines, replacing whatever
6636 is was there before. If these lines are not in the buffer, the table
6637 is inserted at point, surrounded by the special lines.
6638 The BEGIN line can contain parameters. Allowed are:
6639 :maxlevel The maximum level to be included in the table. Default is 3.
6640 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6641 (interactive)
6642 (org-remove-clock-overlays)
6643 (unless (org-find-dblock "clocktable")
6644 (org-create-dblock (list :name "clocktable"
6645 :maxlevel 2 :emphasize nil)))
6646 (org-update-dblock))
6648 (defun org-clock-update-time-maybe ()
6649 "If this is a CLOCK line, update it and return t.
6650 Otherwise, return nil."
6651 (interactive)
6652 (save-excursion
6653 (beginning-of-line 1)
6654 (skip-chars-forward " \t")
6655 (when (looking-at org-clock-string)
6656 (let ((re (concat "[ \t]*" org-clock-string
6657 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6658 "\\([ \t]*=>.*\\)?"))
6659 ts te h m s)
6660 (if (not (looking-at re))
6662 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6663 (end-of-line 1)
6664 (setq ts (match-string 1)
6665 te (match-string 2))
6666 (setq s (- (time-to-seconds
6667 (apply 'encode-time (org-parse-time-string te)))
6668 (time-to-seconds
6669 (apply 'encode-time (org-parse-time-string ts))))
6670 h (floor (/ s 3600))
6671 s (- s (* 3600 h))
6672 m (floor (/ s 60))
6673 s (- s (* 60 s)))
6674 (insert " => " (format "%2d:%02d" h m))
6675 t)))))
6677 (defun org-clock-special-range (key &optional time as-strings)
6678 "Return two times bordering a special time range.
6679 Key is a symbol specifying the range and can be one of `today', `yesterday',
6680 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6681 A week starts Monday 0:00 and ends Sunday 24:00.
6682 The range is determined relative to TIME. TIME defaults to the current time.
6683 The return value is a cons cell with two internal times like the ones
6684 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6685 the returned times will be formatted strings."
6686 (let* ((tm (decode-time (or time (current-time))))
6687 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6688 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6689 (dow (nth 6 tm))
6690 s1 m1 h1 d1 month1 y1 diff ts te fm)
6691 (cond
6692 ((eq key 'today)
6693 (setq h 0 m 0 h1 24 m1 0))
6694 ((eq key 'yesterday)
6695 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6696 ((eq key 'thisweek)
6697 (setq diff (if (= dow 0) 6 (1- dow))
6698 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6699 ((eq key 'lastweek)
6700 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6701 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6702 ((eq key 'thismonth)
6703 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6704 ((eq key 'lastmonth)
6705 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6706 ((eq key 'thisyear)
6707 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6708 ((eq key 'lastyear)
6709 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6710 (t (error "No such time block %s" key)))
6711 (setq ts (encode-time s m h d month y)
6712 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6713 (or d1 d) (or month1 month) (or y1 y)))
6714 (setq fm (cdr org-time-stamp-formats))
6715 (if as-strings
6716 (cons (format-time-string fm ts) (format-time-string fm te))
6717 (cons ts te))))
6719 (defun org-dblock-write:clocktable (params)
6720 "Write the standard clocktable."
6721 (let ((hlchars '((1 . "*") (2 . ?/)))
6722 (emph nil)
6723 (ins (make-marker))
6724 ipos time h m p level hlc hdl maxlevel
6725 ts te cc block)
6726 (setq maxlevel (or (plist-get params :maxlevel) 3)
6727 emph (plist-get params :emphasize)
6728 ts (plist-get params :tstart)
6729 te (plist-get params :tend)
6730 block (plist-get params :block))
6731 (when block
6732 (setq cc (org-clock-special-range block nil t)
6733 ts (car cc) te (cdr cc)))
6734 (if ts (setq ts (time-to-seconds
6735 (apply 'encode-time (org-parse-time-string ts)))))
6736 (if te (setq te (time-to-seconds
6737 (apply 'encode-time (org-parse-time-string te)))))
6738 (move-marker ins (point))
6739 (setq ipos (point))
6740 ;; FIXME: does not yet use org-insert-time-stamp
6741 (insert-before-markers "Clock summary at ["
6742 (substring
6743 (format-time-string (cdr org-time-stamp-formats))
6744 1 -1)
6745 "]."
6746 (if block
6747 (format " Considered range is /%s/." block)
6749 "\n\n|L|Headline|Time|\n")
6750 (org-clock-sum ts te)
6751 (setq h (/ org-clock-file-total-minutes 60)
6752 m (- org-clock-file-total-minutes (* 60 h)))
6753 (insert-before-markers "|-\n|0|" "*Total file time*| "
6754 (format "*%d:%02d*" h m)
6755 "|\n")
6756 (goto-char (point-min))
6757 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6758 (goto-char p)
6759 (when (setq time (get-text-property p :org-clock-minutes))
6760 (save-excursion
6761 (beginning-of-line 1)
6762 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6763 (setq level (- (match-end 1) (match-beginning 1)))
6764 (<= level maxlevel))
6765 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6766 hdl (match-string 2)
6767 h (/ time 60)
6768 m (- time (* 60 h)))
6769 (goto-char ins)
6770 (if (= level 1) (insert-before-markers "|-\n"))
6771 (insert-before-markers
6772 "| " (int-to-string level) "|" hlc hdl hlc " |"
6773 (make-string (1- level) ?|)
6775 (format "%d:%02d" h m)
6777 " |\n")))))
6778 (goto-char ins)
6779 (backward-delete-char 1)
6780 (goto-char ipos)
6781 (skip-chars-forward "^|")
6782 (org-table-align)))
6784 (defun org-collect-clock-time-entries ()
6785 "Return an internal list with clocking information.
6786 This list has one entry for each CLOCK interval.
6787 FIXME: describe the elements."
6788 (interactive)
6789 (let ((re (concat "^[ \t]*" org-clock-string
6790 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6791 rtn beg end next cont level title total closedp leafp
6792 clockpos titlepos h m donep)
6793 (save-excursion
6794 (org-clock-sum)
6795 (goto-char (point-min))
6796 (while (re-search-forward re nil t)
6797 (setq clockpos (match-beginning 0)
6798 beg (match-string 1) end (match-string 2)
6799 cont (match-end 0))
6800 (setq beg (apply 'encode-time (org-parse-time-string beg))
6801 end (apply 'encode-time (org-parse-time-string end)))
6802 (org-back-to-heading t)
6803 (setq donep (org-entry-is-done-p))
6804 (setq titlepos (point)
6805 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6806 h (/ total 60) m (- total (* 60 h))
6807 total (cons h m))
6808 (looking-at "\\(\\*+\\) +\\(.*\\)")
6809 (setq level (- (match-end 1) (match-beginning 1))
6810 title (org-match-string-no-properties 2))
6811 (save-excursion (outline-next-heading) (setq next (point)))
6812 (setq closedp (re-search-forward org-closed-time-regexp next t))
6813 (goto-char next)
6814 (setq leafp (and (looking-at "^\\*+ ")
6815 (<= (- (match-end 0) (point)) level)))
6816 (push (list beg end clockpos closedp donep
6817 total title titlepos level leafp)
6818 rtn)
6819 (goto-char cont)))
6820 (nreverse rtn)))
6822 ;;; Agenda, and Diary Integration
6824 ;;; Define the mode
6826 (defvar org-agenda-mode-map (make-sparse-keymap)
6827 "Keymap for `org-agenda-mode'.")
6829 (defvar org-agenda-menu) ; defined later in this file.
6830 (defvar org-agenda-follow-mode nil)
6831 (defvar org-agenda-show-log nil)
6832 (defvar org-agenda-redo-command nil)
6833 (defvar org-agenda-mode-hook nil)
6834 (defvar org-agenda-type nil)
6835 (defvar org-agenda-force-single-file nil)
6837 (defun org-agenda-mode ()
6838 "Mode for time-sorted view on action items in Org-mode files.
6840 The following commands are available:
6842 \\{org-agenda-mode-map}"
6843 (interactive)
6844 (kill-all-local-variables)
6845 (setq major-mode 'org-agenda-mode)
6846 (setq mode-name "Org-Agenda")
6847 (use-local-map org-agenda-mode-map)
6848 (easy-menu-add org-agenda-menu)
6849 (if org-startup-truncated (setq truncate-lines t))
6850 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6851 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6852 (unless org-agenda-keep-modes
6853 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6854 org-agenda-show-log nil))
6855 (easy-menu-change
6856 '("Agenda") "Agenda Files"
6857 (append
6858 (list
6859 (vector
6860 (if (get 'org-agenda-files 'org-restrict)
6861 "Restricted to single file"
6862 "Edit File List")
6863 '(org-edit-agenda-file-list)
6864 (not (get 'org-agenda-files 'org-restrict)))
6865 "--")
6866 (mapcar 'org-file-menu-entry (org-agenda-files))))
6867 (org-agenda-set-mode-name)
6868 (apply
6869 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6870 (list 'org-agenda-mode-hook)))
6872 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6873 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6874 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6875 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
6876 (define-key org-agenda-mode-map " " 'org-agenda-show)
6877 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6878 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6879 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6880 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6881 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6882 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6883 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6884 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6885 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6886 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6887 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6888 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6889 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6891 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6892 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6893 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6894 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6895 (while l (define-key org-agenda-mode-map
6896 (int-to-string (pop l)) 'digit-argument)))
6898 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6899 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6900 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6901 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6902 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6903 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6904 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6905 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6906 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6907 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6908 (define-key org-agenda-mode-map "n" 'next-line)
6909 (define-key org-agenda-mode-map "p" 'previous-line)
6910 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6911 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6912 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6913 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6914 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6915 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6916 (eval-after-load "calendar"
6917 '(define-key calendar-mode-map org-calendar-to-agenda-key
6918 'org-calendar-goto-agenda))
6919 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6920 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6921 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6922 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6923 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6924 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6925 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6926 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6927 (define-key org-agenda-mode-map "O" 'org-clock-out)
6928 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6929 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6930 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6931 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6932 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6933 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6934 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6935 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6936 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6937 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6938 "Local keymap for agenda entries from Org-mode.")
6940 (define-key org-agenda-keymap
6941 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6942 (define-key org-agenda-keymap
6943 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6944 (when org-agenda-mouse-1-follows-link
6945 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6946 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6947 '("Agenda"
6948 ("Agenda Files")
6949 "--"
6950 ["Show" org-agenda-show t]
6951 ["Go To (other window)" org-agenda-goto t]
6952 ["Go To (this window)" org-agenda-switch-to t]
6953 ["Follow Mode" org-agenda-follow-mode
6954 :style toggle :selected org-agenda-follow-mode :active t]
6955 "--"
6956 ["Cycle TODO" org-agenda-todo t]
6957 ("Tags"
6958 ["Show all Tags" org-agenda-show-tags t]
6959 ["Set Tags" org-agenda-set-tags t])
6960 ("Schedule"
6961 ["Schedule" org-agenda-schedule t]
6962 ["Set Deadline" org-agenda-deadline t]
6963 "--"
6964 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6965 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6966 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6967 ("Priority"
6968 ["Set Priority" org-agenda-priority t]
6969 ["Increase Priority" org-agenda-priority-up t]
6970 ["Decrease Priority" org-agenda-priority-down t]
6971 ["Show Priority" org-agenda-show-priority t])
6972 "--"
6973 ;; ["New agenda command" org-agenda t]
6974 ["Rebuild buffer" org-agenda-redo t]
6975 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6976 "--"
6977 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6978 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6979 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6980 "--"
6981 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6982 :style radio :selected (equal org-agenda-ndays 1)]
6983 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6984 :style radio :selected (equal org-agenda-ndays 7)]
6985 "--"
6986 ["Show Logbook entries" org-agenda-log-mode
6987 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6988 ["Include Diary" org-agenda-toggle-diary
6989 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6990 ["Use Time Grid" org-agenda-toggle-time-grid
6991 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6992 "--"
6993 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6994 ("Calendar Commands"
6995 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6996 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6997 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6998 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6999 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
7000 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
7001 "--"
7002 ["Quit" org-agenda-quit t]
7003 ["Exit and Release Buffers" org-agenda-exit t]
7006 (defvar org-agenda-restrict nil)
7007 (defvar org-agenda-restrict-begin (make-marker))
7008 (defvar org-agenda-restrict-end (make-marker))
7009 (defvar org-agenda-last-dispatch-buffer nil)
7011 ;;;###autoload
7012 (defun org-agenda (arg)
7013 "Dispatch agenda commands to collect entries to the agenda buffer.
7014 Prompts for a character to select a command. Any prefix arg will be passed
7015 on to the selected command. The default selections are:
7017 a Call `org-agenda-list' to display the agenda for current day or week.
7018 t Call `org-todo-list' to display the global todo list.
7019 T Call `org-todo-list' to display the global todo list, select only
7020 entries with a specific TODO keyword (the user gets a prompt).
7021 m Call `org-tags-view' to display headlines with tags matching
7022 a condition (the user is prompted for the condition).
7023 M Like `m', but select only TODO entries, no ordinary headlines.
7024 l Create a timeeline for the current buffer.
7026 More commands can be added by configuring the variable
7027 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
7028 searches can be pre-defined in this way.
7030 If the current buffer is in Org-mode and visiting a file, you can also
7031 first press `1' to indicate that the agenda should be temporarily (until the
7032 next use of \\[org-agenda]) restricted to the current file."
7033 (interactive "P")
7034 (catch 'exit
7035 (let* ((buf (current-buffer))
7036 (bfn (buffer-file-name (buffer-base-buffer)))
7037 (restrict-ok (and bfn (org-mode-p)))
7038 (custom org-agenda-custom-commands)
7039 c entry key type match lprops)
7040 ;; Turn off restriction
7041 (put 'org-agenda-files 'org-restrict nil)
7042 (setq org-agenda-restrict nil)
7043 (move-marker org-agenda-restrict-begin nil)
7044 (move-marker org-agenda-restrict-end nil)
7045 ;; Remember where this call originated
7046 (setq org-agenda-last-dispatch-buffer (current-buffer))
7047 (save-window-excursion
7048 (delete-other-windows)
7049 (switch-to-buffer-other-window " *Agenda Commands*")
7050 (erase-buffer)
7051 (insert
7052 "Press key for an agenda command:
7053 --------------------------------
7054 a Agenda for current week or day
7055 t List of all TODO entries T Entries with special TODO kwd
7056 m Match a TAGS query M Like m, but only TODO entries
7057 L Timeline for current buffer C Configure custom agenda commands")
7058 (while (setq entry (pop custom))
7059 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
7060 (insert (format "\n%-4s%-14s: %s"
7062 (cond
7063 ((stringp type) type)
7064 ((eq type 'tags) "Tags query")
7065 ((eq type 'todo) "TODO keyword")
7066 ((eq type 'tags-tree) "Tags tree")
7067 ((eq type 'todo-tree) "TODO kwd tree")
7068 ((eq type 'occur-tree) "Occur tree")
7069 (t "???"))
7070 (if (stringp match)
7071 (org-add-props match nil 'face 'org-warning)
7072 (format "set of %d commands" (+ -2 (length entry)))))))
7073 (if restrict-ok
7074 (insert "\n"
7075 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
7077 (goto-char (point-min))
7078 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
7079 (message "Press key for agenda command%s"
7080 (if restrict-ok ", or [1] or [0] to restrict" ""))
7081 (setq c (read-char-exclusive))
7082 (message "")
7083 (when (memq c '(?L ?1 ?0))
7084 (if restrict-ok
7085 (put 'org-agenda-files 'org-restrict (list bfn))
7086 (error "Cannot restrict agenda to current buffer"))
7087 (with-current-buffer " *Agenda Commands*"
7088 (goto-char (point-max))
7089 (delete-region (point-at-bol) (point))
7090 (goto-char (point-min)))
7091 (when (eq c ?0)
7092 (setq org-agenda-restrict t)
7093 (with-current-buffer buf
7094 (if (org-region-active-p)
7095 (progn
7096 (move-marker org-agenda-restrict-begin (region-beginning))
7097 (move-marker org-agenda-restrict-end (region-end)))
7098 (save-excursion
7099 (org-back-to-heading t)
7100 (move-marker org-agenda-restrict-begin (point))
7101 (move-marker org-agenda-restrict-end
7102 (progn (org-end-of-subtree t)))))))
7103 (unless (eq c ?L)
7104 (message "Press key for agenda command%s"
7105 (if restrict-ok " (restricted to current file)" ""))
7106 (setq c (read-char-exclusive)))
7107 (message "")))
7108 (require 'calendar) ; FIXME: can we avoid this for some commands?
7109 ;; For example the todo list should not need it (but does...)
7110 (cond
7111 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
7112 ((equal c ?a) (call-interactively 'org-agenda-list))
7113 ((equal c ?t) (call-interactively 'org-todo-list))
7114 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
7115 ((equal c ?m) (call-interactively 'org-tags-view))
7116 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
7117 ((equal c ?L)
7118 (unless restrict-ok
7119 (error "This is not an Org-mode file"))
7120 (org-call-with-arg 'org-timeline arg))
7121 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
7122 (if (symbolp (nth 1 entry))
7123 (progn
7124 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
7125 lprops (nth 3 entry))
7126 (cond
7127 ((eq type 'tags)
7128 (org-let lprops '(org-tags-view current-prefix-arg match)))
7129 ((eq type 'tags-todo)
7130 (org-let lprops '(org-tags-view '(4) match)))
7131 ((eq type 'todo)
7132 (org-let lprops '(org-todo-list match)))
7133 ((eq type 'tags-tree)
7134 (org-check-for-org-mode)
7135 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
7136 ((eq type 'todo-tree)
7137 (org-check-for-org-mode)
7138 (org-let lprops
7139 '(org-occur (concat "^" outline-regexp "[ \t]*"
7140 (regexp-quote match) "\\>"))))
7141 ((eq type 'occur-tree)
7142 (org-check-for-org-mode)
7143 (org-let lprops '(org-occur match)))
7144 (t (error "Invalid custom agenda command type %s" type))))
7145 (org-run-agenda-series (cddr entry))))
7146 (t (error "Invalid key"))))))
7148 ;; FIXME: what is the meaning of WINDOW?????
7149 (defun org-run-agenda-series (series &optional window)
7150 (org-prepare-agenda)
7151 (let* ((org-agenda-multi t)
7152 (redo (list 'org-run-agenda-series (list 'quote series)))
7153 (org-select-agenda-window t)
7154 (cmds (car series))
7155 (gprops (nth 1 series))
7156 match ;; The byte compiler incorrectly complains about this. Keep it!
7157 cmd type lprops)
7158 (while (setq cmd (pop cmds))
7159 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
7160 (cond
7161 ((eq type 'agenda)
7162 (call-interactively 'org-agenda-list))
7163 ((eq type 'alltodo)
7164 (call-interactively 'org-todo-list))
7165 ((eq type 'tags)
7166 (org-let2 gprops lprops
7167 '(org-tags-view current-prefix-arg match)))
7168 ((eq type 'tags-todo)
7169 (org-let2 gprops lprops
7170 '(org-tags-view '(4) match)))
7171 ((eq type 'todo)
7172 (org-let2 gprops lprops
7173 '(org-todo-list match)))
7174 (t (error "Invalid type in command series"))))
7175 (widen)
7176 (setq org-agenda-redo-command redo)
7177 (goto-char (point-min)))
7178 (org-finalize-agenda))
7180 ;;;###autoload
7181 (defmacro org-batch-agenda (cmd-key &rest parameters)
7182 "Run an agenda command in batch mode, send result to STDOUT.
7183 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
7184 Paramters are alternating variable names and values that will be bound
7185 before running the agenda command."
7186 (let (pars)
7187 (while parameters
7188 (push (list (pop parameters) (if parameters (pop parameters))) pars))
7189 (flet ((read-char-exclusive () (string-to-char cmd-key)))
7190 (eval (list 'let (nreverse pars) '(org-agenda nil))))
7191 (set-buffer "*Org Agenda*")
7192 (princ (buffer-string))))
7194 (defmacro org-no-read-only (&rest body)
7195 "Inhibit read-only for BODY."
7196 `(let ((inhibit-read-only t)) ,@body))
7198 (defun org-check-for-org-mode ()
7199 "Make sure current buffer is in org-mode. Error if not."
7200 (or (org-mode-p)
7201 (error "Cannot execute org-mode agenda command on buffer in %s."
7202 major-mode)))
7204 (defun org-fit-agenda-window ()
7205 "Fit the window to the buffer size."
7206 (and org-fit-agenda-window
7207 (memq org-agenda-window-setup '(reorganize-frame))
7208 (fboundp 'fit-window-to-buffer)
7209 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
7210 (/ (frame-height) 2))))
7212 (defun org-agenda-files (&optional unrestricted)
7213 "Get the list of agenda files.
7214 Optional UNRESTRICTED means return the full list even if a restriction
7215 is currently in place."
7216 (cond
7217 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
7218 ((stringp org-agenda-files) (org-read-agenda-file-list))
7219 ((listp org-agenda-files) org-agenda-files)
7220 (t (error "Invalid value of `org-agenda-files'"))))
7222 (defvar org-window-configuration)
7224 (defun org-edit-agenda-file-list ()
7225 "Edit the list of agenda files.
7226 Depending on setup, this either uses customize to edit the variable
7227 `org-agenda-files', or it visits the file that is holding the list. In the
7228 latter case, the buffer is set up in a way that saving it automatically kills
7229 the buffer and restores the previous window configuration."
7230 (interactive)
7231 (if (stringp org-agenda-files)
7232 (let ((cw (current-window-configuration)))
7233 (find-file org-agenda-files)
7234 (org-set-local 'org-window-configuration cw)
7235 (org-add-hook 'after-save-hook
7236 (lambda ()
7237 (set-window-configuration
7238 (prog1 org-window-configuration
7239 (kill-buffer (current-buffer))))
7240 (org-install-agenda-files-menu)
7241 (message "New agenda file list installed"))
7242 nil 'local)
7243 (message (substitute-command-keys
7244 "Edit list and finish with \\[save-buffer]")))
7245 (customize-variable 'org-agenda-files)))
7247 (defun org-store-new-agenda-file-list (list)
7248 "Set new value for the agenda file list and save it correcly."
7249 (if (stringp org-agenda-files)
7250 (let ((f org-agenda-files) b)
7251 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
7252 (with-temp-file f
7253 (insert (mapconcat 'identity list "\n") "\n")))
7254 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
7255 (setq org-agenda-files list)
7256 (customize-save-variable 'org-agenda-files org-agenda-files))))
7258 (defun org-read-agenda-file-list ()
7259 "Read the list of agenda files from a file."
7260 (when (stringp org-agenda-files)
7261 (with-temp-buffer
7262 (insert-file-contents org-agenda-files)
7263 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
7265 (defvar org-agenda-markers nil
7266 "List of all currently active markers created by `org-agenda'.")
7267 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
7268 "Creation time of the last agenda marker.")
7270 (defun org-agenda-new-marker (&optional pos)
7271 "Return a new agenda marker.
7272 Org-mode keeps a list of these markers and resets them when they are
7273 no longer in use."
7274 (let ((m (copy-marker (or pos (point)))))
7275 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
7276 (push m org-agenda-markers)
7279 (defun org-agenda-maybe-reset-markers (&optional force)
7280 "Reset markers created by `org-agenda'. But only if they are old enough."
7281 (if (or (and force (not org-agenda-multi))
7282 (> (- (time-to-seconds (current-time))
7283 org-agenda-last-marker-time)
7285 (while org-agenda-markers
7286 (move-marker (pop org-agenda-markers) nil))))
7288 (defvar org-agenda-new-buffers nil
7289 "Buffers created to visit agenda files.")
7291 (defun org-get-agenda-file-buffer (file)
7292 "Get a buffer visiting FILE. If the buffer needs to be created, add
7293 it to the list of buffers which might be released later."
7294 (let ((buf (find-buffer-visiting file)))
7295 (if buf
7296 buf ; just return it
7297 ;; Make a new buffer and remember it
7298 (setq buf (find-file-noselect file))
7299 (if buf (push buf org-agenda-new-buffers))
7300 buf)))
7302 (defun org-release-buffers (blist)
7303 "Release all buffers in list, asking the user for confirmation when needed.
7304 When a buffer is unmodified, it is just killed. When modified, it is saved
7305 \(if the user agrees) and then killed."
7306 (let (buf file)
7307 (while (setq buf (pop blist))
7308 (setq file (buffer-file-name buf))
7309 (when (and (buffer-modified-p buf)
7310 file
7311 (y-or-n-p (format "Save file %s? " file)))
7312 (with-current-buffer buf (save-buffer)))
7313 (kill-buffer buf))))
7315 (defun org-timeline (&optional include-all)
7316 "Show a time-sorted view of the entries in the current org file.
7317 Only entries with a time stamp of today or later will be listed. With
7318 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
7319 under the current date.
7320 If the buffer contains an active region, only check the region for
7321 dates."
7322 (interactive "P")
7323 (require 'calendar)
7324 (org-compile-prefix-format 'timeline)
7325 (org-set-sorting-strategy 'timeline)
7326 (let* ((dopast t)
7327 (dotodo include-all)
7328 (doclosed org-agenda-show-log)
7329 (entry buffer-file-name)
7330 (date (calendar-current-date))
7331 (win (selected-window))
7332 (pos1 (point))
7333 (beg (if (org-region-active-p) (region-beginning) (point-min)))
7334 (end (if (org-region-active-p) (region-end) (point-max)))
7335 (day-numbers (org-get-all-dates beg end 'no-ranges
7336 t doclosed ; always include today
7337 org-timeline-show-empty-dates))
7338 (today (time-to-days (current-time)))
7339 (past t)
7340 args
7341 s e rtn d emptyp)
7342 (setq org-agenda-redo-command
7343 (list 'progn
7344 (list 'switch-to-buffer-other-window (current-buffer))
7345 (list 'org-timeline (list 'quote include-all))))
7346 (if (not dopast)
7347 ;; Remove past dates from the list of dates.
7348 (setq day-numbers (delq nil (mapcar (lambda(x)
7349 (if (>= x today) x nil))
7350 day-numbers))))
7351 (org-prepare-agenda)
7352 (if doclosed (push :closed args))
7353 (push :timestamp args)
7354 (if dotodo (push :todo args))
7355 (while (setq d (pop day-numbers))
7356 (if (and (listp d) (eq (car d) :omitted))
7357 (progn
7358 (setq s (point))
7359 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
7360 (put-text-property s (1- (point)) 'face 'org-level-3))
7361 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
7362 (if (and (>= d today)
7363 dopast
7364 past)
7365 (progn
7366 (setq past nil)
7367 (insert (make-string 79 ?-) "\n")))
7368 (setq date (calendar-gregorian-from-absolute d))
7369 (setq s (point))
7370 (setq rtn (and (not emptyp)
7371 (apply 'org-agenda-get-day-entries
7372 entry date args)))
7373 (if (or rtn (equal d today) org-timeline-show-empty-dates)
7374 (progn
7375 (insert (calendar-day-name date) " "
7376 (number-to-string (extract-calendar-day date)) " "
7377 (calendar-month-name (extract-calendar-month date)) " "
7378 (number-to-string (extract-calendar-year date)) "\n")
7379 (put-text-property s (1- (point)) 'face
7380 'org-level-3)
7381 (if (equal d today)
7382 (put-text-property s (1- (point)) 'org-today t))
7383 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
7384 (put-text-property s (1- (point)) 'day d)))))
7385 (goto-char (point-min))
7386 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7387 (point-min)))
7388 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
7389 (org-finalize-agenda)
7390 (setq buffer-read-only t)
7391 (when (not org-select-agenda-window)
7392 (select-window win)
7393 (goto-char pos1))))
7395 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
7396 (defvar org-agenda-last-arguments nil
7397 "The arguments of the previous call to org-agenda")
7399 ;;;###autoload
7400 (defun org-agenda-list (&optional include-all start-day ndays)
7401 "Produce a weekly view from all files in variable `org-agenda-files'.
7402 The view will be for the current week, but from the overview buffer you
7403 will be able to go to other weeks.
7404 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
7405 also be shown, under the current date.
7406 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
7407 on the days are also shown. See the variable `org-log-done' for how
7408 to turn on logging.
7409 START-DAY defaults to TODAY, or to the most recent match for the weekday
7410 given in `org-agenda-start-on-weekday'.
7411 NDAYS defaults to `org-agenda-ndays'."
7412 (interactive "P")
7413 (if org-agenda-overriding-arguments
7414 (setq include-all (car org-agenda-overriding-arguments)
7415 start-day (nth 1 org-agenda-overriding-arguments)
7416 ndays (nth 2 org-agenda-overriding-arguments)))
7417 (setq org-agenda-last-arguments (list include-all start-day ndays))
7418 (org-compile-prefix-format 'agenda)
7419 (org-set-sorting-strategy 'agenda)
7420 (require 'calendar)
7421 (let* ((org-agenda-start-on-weekday
7422 (if (or (equal ndays 1)
7423 (and (null ndays) (equal 1 org-agenda-ndays)))
7424 nil org-agenda-start-on-weekday))
7425 (thefiles (org-agenda-files))
7426 (files thefiles)
7427 (win (selected-window))
7428 (today (time-to-days (current-time)))
7429 (sd (or start-day today))
7430 (start (if (or (null org-agenda-start-on-weekday)
7431 (< org-agenda-ndays 7))
7433 (let* ((nt (calendar-day-of-week
7434 (calendar-gregorian-from-absolute sd)))
7435 (n1 org-agenda-start-on-weekday)
7436 (d (- nt n1)))
7437 (- sd (+ (if (< d 0) 7 0) d)))))
7438 (day-numbers (list start))
7439 (inhibit-redisplay t)
7440 s e rtn rtnall file date d start-pos end-pos todayp nd)
7441 (setq org-agenda-redo-command
7442 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
7443 ;; Make the list of days
7444 (setq ndays (or ndays org-agenda-ndays)
7445 nd ndays)
7446 (while (> ndays 1)
7447 (push (1+ (car day-numbers)) day-numbers)
7448 (setq ndays (1- ndays)))
7449 (setq day-numbers (nreverse day-numbers))
7450 (org-prepare-agenda)
7451 (org-set-local 'starting-day (car day-numbers))
7452 (org-set-local 'include-all-loc include-all)
7453 (when (and (or include-all org-agenda-include-all-todo)
7454 (member today day-numbers))
7455 (setq files thefiles
7456 rtnall nil)
7457 (while (setq file (pop files))
7458 (catch 'nextfile
7459 (org-check-agenda-file file)
7460 (setq date (calendar-gregorian-from-absolute today)
7461 rtn (org-agenda-get-day-entries
7462 file date :todo))
7463 (setq rtnall (append rtnall rtn))))
7464 (when rtnall
7465 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
7466 (add-text-properties (point-min) (1- (point))
7467 (list 'face 'org-level-3))
7468 (insert (org-finalize-agenda-entries rtnall) "\n")))
7469 (setq s (point))
7470 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
7471 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
7472 (while (setq d (pop day-numbers))
7473 (setq date (calendar-gregorian-from-absolute d)
7474 s (point))
7475 (if (or (setq todayp (= d today))
7476 (and (not start-pos) (= d sd)))
7477 (setq start-pos (point))
7478 (if (and start-pos (not end-pos))
7479 (setq end-pos (point))))
7480 (setq files thefiles
7481 rtnall nil)
7482 (while (setq file (pop files))
7483 (catch 'nextfile
7484 (org-check-agenda-file file)
7485 (if org-agenda-show-log
7486 (setq rtn (org-agenda-get-day-entries
7487 file date
7488 :deadline :scheduled :timestamp :closed))
7489 (setq rtn (org-agenda-get-day-entries
7490 file date
7491 :deadline :scheduled :timestamp)))
7492 (setq rtnall (append rtnall rtn))))
7493 (if org-agenda-include-diary
7494 (progn
7495 (require 'diary-lib)
7496 (setq rtn (org-get-entries-from-diary date))
7497 (setq rtnall (append rtnall rtn))))
7498 (if (or rtnall org-agenda-show-all-dates)
7499 (progn
7500 (insert (format "%-9s %2d %s %4d\n"
7501 (calendar-day-name date)
7502 (extract-calendar-day date)
7503 (calendar-month-name (extract-calendar-month date))
7504 (extract-calendar-year date)))
7505 (put-text-property s (1- (point)) 'face
7506 'org-level-3)
7507 (if todayp (put-text-property s (1- (point)) 'org-today t))
7509 (if rtnall (insert
7510 (org-finalize-agenda-entries
7511 (org-agenda-add-time-grid-maybe
7512 rtnall nd todayp))
7513 "\n"))
7514 (put-text-property s (1- (point)) 'day d))))
7515 (goto-char (point-min))
7516 (org-fit-agenda-window)
7517 (unless (and (pos-visible-in-window-p (point-min))
7518 (pos-visible-in-window-p (point-max)))
7519 (goto-char (1- (point-max)))
7520 (recenter -1)
7521 (if (not (pos-visible-in-window-p (or start-pos 1)))
7522 (progn
7523 (goto-char (or start-pos 1))
7524 (recenter 1))))
7525 (goto-char (or start-pos 1))
7526 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
7527 (org-finalize-agenda)
7528 (setq buffer-read-only t)
7529 (if (not org-select-agenda-window) (select-window win))
7530 (message "")))
7532 (defvar org-select-this-todo-keyword nil)
7534 ;;;###autoload
7535 (defun org-todo-list (arg)
7536 "Show all TODO entries from all agenda file in a single list.
7537 The prefix arg can be used to select a specific TODO keyword and limit
7538 the list to these. When using \\[universal-argument], you will be prompted
7539 for a keyword. A numeric prefix directly selects the Nth keyword in
7540 `org-todo-keywords'."
7541 (interactive "P")
7542 (require 'calendar)
7543 (org-compile-prefix-format 'todo)
7544 (org-set-sorting-strategy 'todo)
7545 (let* ((today (time-to-days (current-time)))
7546 (date (calendar-gregorian-from-absolute today))
7547 (win (selected-window))
7548 (kwds org-todo-keywords)
7549 (completion-ignore-case t)
7550 (org-select-this-todo-keyword
7551 (if (stringp arg) arg
7552 (and arg (integerp arg) (> arg 0)
7553 (nth (1- arg) org-todo-keywords))))
7554 rtn rtnall files file pos)
7555 (when (equal arg '(4))
7556 (setq org-select-this-todo-keyword
7557 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
7558 nil t)))
7559 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
7560 (org-prepare-agenda)
7561 (org-set-local 'last-arg arg)
7562 (org-set-local 'org-todo-keywords kwds)
7563 (setq org-agenda-redo-command
7564 '(org-todo-list (or current-prefix-arg last-arg)))
7565 (setq files (org-agenda-files)
7566 rtnall nil)
7567 (while (setq file (pop files))
7568 (catch 'nextfile
7569 (org-check-agenda-file file)
7570 (setq rtn (org-agenda-get-day-entries file date :todo))
7571 (setq rtnall (append rtnall rtn))))
7572 (insert "Global list of TODO items of type: ")
7573 (add-text-properties (point-min) (1- (point))
7574 (list 'face 'org-level-3))
7575 (setq pos (point))
7576 (insert (or org-select-this-todo-keyword "ALL") "\n")
7577 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7578 (setq pos (point))
7579 (unless org-agenda-multi
7580 (insert
7581 "Available with `N r': (0)ALL "
7582 (let ((n 0))
7583 (mapconcat (lambda (x)
7584 (format "(%d)%s" (setq n (1+ n)) x))
7585 org-todo-keywords " "))
7586 "\n"))
7587 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7588 (when rtnall
7589 (insert (org-finalize-agenda-entries rtnall) "\n"))
7590 (goto-char (point-min))
7591 (org-fit-agenda-window)
7592 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
7593 (org-finalize-agenda)
7594 (setq buffer-read-only t)
7595 (if (not org-select-agenda-window) (select-window win))))
7597 (defun org-check-agenda-file (file)
7598 "Make sure FILE exists. If not, ask user what to do."
7599 (when (not (file-exists-p file))
7600 (message "non-existent file %s. [R]emove from list or [A]bort?"
7601 (abbreviate-file-name file))
7602 (let ((r (downcase (read-char-exclusive))))
7603 (cond
7604 ((equal r ?r)
7605 (org-remove-file file)
7606 (throw 'nextfile t))
7607 (t (error "Abort"))))))
7609 (defun org-agenda-check-type (error &rest types)
7610 "Check if agenda buffer is of allowed type.
7611 If ERROR is non-nil, throw an error, otherwise just return nil."
7612 (if (memq org-agenda-type types)
7614 (if error
7615 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
7616 nil)))
7618 (defun org-agenda-quit ()
7619 "Exit agenda by removing the window or the buffer."
7620 (interactive)
7621 (let ((buf (current-buffer)))
7622 (if (not (one-window-p)) (delete-window))
7623 (kill-buffer buf)
7624 (org-agenda-maybe-reset-markers 'force))
7625 ;; Maybe restore the pre-agenda window configuration.
7626 (and org-agenda-restore-windows-after-quit
7627 (not (eq org-agenda-window-setup 'other-frame))
7628 org-pre-agenda-window-conf
7629 (set-window-configuration org-pre-agenda-window-conf)))
7631 (defun org-agenda-exit ()
7632 "Exit agenda by removing the window or the buffer.
7633 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
7634 Org-mode buffers visited directly by the user will not be touched."
7635 (interactive)
7636 (org-release-buffers org-agenda-new-buffers)
7637 (setq org-agenda-new-buffers nil)
7638 (org-agenda-quit))
7640 (defun org-save-all-org-buffers ()
7641 "Save all Org-mode buffers without user confirmation."
7642 (interactive)
7643 (message "Saving all Org-mode buffers...")
7644 (save-some-buffers t 'org-mode-p)
7645 (message "Saving all Org-mode buffers... done"))
7647 (defun org-agenda-redo ()
7648 "Rebuild Agenda.
7649 When this is the global TODO list, a prefix argument will be interpreted."
7650 (interactive)
7651 (let* ((org-agenda-keep-modes t)
7652 (line (org-current-line))
7653 (window-line (- line (org-current-line (window-start)))))
7654 (message "Rebuilding agenda buffer...")
7655 (eval org-agenda-redo-command)
7656 (message "Rebuilding agenda buffer...done")
7657 (goto-line line)
7658 (recenter window-line)))
7660 (defun org-agenda-goto-today ()
7661 "Go to today."
7662 (interactive)
7663 (org-agenda-check-type t 'timeline 'agenda)
7664 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
7665 (cond
7666 (tdpos (goto-char tdpos))
7667 ((eq org-agenda-type 'agenda)
7668 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
7669 (setf (nth 1 org-agenda-overriding-arguments) nil)
7670 (org-agenda-redo)
7671 (org-agenda-find-today-or-agenda)))
7672 (t (error "Cannot find today")))))
7674 (defun org-agenda-find-today-or-agenda ()
7675 (goto-char
7676 (or (text-property-any (point-min) (point-max) 'org-today t)
7677 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
7678 (point-min))))
7680 (defun org-agenda-later (arg)
7681 "Go forward in time by `org-agenda-ndays' days.
7682 With prefix ARG, go forward that many times `org-agenda-ndays'."
7683 (interactive "p")
7684 (org-agenda-check-type t 'agenda)
7685 (let ((org-agenda-overriding-arguments
7686 (list (car org-agenda-last-arguments)
7687 (+ starting-day (* arg org-agenda-ndays))
7688 nil t)))
7689 (org-agenda-redo)
7690 (org-agenda-find-today-or-agenda)))
7692 (defun org-agenda-earlier (arg)
7693 "Go back in time by `org-agenda-ndays' days.
7694 With prefix ARG, go back that many times `org-agenda-ndays'."
7695 (interactive "p")
7696 (org-agenda-check-type t 'agenda)
7697 (let ((org-agenda-overriding-arguments
7698 (list (car org-agenda-last-arguments)
7699 (- starting-day (* arg org-agenda-ndays))
7700 nil t)))
7701 (org-agenda-redo)
7702 (org-agenda-find-today-or-agenda)))
7704 (defun org-agenda-week-view ()
7705 "Switch to weekly view for agenda."
7706 (interactive)
7707 (org-agenda-check-type t 'agenda)
7708 (if (= org-agenda-ndays 7)
7709 (error "This is already the week view"))
7710 (setq org-agenda-ndays 7)
7711 (let ((org-agenda-overriding-arguments
7712 (list (car org-agenda-last-arguments)
7713 (or (get-text-property (point) 'day)
7714 starting-day)
7715 nil t)))
7716 (org-agenda-redo)
7717 (org-agenda-find-today-or-agenda))
7718 (org-agenda-set-mode-name)
7719 (message "Switched to week view"))
7721 (defun org-agenda-day-view ()
7722 "Switch to daily view for agenda."
7723 (interactive)
7724 (org-agenda-check-type t 'agenda)
7725 (if (= org-agenda-ndays 1)
7726 (error "This is already the day view"))
7727 (setq org-agenda-ndays 1)
7728 (let ((org-agenda-overriding-arguments
7729 (list (car org-agenda-last-arguments)
7730 (or (get-text-property (point) 'day)
7731 starting-day)
7732 nil t)))
7733 (org-agenda-redo)
7734 (org-agenda-find-today-or-agenda))
7735 (org-agenda-set-mode-name)
7736 (message "Switched to day view"))
7738 (defun org-agenda-next-date-line (&optional arg)
7739 "Jump to the next line indicating a date in agenda buffer."
7740 (interactive "p")
7741 (org-agenda-check-type t 'agenda 'timeline)
7742 (beginning-of-line 1)
7743 (if (looking-at "^\\S-") (forward-char 1))
7744 (if (not (re-search-forward "^\\S-" nil t arg))
7745 (progn
7746 (backward-char 1)
7747 (error "No next date after this line in this buffer")))
7748 (goto-char (match-beginning 0)))
7750 (defun org-agenda-previous-date-line (&optional arg)
7751 "Jump to the previous line indicating a date in agenda buffer."
7752 (interactive "p")
7753 (org-agenda-check-type t 'agenda 'timeline)
7754 (beginning-of-line 1)
7755 (if (not (re-search-backward "^\\S-" nil t arg))
7756 (error "No previous date before this line in this buffer")))
7758 ;; Initialize the highlight
7759 (defvar org-hl (org-make-overlay 1 1))
7760 (org-overlay-put org-hl 'face 'highlight)
7762 (defun org-highlight (begin end &optional buffer)
7763 "Highlight a region with overlay."
7764 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7765 org-hl begin end (or buffer (current-buffer))))
7767 (defun org-unhighlight ()
7768 "Detach overlay INDEX."
7769 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7772 (defun org-agenda-follow-mode ()
7773 "Toggle follow mode in an agenda buffer."
7774 (interactive)
7775 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7776 (org-agenda-set-mode-name)
7777 (message "Follow mode is %s"
7778 (if org-agenda-follow-mode "on" "off")))
7780 (defun org-agenda-log-mode ()
7781 "Toggle log mode in an agenda buffer."
7782 (interactive)
7783 (org-agenda-check-type t 'agenda 'timeline)
7784 (setq org-agenda-show-log (not org-agenda-show-log))
7785 (org-agenda-set-mode-name)
7786 (org-agenda-redo)
7787 (message "Log mode is %s"
7788 (if org-agenda-show-log "on" "off")))
7790 (defun org-agenda-toggle-diary ()
7791 "Toggle diary inclusion in an agenda buffer."
7792 (interactive)
7793 (org-agenda-check-type t 'agenda)
7794 (setq org-agenda-include-diary (not org-agenda-include-diary))
7795 (org-agenda-redo)
7796 (org-agenda-set-mode-name)
7797 (message "Diary inclusion turned %s"
7798 (if org-agenda-include-diary "on" "off")))
7800 (defun org-agenda-toggle-time-grid ()
7801 "Toggle time grid in an agenda buffer."
7802 (interactive)
7803 (org-agenda-check-type t 'agenda)
7804 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7805 (org-agenda-redo)
7806 (org-agenda-set-mode-name)
7807 (message "Time-grid turned %s"
7808 (if org-agenda-use-time-grid "on" "off")))
7810 (defun org-agenda-set-mode-name ()
7811 "Set the mode name to indicate all the small mode settings."
7812 (setq mode-name
7813 (concat "Org-Agenda"
7814 (if (equal org-agenda-ndays 1) " Day" "")
7815 (if (equal org-agenda-ndays 7) " Week" "")
7816 (if org-agenda-follow-mode " Follow" "")
7817 (if org-agenda-include-diary " Diary" "")
7818 (if org-agenda-use-time-grid " Grid" "")
7819 (if org-agenda-show-log " Log" "")))
7820 (force-mode-line-update))
7822 (defun org-agenda-post-command-hook ()
7823 (and (eolp) (not (bolp)) (backward-char 1))
7824 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
7825 (if (and org-agenda-follow-mode
7826 (get-text-property (point) 'org-marker))
7827 (org-agenda-show)))
7829 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7831 (defun org-get-entries-from-diary (date)
7832 "Get the (Emacs Calendar) diary entries for DATE."
7833 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7834 (diary-display-hook '(fancy-diary-display))
7835 (list-diary-entries-hook
7836 (cons 'org-diary-default-entry list-diary-entries-hook))
7837 (diary-file-name-prefix-function nil) ; turn this feature off
7838 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7839 entries
7840 (org-disable-agenda-to-diary t))
7841 (save-excursion
7842 (save-window-excursion
7843 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7844 (if (not (get-buffer fancy-diary-buffer))
7845 (setq entries nil)
7846 (with-current-buffer fancy-diary-buffer
7847 (setq buffer-read-only nil)
7848 (if (= (point-max) 1)
7849 ;; No entries
7850 (setq entries nil)
7851 ;; Omit the date and other unnecessary stuff
7852 (org-agenda-cleanup-fancy-diary)
7853 ;; Add prefix to each line and extend the text properties
7854 (if (= (point-max) 1)
7855 (setq entries nil)
7856 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7857 (set-buffer-modified-p nil)
7858 (kill-buffer fancy-diary-buffer)))
7859 (when entries
7860 (setq entries (org-split-string entries "\n"))
7861 (setq entries
7862 (mapcar
7863 (lambda (x)
7864 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7865 ;; Extend the text properties to the beginning of the line
7866 (org-add-props x (text-properties-at (1- (length x)) x)))
7867 entries)))))
7869 (defun org-agenda-cleanup-fancy-diary ()
7870 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7871 This gets rid of the date, the underline under the date, and
7872 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7873 date. It also removes lines that contain only whitespace."
7874 (goto-char (point-min))
7875 (if (looking-at ".*?:[ \t]*")
7876 (progn
7877 (replace-match "")
7878 (re-search-forward "\n=+$" nil t)
7879 (replace-match "")
7880 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7881 (re-search-forward "\n=+$" nil t)
7882 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7883 (goto-char (point-min))
7884 (while (re-search-forward "^ +\n" nil t)
7885 (replace-match ""))
7886 (goto-char (point-min))
7887 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7888 (replace-match "")))
7890 ;; Make sure entries from the diary have the right text properties.
7891 (eval-after-load "diary-lib"
7892 '(if (boundp 'diary-modify-entry-list-string-function)
7893 ;; We can rely on the hook, nothing to do
7895 ;; Hook not avaiable, must use advice to make this work
7896 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7897 "Make the position visible."
7898 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7899 (stringp string)
7900 buffer-file-name)
7901 (setq string (org-modify-diary-entry-string string))))))
7903 (defun org-modify-diary-entry-string (string)
7904 "Add text properties to string, allowing org-mode to act on it."
7905 (org-add-props string nil
7906 'mouse-face 'highlight
7907 'keymap org-agenda-keymap
7908 'help-echo (format "mouse-2 or RET jump to diary file %s"
7909 (abbreviate-file-name buffer-file-name))
7910 'org-agenda-diary-link t
7911 'org-marker (org-agenda-new-marker (point-at-bol))))
7913 (defun org-diary-default-entry ()
7914 "Add a dummy entry to the diary.
7915 Needed to avoid empty dates which mess up holiday display."
7916 ;; Catch the error if dealing with the new add-to-diary-alist
7917 (when org-disable-agenda-to-diary
7918 (condition-case nil
7919 (add-to-diary-list original-date "Org-mode dummy" "")
7920 (error
7921 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7923 ;;;###autoload
7924 (defun org-cycle-agenda-files ()
7925 "Cycle through the files in `org-agenda-files'.
7926 If the current buffer visits an agenda file, find the next one in the list.
7927 If the current buffer does not, find the first agenda file."
7928 (interactive)
7929 (let* ((fs (org-agenda-files t))
7930 (files (append fs (list (car fs))))
7931 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7932 file)
7933 (unless files (error "No agenda files"))
7934 (catch 'exit
7935 (while (setq file (pop files))
7936 (if (equal (file-truename file) tcf)
7937 (when (car files)
7938 (find-file (car files))
7939 (throw 'exit t))))
7940 (find-file (car fs)))))
7942 (defun org-agenda-file-to-end ()
7943 "Move/add the current file to the end of the agenda file list.
7944 If the file is not present in the list, it is appended to the list. If it is
7945 present, it is moved there."
7946 (interactive)
7947 (org-agenda-file-to-front 'to-end))
7949 (defun org-agenda-file-to-front (&optional to-end)
7950 "Move/add the current file to the top of the agenda file list.
7951 If the file is not present in the list, it is added to the front. If it is
7952 present, it is moved there. With optional argument TO-END, add/move to the
7953 end of the list."
7954 (interactive "P")
7955 (let ((file-alist (mapcar (lambda (x)
7956 (cons (file-truename x) x))
7957 (org-agenda-files t)))
7958 (ctf (file-truename buffer-file-name))
7959 x had)
7960 (setq x (assoc ctf file-alist) had x)
7962 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7963 (if to-end
7964 (setq file-alist (append (delq x file-alist) (list x)))
7965 (setq file-alist (cons x (delq x file-alist))))
7966 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7967 (org-install-agenda-files-menu)
7968 (message "File %s to %s of agenda file list"
7969 (if had "moved" "added") (if to-end "end" "front"))))
7971 (defun org-remove-file (&optional file)
7972 "Remove current file from the list of files in variable `org-agenda-files'.
7973 These are the files which are being checked for agenda entries.
7974 Optional argument FILE means, use this file instead of the current."
7975 (interactive)
7976 (let* ((file (or file buffer-file-name))
7977 (true-file (file-truename file))
7978 (afile (abbreviate-file-name file))
7979 (files (delq nil (mapcar
7980 (lambda (x)
7981 (if (equal true-file
7982 (file-truename x))
7983 nil x))
7984 (org-agenda-files t)))))
7985 (if (not (= (length files) (length (org-agenda-files t))))
7986 (progn
7987 (org-store-new-agenda-file-list files)
7988 (org-install-agenda-files-menu)
7989 (message "Removed file: %s" afile))
7990 (message "File was not in list: %s" afile))))
7992 (defun org-file-menu-entry (file)
7993 (vector file (list 'find-file file) t))
7995 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7996 "Return a list of all relevant day numbers from BEG to END buffer positions.
7997 If NO-RANGES is non-nil, include only the start and end dates of a range,
7998 not every single day in the range. If FORCE-TODAY is non-nil, make
7999 sure that TODAY is included in the list. If INACTIVE is non-nil, also
8000 inactive time stamps (those in square brackets) are included.
8001 When EMPTY is non-nil, also include days without any entries."
8002 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
8003 dates dates1 date day day1 day2 ts1 ts2)
8004 (if force-today
8005 (setq dates (list (time-to-days (current-time)))))
8006 (save-excursion
8007 (goto-char beg)
8008 (while (re-search-forward re end t)
8009 (setq day (time-to-days (org-time-string-to-time
8010 (substring (match-string 1) 0 10))))
8011 (or (memq day dates) (push day dates)))
8012 (unless no-ranges
8013 (goto-char beg)
8014 (while (re-search-forward org-tr-regexp end t)
8015 (setq ts1 (substring (match-string 1) 0 10)
8016 ts2 (substring (match-string 2) 0 10)
8017 day1 (time-to-days (org-time-string-to-time ts1))
8018 day2 (time-to-days (org-time-string-to-time ts2)))
8019 (while (< (setq day1 (1+ day1)) day2)
8020 (or (memq day1 dates) (push day1 dates)))))
8021 (setq dates (sort dates '<))
8022 (when empty
8023 (while (setq day (pop dates))
8024 (setq day2 (car dates))
8025 (push day dates1)
8026 (when (and day2 empty)
8027 (if (or (eq empty t)
8028 (and (numberp empty) (<= (- day2 day) empty)))
8029 (while (< (setq day (1+ day)) day2)
8030 (push (list day) dates1))
8031 (push (cons :omitted (- day2 day)) dates1))))
8032 (setq dates (nreverse dates1)))
8033 dates)))
8035 ;;;###autoload
8036 (defun org-diary (&rest args)
8037 "Return diary information from org-files.
8038 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
8039 It accesses org files and extracts information from those files to be
8040 listed in the diary. The function accepts arguments specifying what
8041 items should be listed. The following arguments are allowed:
8043 :timestamp List the headlines of items containing a date stamp or
8044 date range matching the selected date. Deadlines will
8045 also be listed, on the expiration day.
8047 :deadline List any deadlines past due, or due within
8048 `org-deadline-warning-days'. The listing occurs only
8049 in the diary for *today*, not at any other date. If
8050 an entry is marked DONE, it is no longer listed.
8052 :scheduled List all items which are scheduled for the given date.
8053 The diary for *today* also contains items which were
8054 scheduled earlier and are not yet marked DONE.
8056 :todo List all TODO items from the org-file. This may be a
8057 long list - so this is not turned on by default.
8058 Like deadlines, these entries only show up in the
8059 diary for *today*, not at any other date.
8061 The call in the diary file should look like this:
8063 &%%(org-diary) ~/path/to/some/orgfile.org
8065 Use a separate line for each org file to check. Or, if you omit the file name,
8066 all files listed in `org-agenda-files' will be checked automatically:
8068 &%%(org-diary)
8070 If you don't give any arguments (as in the example above), the default
8071 arguments (:deadline :scheduled :timestamp) are used. So the example above may
8072 also be written as
8074 &%%(org-diary :deadline :timestamp :scheduled)
8076 The function expects the lisp variables `entry' and `date' to be provided
8077 by the caller, because this is how the calendar works. Don't use this
8078 function from a program - use `org-agenda-get-day-entries' instead."
8079 (org-agenda-maybe-reset-markers)
8080 (org-compile-prefix-format 'agenda)
8081 (org-set-sorting-strategy 'agenda)
8082 (setq args (or args '(:deadline :scheduled :timestamp)))
8083 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
8084 (list entry)
8085 (org-agenda-files t)))
8086 file rtn results)
8087 ;; If this is called during org-agenda, don't return any entries to
8088 ;; the calendar. Org Agenda will list these entries itself.
8089 (if org-disable-agenda-to-diary (setq files nil))
8090 (while (setq file (pop files))
8091 (setq rtn (apply 'org-agenda-get-day-entries file date args))
8092 (setq results (append results rtn)))
8093 (if results
8094 (concat (org-finalize-agenda-entries results) "\n"))))
8095 (defvar org-category-table nil)
8096 (defun org-get-category-table ()
8097 "Get the table of categories and positions in current buffer."
8098 (let (tbl)
8099 (save-excursion
8100 (goto-char (point-min))
8101 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
8102 (push (cons (point) (org-trim (match-string 2))) tbl)))
8103 tbl))
8104 (defun org-get-category (&optional pos)
8105 "Get the category applying to position POS."
8106 (if (not org-category-table)
8107 (cond
8108 ((null org-category)
8109 (setq org-category
8110 (if buffer-file-name
8111 (file-name-sans-extension
8112 (file-name-nondirectory buffer-file-name))
8113 "???")))
8114 ((symbolp org-category) (symbol-name org-category))
8115 (t org-category))
8116 (let ((tbl org-category-table)
8117 (pos (or pos (point))))
8118 (while (and tbl (> (caar tbl) pos))
8119 (pop tbl))
8120 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
8121 org-category-table))))))
8123 (defun org-agenda-get-day-entries (file date &rest args)
8124 "Does the work for `org-diary' and `org-agenda'.
8125 FILE is the path to a file to be checked for entries. DATE is date like
8126 the one returned by `calendar-current-date'. ARGS are symbols indicating
8127 which kind of entries should be extracted. For details about these, see
8128 the documentation of `org-diary'."
8129 (setq args (or args '(:deadline :scheduled :timestamp)))
8130 (let* ((org-startup-with-deadline-check nil)
8131 (org-startup-folded nil)
8132 (org-startup-align-all-tables nil)
8133 (buffer (if (file-exists-p file)
8134 (org-get-agenda-file-buffer file)
8135 (error "No such file %s" file)))
8136 arg results rtn)
8137 (if (not buffer)
8138 ;; If file does not exist, make sure an error message ends up in diary
8139 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8140 (with-current-buffer buffer
8141 (unless (org-mode-p)
8142 (error "Agenda file %s is not in `org-mode'" file))
8143 (setq org-category-table (org-get-category-table))
8144 (let ((case-fold-search nil))
8145 (save-excursion
8146 (save-restriction
8147 (if org-agenda-restrict
8148 (narrow-to-region org-agenda-restrict-begin
8149 org-agenda-restrict-end)
8150 (widen))
8151 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
8152 (while (setq arg (pop args))
8153 (cond
8154 ((and (eq arg :todo)
8155 (equal date (calendar-current-date)))
8156 (setq rtn (org-agenda-get-todos))
8157 (setq results (append results rtn)))
8158 ((eq arg :timestamp)
8159 (setq rtn (org-agenda-get-blocks))
8160 (setq results (append results rtn))
8161 (setq rtn (org-agenda-get-timestamps))
8162 (setq results (append results rtn)))
8163 ((eq arg :scheduled)
8164 (setq rtn (org-agenda-get-scheduled))
8165 (setq results (append results rtn)))
8166 ((eq arg :closed)
8167 (setq rtn (org-agenda-get-closed))
8168 (setq results (append results rtn)))
8169 ((and (eq arg :deadline)
8170 (equal date (calendar-current-date)))
8171 (setq rtn (org-agenda-get-deadlines))
8172 (setq results (append results rtn))))))))
8173 results))))
8175 (defun org-entry-is-done-p ()
8176 "Is the current entry marked DONE?"
8177 (save-excursion
8178 (and (re-search-backward "[\r\n]\\*" nil t)
8179 (looking-at org-nl-done-regexp))))
8181 (defun org-at-date-range-p (&optional inactive-ok)
8182 "Is the cursor inside a date range?"
8183 (interactive)
8184 (save-excursion
8185 (catch 'exit
8186 (let ((pos (point)))
8187 (skip-chars-backward "^[<\r\n")
8188 (skip-chars-backward "<[")
8189 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8190 (>= (match-end 0) pos)
8191 (throw 'exit t))
8192 (skip-chars-backward "^<[\r\n")
8193 (skip-chars-backward "<[")
8194 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8195 (>= (match-end 0) pos)
8196 (throw 'exit t)))
8197 nil)))
8199 (defun org-agenda-get-todos ()
8200 "Return the TODO information for agenda display."
8201 (let* ((props (list 'face nil
8202 'done-face 'org-done
8203 'org-not-done-regexp org-not-done-regexp
8204 'mouse-face 'highlight
8205 'keymap org-agenda-keymap
8206 'help-echo
8207 (format "mouse-2 or RET jump to org file %s"
8208 (abbreviate-file-name buffer-file-name))))
8209 (regexp (concat "[\n\r]\\*+ *\\("
8210 (if org-select-this-todo-keyword
8211 (concat "\\<\\(" org-select-this-todo-keyword
8212 "\\)\\>")
8213 org-not-done-regexp)
8214 "[^\n\r]*\\)"))
8215 (deadline-re (concat ".*\\(\n[^*].*\\)?" org-deadline-time-regexp))
8216 (sched-re (concat ".*\\(\n[^*].*\\)?" org-scheduled-time-regexp))
8217 ; FIXME why was this wrong? (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
8218 marker priority category tags
8219 ee txt)
8220 (goto-char (point-min))
8221 (while (re-search-forward regexp nil t)
8222 (catch :skip
8223 (save-match-data
8224 (beginning-of-line)
8225 (when (or (and org-agenda-todo-ignore-scheduled
8226 (looking-at sched-re))
8227 (and org-agenda-todo-ignore-deadlines
8228 (looking-at deadline-re)
8229 (org-deadline-close (match-string 2))))
8231 ;; FIXME: the following test also happens below, but we need it here
8232 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
8233 (throw :skip nil)))
8234 (org-agenda-skip)
8235 (goto-char (match-beginning 1))
8236 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
8237 category (org-get-category)
8238 tags (org-get-tags-at (point))
8239 txt (org-format-agenda-item "" (match-string 1) category tags)
8240 priority
8241 (+ (org-get-priority txt)
8242 (if org-todo-kwd-priority-p
8243 (- org-todo-kwd-max-priority -2
8244 (length
8245 (member (match-string 2) org-todo-keywords)))
8246 1)))
8247 (org-add-props txt props
8248 'org-marker marker 'org-hd-marker marker
8249 'priority priority 'category category)
8250 (push txt ee)
8251 (if org-agenda-todo-list-sublevels
8252 (goto-char (match-end 1))
8253 (org-end-of-subtree 'invisible))))
8254 (nreverse ee)))
8256 (defconst org-agenda-no-heading-message
8257 "No heading for this item in buffer or region.")
8259 (defun org-agenda-get-timestamps ()
8260 "Return the date stamp information for agenda display."
8261 (let* ((props (list 'face nil
8262 'org-not-done-regexp org-not-done-regexp
8263 'mouse-face 'highlight
8264 'keymap org-agenda-keymap
8265 'help-echo
8266 (format "mouse-2 or RET jump to org file %s"
8267 (abbreviate-file-name buffer-file-name))))
8268 (regexp (regexp-quote
8269 (substring
8270 (format-time-string
8271 (car org-time-stamp-formats)
8272 (apply 'encode-time ; DATE bound by calendar
8273 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8274 0 11)))
8275 marker hdmarker deadlinep scheduledp donep tmp priority category
8276 ee txt timestr tags)
8277 (goto-char (point-min))
8278 (while (re-search-forward regexp nil t)
8279 (catch :skip
8280 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
8281 (org-agenda-skip)
8282 (setq marker (org-agenda-new-marker (match-beginning 0))
8283 category (org-get-category (match-beginning 0))
8284 tmp (buffer-substring (max (point-min)
8285 (- (match-beginning 0)
8286 org-ds-keyword-length))
8287 (match-beginning 0))
8288 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8289 deadlinep (string-match org-deadline-regexp tmp)
8290 scheduledp (string-match org-scheduled-regexp tmp)
8291 donep (org-entry-is-done-p))
8292 (if (string-match ">" timestr)
8293 ;; substring should only run to end of time stamp
8294 (setq timestr (substring timestr 0 (match-end 0))))
8295 (save-excursion
8296 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8297 (progn
8298 (goto-char (match-end 1))
8299 (setq hdmarker (org-agenda-new-marker)
8300 tags (org-get-tags-at))
8301 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8302 (setq txt (org-format-agenda-item
8303 (format "%s%s"
8304 (if deadlinep "Deadline: " "")
8305 (if scheduledp "Scheduled: " ""))
8306 (match-string 1) category tags timestr)))
8307 (setq txt org-agenda-no-heading-message))
8308 (setq priority (org-get-priority txt))
8309 (org-add-props txt props
8310 'org-marker marker 'org-hd-marker hdmarker)
8311 (if deadlinep
8312 (org-add-props txt nil
8313 'face (if donep 'org-done 'org-warning)
8314 'undone-face 'org-warning 'done-face 'org-done
8315 'category category 'priority (+ 100 priority))
8316 (if scheduledp
8317 (org-add-props txt nil
8318 'face 'org-scheduled-today
8319 'undone-face 'org-scheduled-today 'done-face 'org-done
8320 'category category 'priority (+ 99 priority))
8321 (org-add-props txt nil 'priority priority 'category category)))
8322 (push txt ee))
8323 (outline-next-heading)))
8324 (nreverse ee)))
8326 (defun org-agenda-get-closed ()
8327 "Return the logged TODO entries for agenda display."
8328 (let* ((props (list 'mouse-face 'highlight
8329 'org-not-done-regexp org-not-done-regexp
8330 'keymap org-agenda-keymap
8331 'help-echo
8332 (format "mouse-2 or RET jump to org file %s"
8333 (abbreviate-file-name buffer-file-name))))
8334 (regexp (concat
8335 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
8336 (regexp-quote
8337 (substring
8338 (format-time-string
8339 (car org-time-stamp-formats)
8340 (apply 'encode-time ; DATE bound by calendar
8341 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8342 1 11))))
8343 marker hdmarker priority category tags closedp
8344 ee txt timestr)
8345 (goto-char (point-min))
8346 (while (re-search-forward regexp nil t)
8347 (catch :skip
8348 (org-agenda-skip)
8349 (setq marker (org-agenda-new-marker (match-beginning 0))
8350 closedp (equal (match-string 1) org-closed-string)
8351 category (org-get-category (match-beginning 0))
8352 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8353 ;; donep (org-entry-is-done-p)
8355 (if (string-match "\\]" timestr)
8356 ;; substring should only run to end of time stamp
8357 (setq timestr (substring timestr 0 (match-end 0))))
8358 (save-excursion
8359 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8360 (progn
8361 (goto-char (match-end 1))
8362 (setq hdmarker (org-agenda-new-marker)
8363 tags (org-get-tags-at))
8364 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8365 (setq txt (org-format-agenda-item
8366 (if closedp "Closed: " "Clocked: ")
8367 (match-string 1) category tags timestr)))
8368 (setq txt org-agenda-no-heading-message))
8369 (setq priority 100000)
8370 (org-add-props txt props
8371 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
8372 'priority priority 'category category
8373 'undone-face 'org-warning 'done-face 'org-done)
8374 (push txt ee))
8375 (outline-next-heading)))
8376 (nreverse ee)))
8378 (defun org-agenda-get-deadlines ()
8379 "Return the deadline information for agenda display."
8380 (let* ((wdays org-deadline-warning-days)
8381 (props (list 'mouse-face 'highlight
8382 'org-not-done-regexp org-not-done-regexp
8383 'keymap org-agenda-keymap
8384 'help-echo
8385 (format "mouse-2 or RET jump to org file %s"
8386 (abbreviate-file-name buffer-file-name))))
8387 (regexp org-deadline-time-regexp)
8388 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8389 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8390 d2 diff pos pos1 category tags
8391 ee txt head face)
8392 (goto-char (point-min))
8393 (while (re-search-forward regexp nil t)
8394 (catch :skip
8395 (org-agenda-skip)
8396 (setq pos (1- (match-beginning 1))
8397 d2 (time-to-days
8398 (org-time-string-to-time (match-string 1)))
8399 diff (- d2 d1))
8400 ;; When to show a deadline in the calendar:
8401 ;; If the expiration is within wdays warning time.
8402 ;; Past-due deadlines are only shown on the current date
8403 (if (and (< diff wdays) todayp (not (= diff 0)))
8404 (save-excursion
8405 (setq category (org-get-category))
8406 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8407 (progn
8408 (goto-char (match-end 0))
8409 (setq pos1 (match-end 1))
8410 (setq tags (org-get-tags-at pos1))
8411 (setq head (buffer-substring-no-properties
8412 (point)
8413 (progn (skip-chars-forward "^\r\n")
8414 (point))))
8415 (if (string-match org-looking-at-done-regexp head)
8416 (setq txt nil)
8417 (setq txt (org-format-agenda-item
8418 (format "In %3d d.: " diff) head category tags))))
8419 (setq txt org-agenda-no-heading-message))
8420 (when txt
8421 (setq face (cond ((<= diff 0) 'org-warning)
8422 ((<= diff 5) 'org-upcoming-deadline)
8423 (t nil)))
8424 (org-add-props txt props
8425 'org-marker (org-agenda-new-marker pos)
8426 'org-hd-marker (org-agenda-new-marker pos1)
8427 'priority (+ (- 10 diff) (org-get-priority txt))
8428 'category category
8429 'face face 'undone-face face 'done-face 'org-done)
8430 (push txt ee))))))
8431 ee))
8433 (defun org-agenda-get-scheduled ()
8434 "Return the scheduled information for agenda display."
8435 (let* ((props (list 'face 'org-scheduled-previously
8436 'org-not-done-regexp org-not-done-regexp
8437 'undone-face 'org-scheduled-previously
8438 'done-face 'org-done
8439 'mouse-face 'highlight
8440 'keymap org-agenda-keymap
8441 'help-echo
8442 (format "mouse-2 or RET jump to org file %s"
8443 (abbreviate-file-name buffer-file-name))))
8444 (regexp org-scheduled-time-regexp)
8445 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8446 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8447 d2 diff pos pos1 category tags
8448 ee txt head)
8449 (goto-char (point-min))
8450 (while (re-search-forward regexp nil t)
8451 (catch :skip
8452 (org-agenda-skip)
8453 (setq pos (1- (match-beginning 1))
8454 d2 (time-to-days
8455 (org-time-string-to-time (match-string 1)))
8456 diff (- d2 d1))
8457 ;; When to show a scheduled item in the calendar:
8458 ;; If it is on or past the date.
8459 (if (and (< diff 0) todayp)
8460 (save-excursion
8461 (setq category (org-get-category))
8462 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8463 (progn
8464 (goto-char (match-end 0))
8465 (setq pos1 (match-end 1))
8466 (setq tags (org-get-tags-at))
8467 (setq head (buffer-substring-no-properties
8468 (point)
8469 (progn (skip-chars-forward "^\r\n") (point))))
8470 (if (string-match org-looking-at-done-regexp head)
8471 (setq txt nil)
8472 (setq txt (org-format-agenda-item
8473 (format "Sched.%2dx: " (- 1 diff)) head
8474 category tags))))
8475 (setq txt org-agenda-no-heading-message))
8476 (when txt
8477 (org-add-props txt props
8478 'org-marker (org-agenda-new-marker pos)
8479 'org-hd-marker (org-agenda-new-marker pos1)
8480 'priority (+ (- 5 diff) (org-get-priority txt))
8481 'category category)
8482 (push txt ee))))))
8483 ee))
8485 (defun org-agenda-get-blocks ()
8486 "Return the date-range information for agenda display."
8487 (let* ((props (list 'face nil
8488 'org-not-done-regexp org-not-done-regexp
8489 'mouse-face 'highlight
8490 'keymap org-agenda-keymap
8491 'help-echo
8492 (format "mouse-2 or RET jump to org file %s"
8493 (abbreviate-file-name buffer-file-name))))
8494 (regexp org-tr-regexp)
8495 (d0 (calendar-absolute-from-gregorian date))
8496 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
8497 (goto-char (point-min))
8498 (while (re-search-forward regexp nil t)
8499 (catch :skip
8500 (org-agenda-skip)
8501 (setq pos (point))
8502 (setq timestr (match-string 0)
8503 s1 (match-string 1)
8504 s2 (match-string 2)
8505 d1 (time-to-days (org-time-string-to-time s1))
8506 d2 (time-to-days (org-time-string-to-time s2)))
8507 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
8508 ;; Only allow days between the limits, because the normal
8509 ;; date stamps will catch the limits.
8510 (save-excursion
8511 (setq marker (org-agenda-new-marker (point)))
8512 (setq category (org-get-category))
8513 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8514 (progn
8515 (setq hdmarker (org-agenda-new-marker (match-end 1)))
8516 (goto-char (match-end 1))
8517 (setq tags (org-get-tags-at))
8518 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8519 (setq txt (org-format-agenda-item
8520 (format (if (= d1 d2) "" "(%d/%d): ")
8521 (1+ (- d0 d1)) (1+ (- d2 d1)))
8522 (match-string 1) category tags
8523 (if (= d0 d1) timestr))))
8524 (setq txt org-agenda-no-heading-message))
8525 (org-add-props txt props
8526 'org-marker marker 'org-hd-marker hdmarker
8527 'priority (org-get-priority txt) 'category category)
8528 (push txt ee)))
8529 (goto-char pos)))
8530 ;; Sort the entries by expiration date.
8531 (nreverse ee)))
8533 (defconst org-plain-time-of-day-regexp
8534 (concat
8535 "\\(\\<[012]?[0-9]"
8536 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8537 "\\(--?"
8538 "\\(\\<[012]?[0-9]"
8539 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8540 "\\)?")
8541 "Regular expression to match a plain time or time range.
8542 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
8543 groups carry important information:
8544 0 the full match
8545 1 the first time, range or not
8546 8 the second time, if it is a range.")
8548 (defconst org-stamp-time-of-day-regexp
8549 (concat
8550 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
8551 "\\([012][0-9]:[0-5][0-9]\\)>"
8552 "\\(--?"
8553 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
8554 "Regular expression to match a timestamp time or time range.
8555 After a match, the following groups carry important information:
8556 0 the full match
8557 1 date plus weekday, for backreferencing to make sure both times on same day
8558 2 the first time, range or not
8559 4 the second time, if it is a range.")
8561 (defvar org-prefix-has-time nil
8562 "A flag, set by `org-compile-prefix-format'.
8563 The flag is set if the currently compiled format contains a `%t'.")
8564 (defvar org-prefix-has-tag nil
8565 "A flag, set by `org-compile-prefix-format'.
8566 The flag is set if the currently compiled format contains a `%T'.")
8568 (defun org-format-agenda-item (extra txt &optional category tags dotime
8569 noprefix)
8570 "Format TXT to be inserted into the agenda buffer.
8571 In particular, it adds the prefix and corresponding text properties. EXTRA
8572 must be a string and replaces the `%s' specifier in the prefix format.
8573 CATEGORY (string, symbol or nil) may be used to overrule the default
8574 category taken from local variable or file name. It will replace the `%c'
8575 specifier in the format. DOTIME, when non-nil, indicates that a
8576 time-of-day should be extracted from TXT for sorting of this entry, and for
8577 the `%t' specifier in the format. When DOTIME is a string, this string is
8578 searched for a time before TXT is. NOPREFIX is a flag and indicates that
8579 only the correctly processes TXT should be returned - this is used by
8580 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
8581 (save-match-data
8582 ;; Diary entries sometimes have extra whitespace at the beginning
8583 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
8584 (let* ((category (or category
8585 org-category
8586 (if buffer-file-name
8587 (file-name-sans-extension
8588 (file-name-nondirectory buffer-file-name))
8589 "")))
8590 (tag (if tags (nth (1- (length tags)) tags) ""))
8591 time ;; needed for the eval of the prefix format
8592 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
8593 (time-of-day (and dotime (org-get-time-of-day ts)))
8594 stamp plain s0 s1 s2 rtn)
8595 (when (and dotime time-of-day org-prefix-has-time)
8596 ;; Extract starting and ending time and move them to prefix
8597 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
8598 (setq plain (string-match org-plain-time-of-day-regexp ts)))
8599 (setq s0 (match-string 0 ts)
8600 s1 (match-string (if plain 1 2) ts)
8601 s2 (match-string (if plain 8 4) ts))
8603 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
8604 ;; them, we might want to remove them there to avoid duplication.
8605 ;; The user can turn this off with a variable.
8606 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
8607 (string-match (concat (regexp-quote s0) " *") txt)
8608 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
8609 (= (match-beginning 0) 0)
8611 (setq txt (replace-match "" nil nil txt))))
8612 ;; Normalize the time(s) to 24 hour
8613 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
8614 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
8616 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
8617 ;; Tags are in the string
8618 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
8619 (and org-agenda-remove-tags-when-in-prefix
8620 org-prefix-has-tag))
8621 (setq txt (replace-match "" t t txt))
8622 (setq txt (replace-match
8623 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
8624 (match-string 2 txt))
8625 t t txt))))
8627 ;; Create the final string
8628 (if noprefix
8629 (setq rtn txt)
8630 ;; Prepare the variables needed in the eval of the compiled format
8631 (setq time (cond (s2 (concat s1 "-" s2))
8632 (s1 (concat s1 "......"))
8633 (t ""))
8634 extra (or extra "")
8635 category (if (symbolp category) (symbol-name category) category))
8636 ;; Evaluate the compiled format
8637 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
8639 ;; And finally add the text properties
8640 (org-add-props rtn nil
8641 'category (downcase category) 'tags tags
8642 'prefix-length (- (length rtn) (length txt))
8643 'time-of-day time-of-day
8644 'dotime dotime))))
8646 (defvar org-agenda-sorting-strategy)
8647 (defvar org-agenda-sorting-strategy-selected nil)
8649 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
8650 (catch 'exit
8651 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
8652 ((and todayp (member 'today (car org-agenda-time-grid))))
8653 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
8654 ((member 'weekly (car org-agenda-time-grid)))
8655 (t (throw 'exit list)))
8656 (let* ((have (delq nil (mapcar
8657 (lambda (x) (get-text-property 1 'time-of-day x))
8658 list)))
8659 (string (nth 1 org-agenda-time-grid))
8660 (gridtimes (nth 2 org-agenda-time-grid))
8661 (req (car org-agenda-time-grid))
8662 (remove (member 'remove-match req))
8663 new time)
8664 (if (and (member 'require-timed req) (not have))
8665 ;; don't show empty grid
8666 (throw 'exit list))
8667 (while (setq time (pop gridtimes))
8668 (unless (and remove (member time have))
8669 (setq time (int-to-string time))
8670 (push (org-format-agenda-item
8671 nil string "" nil
8672 (concat (substring time 0 -2) ":" (substring time -2)))
8673 new)
8674 (put-text-property
8675 1 (length (car new)) 'face 'org-time-grid (car new))))
8676 (if (member 'time-up org-agenda-sorting-strategy-selected)
8677 (append new list)
8678 (append list new)))))
8680 (defun org-compile-prefix-format (key)
8681 "Compile the prefix format into a Lisp form that can be evaluated.
8682 The resulting form is returned and stored in the variable
8683 `org-prefix-format-compiled'."
8684 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8685 (let ((s (cond
8686 ((stringp org-agenda-prefix-format)
8687 org-agenda-prefix-format)
8688 ((assq key org-agenda-prefix-format)
8689 (cdr (assq key org-agenda-prefix-format)))
8690 (t " %-12:c%?-12t% s")))
8691 (start 0)
8692 varform vars var e c f opt)
8693 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8694 s start)
8695 (setq var (cdr (assoc (match-string 4 s)
8696 '(("c" . category) ("t" . time) ("s" . extra)
8697 ("T" . tag))))
8698 c (or (match-string 3 s) "")
8699 opt (match-beginning 1)
8700 start (1+ (match-beginning 0)))
8701 (if (equal var 'time) (setq org-prefix-has-time t))
8702 (if (equal var 'tag) (setq org-prefix-has-tag t))
8703 (setq f (concat "%" (match-string 2 s) "s"))
8704 (if opt
8705 (setq varform
8706 `(if (equal "" ,var)
8708 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8709 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8710 (setq s (replace-match "%s" t nil s))
8711 (push varform vars))
8712 (setq vars (nreverse vars))
8713 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8715 (defun org-set-sorting-strategy (key)
8716 (if (symbolp (car org-agenda-sorting-strategy))
8717 ;; the old format
8718 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
8719 (setq org-agenda-sorting-strategy-selected
8720 (or (cdr (assq key org-agenda-sorting-strategy))
8721 (cdr (assq 'agenda org-agenda-sorting-strategy))
8722 '(time-up category-keep priority-down)))))
8724 (defun org-get-time-of-day (s &optional string mod24)
8725 "Check string S for a time of day.
8726 If found, return it as a military time number between 0 and 2400.
8727 If not found, return nil.
8728 The optional STRING argument forces conversion into a 5 character wide string
8729 HH:MM."
8730 (save-match-data
8731 (when
8733 (string-match
8734 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8735 (string-match
8736 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8737 (let* ((h (string-to-number (match-string 1 s)))
8738 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8739 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8740 (am-p (equal ampm "am"))
8741 (h1 (cond ((not ampm) h)
8742 ((= h 12) (if am-p 0 12))
8743 (t (+ h (if am-p 0 12)))))
8744 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8745 (mod h1 24) h1))
8746 (t0 (+ (* 100 h2) m))
8747 (t1 (concat (if (>= h1 24) "+" " ")
8748 (if (< t0 100) "0" "")
8749 (if (< t0 10) "0" "")
8750 (int-to-string t0))))
8751 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8753 (defun org-finalize-agenda-entries (list &optional nosort)
8754 "Sort and concatenate the agenda items."
8755 (setq list (mapcar 'org-agenda-highlight-todo list))
8756 (if nosort
8757 list
8758 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
8760 (defun org-agenda-highlight-todo (x)
8761 (let (re pl)
8762 (if (eq x 'line)
8763 (save-excursion
8764 (beginning-of-line 1)
8765 (setq re (get-text-property (point) 'org-not-done-regexp))
8766 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
8767 (and (looking-at (concat "[ \t]*\\.*" re))
8768 (add-text-properties (match-beginning 0) (match-end 0)
8769 '(face org-todo))))
8770 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
8771 pl (get-text-property 0 'prefix-length x))
8772 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
8773 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
8774 '(face org-todo) x))
8775 x)))
8777 (defsubst org-cmp-priority (a b)
8778 "Compare the priorities of string A and B."
8779 (let ((pa (or (get-text-property 1 'priority a) 0))
8780 (pb (or (get-text-property 1 'priority b) 0)))
8781 (cond ((> pa pb) +1)
8782 ((< pa pb) -1)
8783 (t nil))))
8785 (defsubst org-cmp-category (a b)
8786 "Compare the string values of categories of strings A and B."
8787 (let ((ca (or (get-text-property 1 'category a) ""))
8788 (cb (or (get-text-property 1 'category b) "")))
8789 (cond ((string-lessp ca cb) -1)
8790 ((string-lessp cb ca) +1)
8791 (t nil))))
8793 (defsubst org-cmp-tag (a b)
8794 "Compare the string values of categories of strings A and B."
8795 (let ((ta (car (last (get-text-property 1 'tags a))))
8796 (tb (car (last (get-text-property 1 'tags b)))))
8797 (cond ((not ta) +1)
8798 ((not tb) -1)
8799 ((string-lessp ta tb) -1)
8800 ((string-lessp tb ta) +1)
8801 (t nil))))
8803 (defsubst org-cmp-time (a b)
8804 "Compare the time-of-day values of strings A and B."
8805 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8806 (ta (or (get-text-property 1 'time-of-day a) def))
8807 (tb (or (get-text-property 1 'time-of-day b) def)))
8808 (cond ((< ta tb) -1)
8809 ((< tb ta) +1)
8810 (t nil))))
8812 (defun org-entries-lessp (a b)
8813 "Predicate for sorting agenda entries."
8814 ;; The following variables will be used when the form is evaluated.
8815 (let* ((time-up (org-cmp-time a b))
8816 (time-down (if time-up (- time-up) nil))
8817 (priority-up (org-cmp-priority a b))
8818 (priority-down (if priority-up (- priority-up) nil))
8819 (category-up (org-cmp-category a b))
8820 (category-down (if category-up (- category-up) nil))
8821 (category-keep (if category-up +1 nil))
8822 (tag-up (org-cmp-tag a b))
8823 (tag-down (if tag-up (- tag-up) nil)))
8824 (cdr (assoc
8825 (eval (cons 'or org-agenda-sorting-strategy-selected))
8826 '((-1 . t) (1 . nil) (nil . nil))))))
8828 (defun org-agenda-show-priority ()
8829 "Show the priority of the current item.
8830 This priority is composed of the main priority given with the [#A] cookies,
8831 and by additional input from the age of a schedules or deadline entry."
8832 (interactive)
8833 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8834 (message "Priority is %d" (if pri pri -1000))))
8836 (defun org-agenda-show-tags ()
8837 "Show the tags applicable to the current item."
8838 (interactive)
8839 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8840 (if tags
8841 (message "Tags are :%s:"
8842 (org-no-properties (mapconcat 'identity tags ":")))
8843 (message "No tags associated with this line"))))
8845 (defun org-agenda-goto (&optional highlight)
8846 "Go to the Org-mode file which contains the item at point."
8847 (interactive)
8848 (let* ((marker (or (get-text-property (point) 'org-marker)
8849 (org-agenda-error)))
8850 (buffer (marker-buffer marker))
8851 (pos (marker-position marker)))
8852 (switch-to-buffer-other-window buffer)
8853 (widen)
8854 (goto-char pos)
8855 (when (org-mode-p)
8856 (org-show-context 'agenda)
8857 (save-excursion
8858 (and (outline-next-heading)
8859 (org-flag-heading nil)))) ; show the next heading
8860 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8862 (defun org-agenda-kill ()
8863 "Kill the entry or subtree belonging to the current agenda entry."
8864 (interactive)
8865 (let* ((marker (or (get-text-property (point) 'org-marker)
8866 (org-agenda-error)))
8867 (hdmarker (get-text-property (point) 'org-hd-marker))
8868 (buffer (marker-buffer marker))
8869 (pos (marker-position marker))
8870 dbeg dend txt n conf)
8871 (with-current-buffer buffer
8872 (save-excursion
8873 (goto-char pos)
8874 (if (org-mode-p)
8875 (setq dbeg (progn (org-back-to-heading t) (point))
8876 dend (org-end-of-subtree t))
8877 (setq dbeg (point-at-bol)
8878 dend (min (point-max) (1+ (point-at-eol)))))
8879 (setq txt (buffer-substring dbeg dend))))
8880 (while (string-match "^[ \t]*\n" txt) (setq txt (replace-match "" t t txt)))
8881 (setq n (length (split-string txt "\n"))
8882 conf (or (eq t org-agenda-confirm-kill)
8883 (and (numberp org-agenda-confirm-kill)
8884 (> n org-agenda-confirm-kill))))
8885 (and conf
8886 (not (y-or-n-p
8887 (format "Delete entry with %d lines in buffer \"%s\"? "
8888 n (buffer-name buffer))))
8889 (error "Abort"))
8890 ;; FIXME: if we kill an entire subtree, should we not find all
8891 ;; lines coming from the subtree?
8892 (save-excursion (org-agenda-change-all-lines "" hdmarker))
8893 (with-current-buffer buffer (delete-region dbeg dend))
8894 (message "Agenda item and source killed")))
8896 (defun org-agenda-switch-to (&optional delete-other-windows)
8897 "Go to the Org-mode file which contains the item at point."
8898 (interactive)
8899 (let* ((marker (or (get-text-property (point) 'org-marker)
8900 (org-agenda-error)))
8901 (buffer (marker-buffer marker))
8902 (pos (marker-position marker)))
8903 (switch-to-buffer buffer)
8904 (and delete-other-windows (delete-other-windows))
8905 (widen)
8906 (goto-char pos)
8907 (when (org-mode-p)
8908 (org-show-context 'agenda)
8909 (save-excursion
8910 (and (outline-next-heading)
8911 (org-flag-heading nil)))))) ; show the next heading
8913 (defun org-agenda-goto-mouse (ev)
8914 "Go to the Org-mode file which contains the item at the mouse click."
8915 (interactive "e")
8916 (mouse-set-point ev)
8917 (org-agenda-goto))
8919 (defun org-agenda-show ()
8920 "Display the Org-mode file which contains the item at point."
8921 (interactive)
8922 (let ((win (selected-window)))
8923 (org-agenda-goto t)
8924 (select-window win)))
8926 (defun org-agenda-recenter (arg)
8927 "Display the Org-mode file which contains the item at point and recenter."
8928 (interactive "P")
8929 (let ((win (selected-window)))
8930 (org-agenda-goto t)
8931 (recenter arg)
8932 (select-window win)))
8934 (defun org-agenda-show-mouse (ev)
8935 "Display the Org-mode file which contains the item at the mouse click."
8936 (interactive "e")
8937 (mouse-set-point ev)
8938 (org-agenda-show))
8940 (defun org-agenda-check-no-diary ()
8941 "Check if the entry is a diary link and abort if yes."
8942 (if (get-text-property (point) 'org-agenda-diary-link)
8943 (org-agenda-error)))
8945 (defun org-agenda-error ()
8946 (error "Command not allowed in this line"))
8948 (defvar org-last-heading-marker (make-marker)
8949 "Marker pointing to the headline that last changed its TODO state
8950 by a remote command from the agenda.")
8952 (defun org-agenda-todo (&optional arg)
8953 "Cycle TODO state of line at point, also in Org-mode file.
8954 This changes the line at point, all other lines in the agenda referring to
8955 the same tree node, and the headline of the tree node in the Org-mode file."
8956 (interactive "P")
8957 (org-agenda-check-no-diary)
8958 (let* ((col (current-column))
8959 (marker (or (get-text-property (point) 'org-marker)
8960 (org-agenda-error)))
8961 (buffer (marker-buffer marker))
8962 (pos (marker-position marker))
8963 (hdmarker (get-text-property (point) 'org-hd-marker))
8964 (buffer-read-only nil)
8965 newhead)
8966 (with-current-buffer buffer
8967 (widen)
8968 (goto-char pos)
8969 (org-show-context 'agenda)
8970 (save-excursion
8971 (and (outline-next-heading)
8972 (org-flag-heading nil))) ; show the next heading
8973 (org-todo arg)
8974 (and (bolp) (forward-char 1))
8975 (setq newhead (org-get-heading))
8976 (save-excursion
8977 (org-back-to-heading)
8978 (move-marker org-last-heading-marker (point))))
8979 (beginning-of-line 1)
8980 (save-excursion
8981 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8982 (move-to-column col)))
8984 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8985 "Change all lines in the agenda buffer which match HDMARKER.
8986 The new content of the line will be NEWHEAD (as modified by
8987 `org-format-agenda-item'). HDMARKER is checked with
8988 `equal' against all `org-hd-marker' text properties in the file.
8989 If FIXFACE is non-nil, the face of each item is modified acording to
8990 the new TODO state."
8991 (let* ((buffer-read-only nil)
8992 props m pl undone-face done-face finish new dotime cat tags)
8993 (save-excursion
8994 (goto-char (point-max))
8995 (beginning-of-line 1)
8996 (while (not finish)
8997 (setq finish (bobp))
8998 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8999 (equal m hdmarker))
9000 (setq props (text-properties-at (point))
9001 dotime (get-text-property (point) 'dotime)
9002 cat (get-text-property (point) 'category)
9003 tags (get-text-property (point) 'tags)
9004 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
9005 pl (get-text-property (point) 'prefix-length)
9006 undone-face (get-text-property (point) 'undone-face)
9007 done-face (get-text-property (point) 'done-face))
9008 (move-to-column pl)
9009 (cond
9010 ((equal new "")
9011 (beginning-of-line 1)
9012 (and (looking-at ".*\n?") (replace-match "")))
9013 ((looking-at ".*")
9014 (replace-match new t t)
9015 (beginning-of-line 1)
9016 (add-text-properties (point-at-bol) (point-at-eol) props)
9017 (when fixface
9018 (add-text-properties
9019 (point-at-bol) (point-at-eol)
9020 (list 'face
9021 (if org-last-todo-state-is-todo
9022 undone-face done-face))))
9023 (org-agenda-highlight-todo 'line)
9024 (beginning-of-line 1))
9025 (t (error "Line update did not work"))))
9026 (beginning-of-line 0)))
9027 (org-finalize-agenda)))
9029 (defun org-agenda-align-tags (&optional line)
9030 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
9031 (let ((buffer-read-only))
9032 (save-excursion
9033 (goto-char (if line (point-at-bol) (point-min)))
9034 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
9035 (if line (point-at-eol) nil) t)
9036 (delete-region (match-beginning 1) (match-end 1))
9037 (goto-char (match-beginning 1))
9038 (insert (org-add-props
9039 (make-string (max 1 (- org-agenda-align-tags-to-column
9040 (current-column))) ?\ )
9041 (text-properties-at (point))))))))
9043 (defun org-agenda-priority-up ()
9044 "Increase the priority of line at point, also in Org-mode file."
9045 (interactive)
9046 (org-agenda-priority 'up))
9048 (defun org-agenda-priority-down ()
9049 "Decrease the priority of line at point, also in Org-mode file."
9050 (interactive)
9051 (org-agenda-priority 'down))
9053 (defun org-agenda-priority (&optional force-direction)
9054 "Set the priority of line at point, also in Org-mode file.
9055 This changes the line at point, all other lines in the agenda referring to
9056 the same tree node, and the headline of the tree node in the Org-mode file."
9057 (interactive)
9058 (org-agenda-check-no-diary)
9059 (let* ((marker (or (get-text-property (point) 'org-marker)
9060 (org-agenda-error)))
9061 (buffer (marker-buffer marker))
9062 (pos (marker-position marker))
9063 (hdmarker (get-text-property (point) 'org-hd-marker))
9064 (buffer-read-only nil)
9065 newhead)
9066 (with-current-buffer buffer
9067 (widen)
9068 (goto-char pos)
9069 (org-show-context 'agenda)
9070 (save-excursion
9071 (and (outline-next-heading)
9072 (org-flag-heading nil))) ; show the next heading
9073 (funcall 'org-priority force-direction)
9074 (end-of-line 1)
9075 (setq newhead (org-get-heading)))
9076 (org-agenda-change-all-lines newhead hdmarker)
9077 (beginning-of-line 1)))
9079 (defun org-get-tags-at (&optional pos)
9080 "Get a list of all headline tags applicable at POS.
9081 POS defaults to point. If tags are inherited, the list contains
9082 the targets in the same sequence as the headlines appear, i.e.
9083 the tags of the current headline come last."
9084 (interactive)
9085 (let (tags)
9086 (save-excursion
9087 (goto-char (or pos (point)))
9088 (save-match-data
9089 (org-back-to-heading t)
9090 (condition-case nil
9091 (while t
9092 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
9093 (setq tags (append (org-split-string
9094 (org-match-string-no-properties 1) ":")
9095 tags)))
9096 (or org-use-tag-inheritance (error ""))
9097 (org-up-heading-all 1))
9098 (error nil))))
9099 tags))
9101 ;; FIXME: should fix the tags property of the agenda line.
9102 (defun org-agenda-set-tags ()
9103 "Set tags for the current headline."
9104 (interactive)
9105 (org-agenda-check-no-diary)
9106 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
9107 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
9108 (org-agenda-error)))
9109 (buffer (marker-buffer hdmarker))
9110 (pos (marker-position hdmarker))
9111 (buffer-read-only nil)
9112 newhead)
9113 (with-current-buffer buffer
9114 (widen)
9115 (goto-char pos)
9116 (org-show-context 'agenda)
9117 (save-excursion
9118 (and (outline-next-heading)
9119 (org-flag-heading nil))) ; show the next heading
9120 (call-interactively 'org-set-tags)
9121 (end-of-line 1)
9122 (setq newhead (org-get-heading)))
9123 (org-agenda-change-all-lines newhead hdmarker)
9124 (beginning-of-line 1)))
9126 (defun org-agenda-date-later (arg &optional what)
9127 "Change the date of this item to one day later."
9128 (interactive "p")
9129 (org-agenda-check-type t 'agenda 'timeline)
9130 (org-agenda-check-no-diary)
9131 (let* ((marker (or (get-text-property (point) 'org-marker)
9132 (org-agenda-error)))
9133 (buffer (marker-buffer marker))
9134 (pos (marker-position marker)))
9135 (with-current-buffer buffer
9136 (widen)
9137 (goto-char pos)
9138 (if (not (org-at-timestamp-p))
9139 (error "Cannot find time stamp"))
9140 (org-timestamp-change arg (or what 'day))
9141 (message "Time stamp changed to %s" org-last-changed-timestamp))))
9143 (defun org-agenda-date-earlier (arg &optional what)
9144 "Change the date of this item to one day earlier."
9145 (interactive "p")
9146 (org-agenda-date-later (- arg) what))
9148 (defun org-agenda-date-prompt (arg)
9149 "Change the date of this item. Date is prompted for, with default today.
9150 The prefix ARG is passed to the `org-time-stamp' command and can therefore
9151 be used to request time specification in the time stamp."
9152 (interactive "P")
9153 (org-agenda-check-type t 'agenda 'timeline)
9154 (org-agenda-check-no-diary)
9155 (let* ((marker (or (get-text-property (point) 'org-marker)
9156 (org-agenda-error)))
9157 (buffer (marker-buffer marker))
9158 (pos (marker-position marker)))
9159 (with-current-buffer buffer
9160 (widen)
9161 (goto-char pos)
9162 (if (not (org-at-timestamp-p))
9163 (error "Cannot find time stamp"))
9164 (org-time-stamp arg)
9165 (message "Time stamp changed to %s" org-last-changed-timestamp))))
9167 (defun org-agenda-schedule (arg)
9168 "Schedule the item at point."
9169 (interactive "P")
9170 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9171 (org-agenda-check-no-diary)
9172 (let* ((marker (or (get-text-property (point) 'org-marker)
9173 (org-agenda-error)))
9174 (buffer (marker-buffer marker))
9175 (pos (marker-position marker))
9176 (org-insert-labeled-timestamps-at-point nil)
9178 (with-current-buffer buffer
9179 (widen)
9180 (goto-char pos)
9181 (setq ts (org-schedule))
9182 (message "Item scheduled for %s" ts))))
9184 (defun org-agenda-deadline (arg)
9185 "Schedule the item at point."
9186 (interactive "P")
9187 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9188 (org-agenda-check-no-diary)
9189 (let* ((marker (or (get-text-property (point) 'org-marker)
9190 (org-agenda-error)))
9191 (buffer (marker-buffer marker))
9192 (pos (marker-position marker))
9193 (org-insert-labeled-timestamps-at-point nil)
9195 (with-current-buffer buffer
9196 (widen)
9197 (goto-char pos)
9198 (setq ts (org-deadline))
9199 (message "Deadline for this item set to %s" ts))))
9201 (defun org-get-heading ()
9202 "Return the heading of the current entry, without the stars."
9203 (save-excursion
9204 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
9205 (if (and (re-search-backward "[\r\n]\\*" nil t)
9206 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
9207 (match-string 1)
9208 "")))
9210 (defun org-agenda-clock-in (&optional arg)
9211 "Start the clock on the currently selected item."
9212 (interactive "P")
9213 (org-agenda-check-no-diary)
9214 (let* ((marker (or (get-text-property (point) 'org-marker)
9215 (org-agenda-error)))
9216 (pos (marker-position marker)))
9217 (with-current-buffer (marker-buffer marker)
9218 (widen)
9219 (goto-char pos)
9220 (org-clock-in))))
9222 (defun org-agenda-diary-entry ()
9223 "Make a diary entry, like the `i' command from the calendar.
9224 All the standard commands work: block, weekly etc."
9225 (interactive)
9226 (org-agenda-check-type t 'agenda 'timeline)
9227 (require 'diary-lib)
9228 (let* ((char (progn
9229 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
9230 (read-char-exclusive)))
9231 (cmd (cdr (assoc char
9232 '((?d . insert-diary-entry)
9233 (?w . insert-weekly-diary-entry)
9234 (?m . insert-monthly-diary-entry)
9235 (?y . insert-yearly-diary-entry)
9236 (?a . insert-anniversary-diary-entry)
9237 (?b . insert-block-diary-entry)
9238 (?c . insert-cyclic-diary-entry)))))
9239 (oldf (symbol-function 'calendar-cursor-to-date))
9240 (point (point))
9241 (mark (or (mark t) (point))))
9242 (unless cmd
9243 (error "No command associated with <%c>" char))
9244 (unless (and (get-text-property point 'day)
9245 (or (not (equal ?b char))
9246 (get-text-property mark 'day)))
9247 (error "Don't know which date to use for diary entry"))
9248 ;; We implement this by hacking the `calendar-cursor-to-date' function
9249 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
9250 (let ((calendar-mark-ring
9251 (list (calendar-gregorian-from-absolute
9252 (or (get-text-property mark 'day)
9253 (get-text-property point 'day))))))
9254 (unwind-protect
9255 (progn
9256 (fset 'calendar-cursor-to-date
9257 (lambda (&optional error)
9258 (calendar-gregorian-from-absolute
9259 (get-text-property point 'day))))
9260 (call-interactively cmd))
9261 (fset 'calendar-cursor-to-date oldf)))))
9264 (defun org-agenda-execute-calendar-command (cmd)
9265 "Execute a calendar command from the agenda, with the date associated to
9266 the cursor position."
9267 (org-agenda-check-type t 'agenda 'timeline)
9268 (require 'diary-lib)
9269 (unless (get-text-property (point) 'day)
9270 (error "Don't know which date to use for calendar command"))
9271 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
9272 (point (point))
9273 (date (calendar-gregorian-from-absolute
9274 (get-text-property point 'day)))
9275 (displayed-day (extract-calendar-day date))
9276 (displayed-month (extract-calendar-month date))
9277 (displayed-year (extract-calendar-year date)))
9278 (unwind-protect
9279 (progn
9280 (fset 'calendar-cursor-to-date
9281 (lambda (&optional error)
9282 (calendar-gregorian-from-absolute
9283 (get-text-property point 'day))))
9284 (call-interactively cmd))
9285 (fset 'calendar-cursor-to-date oldf))))
9287 (defun org-agenda-phases-of-moon ()
9288 "Display the phases of the moon for the 3 months around the cursor date."
9289 (interactive)
9290 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
9292 (defun org-agenda-holidays ()
9293 "Display the holidays for the 3 months around the cursor date."
9294 (interactive)
9295 (org-agenda-execute-calendar-command 'list-calendar-holidays))
9297 (defun org-agenda-sunrise-sunset (arg)
9298 "Display sunrise and sunset for the cursor date.
9299 Latitude and longitude can be specified with the variables
9300 `calendar-latitude' and `calendar-longitude'. When called with prefix
9301 argument, latitude and longitude will be prompted for."
9302 (interactive "P")
9303 (let ((calendar-longitude (if arg nil calendar-longitude))
9304 (calendar-latitude (if arg nil calendar-latitude))
9305 (calendar-location-name
9306 (if arg "the given coordinates" calendar-location-name)))
9307 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
9309 (defun org-agenda-goto-calendar ()
9310 "Open the Emacs calendar with the date at the cursor."
9311 (interactive)
9312 (org-agenda-check-type t 'agenda 'timeline)
9313 (let* ((day (or (get-text-property (point) 'day)
9314 (error "Don't know which date to open in calendar")))
9315 (date (calendar-gregorian-from-absolute day))
9316 (calendar-move-hook nil)
9317 (view-calendar-holidays-initially nil)
9318 (view-diary-entries-initially nil))
9319 (calendar)
9320 (calendar-goto-date date)))
9322 (defun org-calendar-goto-agenda ()
9323 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
9324 This is a command that has to be installed in `calendar-mode-map'."
9325 (interactive)
9326 (org-agenda-list nil (calendar-absolute-from-gregorian
9327 (calendar-cursor-to-date))
9328 nil))
9330 (defun org-agenda-convert-date ()
9331 (interactive)
9332 (org-agenda-check-type t 'agenda 'timeline)
9333 (let ((day (get-text-property (point) 'day))
9334 date s)
9335 (unless day
9336 (error "Don't know which date to convert"))
9337 (setq date (calendar-gregorian-from-absolute day))
9338 (setq s (concat
9339 "Gregorian: " (calendar-date-string date) "\n"
9340 "ISO: " (calendar-iso-date-string date) "\n"
9341 "Day of Yr: " (calendar-day-of-year-string date) "\n"
9342 "Julian: " (calendar-julian-date-string date) "\n"
9343 "Astron. JD: " (calendar-astro-date-string date)
9344 " (Julian date number at noon UTC)\n"
9345 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
9346 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
9347 "French: " (calendar-french-date-string date) "\n"
9348 "Mayan: " (calendar-mayan-date-string date) "\n"
9349 "Coptic: " (calendar-coptic-date-string date) "\n"
9350 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
9351 "Persian: " (calendar-persian-date-string date) "\n"
9352 "Chinese: " (calendar-chinese-date-string date) "\n"))
9353 (with-output-to-temp-buffer "*Dates*"
9354 (princ s))
9355 (if (fboundp 'fit-window-to-buffer)
9356 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
9358 ;;; Tags
9360 (defun org-scan-tags (action matcher &optional todo-only)
9361 "Scan headline tags with inheritance and produce output ACTION.
9362 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9363 evaluated, testing if a given set of tags qualifies a headline for
9364 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9365 are included in the output."
9366 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9367 (mapconcat 'regexp-quote
9368 (nreverse (cdr (reverse org-todo-keywords)))
9369 "\\|")
9370 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
9371 (props (list 'face nil
9372 'done-face 'org-done
9373 'undone-face nil
9374 'mouse-face 'highlight
9375 'org-not-done-regexp org-not-done-regexp
9376 'keymap org-agenda-keymap
9377 'help-echo
9378 (format "mouse-2 or RET jump to org file %s"
9379 (abbreviate-file-name buffer-file-name))))
9380 (case-fold-search nil)
9381 lspos
9382 tags tags-list tags-alist (llast 0) rtn level category i txt
9383 todo marker)
9384 (save-excursion
9385 (goto-char (point-min))
9386 (when (eq action 'sparse-tree) (org-overview))
9387 (while (re-search-forward re nil t)
9388 (catch :skip
9389 (and (eq action 'agenda) (org-agenda-skip))
9390 (setq todo (if (match-end 1) (match-string 2))
9391 tags (if (match-end 4) (match-string 4)))
9392 (goto-char (setq lspos (1+ (match-beginning 0))))
9393 (setq level (funcall outline-level)
9394 category (org-get-category))
9395 (setq i llast llast level)
9396 ;; remove tag lists from same and sublevels
9397 (while (>= i level)
9398 (when (setq entry (assoc i tags-alist))
9399 (setq tags-alist (delete entry tags-alist)))
9400 (setq i (1- i)))
9401 ;; add the nex tags
9402 (when tags
9403 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9404 tags-alist
9405 (cons (cons level tags) tags-alist)))
9406 ;; compile tags for current headline
9407 (setq tags-list
9408 (if org-use-tag-inheritance
9409 (apply 'append (mapcar 'cdr tags-alist))
9410 tags))
9411 (when (and (or (not todo-only) todo)
9412 (eval matcher)
9413 (or (not org-agenda-skip-archived-trees)
9414 (not (member org-archive-tag tags-list))))
9415 ;; list this headline
9416 (if (eq action 'sparse-tree)
9417 (progn
9418 (org-show-context 'tags-tree))
9419 (setq txt (org-format-agenda-item
9421 (concat
9422 (if org-tags-match-list-sublevels
9423 (make-string (1- level) ?.) "")
9424 (org-get-heading))
9425 category tags-list))
9426 (goto-char lspos)
9427 (setq marker (org-agenda-new-marker))
9428 (org-add-props txt props
9429 'org-marker marker 'org-hd-marker marker 'category category)
9430 (push txt rtn))
9431 ;; if we are to skip sublevels, jump to end of subtree
9432 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9433 (when (and (eq action 'sparse-tree)
9434 (not org-sparse-tree-open-archived-trees))
9435 (org-hide-archived-subtrees (point-min) (point-max)))
9436 (nreverse rtn)))
9438 (defun org-tags-sparse-tree (&optional arg match)
9439 "Create a sparse tree according to tags string MATCH.
9440 MATCH can contain positive and negative selection of tags, like
9441 \"+WORK+URGENT-WITHBOSS\"."
9442 (interactive "P")
9443 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))))
9445 (defun org-make-tags-matcher (match)
9446 "Create the TAGS//TODO matcher form for the selection string MATCH."
9447 (unless match
9448 ;; Get a new match request, with completion
9449 (setq org-last-tags-completion-table
9450 (or org-tag-alist
9451 org-last-tags-completion-table))
9452 (setq match (completing-read
9453 "Match: " 'org-tags-completion-function nil nil nil
9454 'org-tags-history))) ; FIXME: SHould we have a separate history for this?
9456 ;; Parse the string and create a lisp form
9457 (let ((match0 match) minus tag mm
9458 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9459 orterms term orlist)
9460 (if (string-match "/+" match)
9461 ;; match contains also a todo-matching request
9462 (setq tagsmatch (substring match 0 (match-beginning 0))
9463 todomatch (substring match (match-end 0)))
9464 ;; only matching tags
9465 (setq tagsmatch match todomatch nil))
9467 ;; Make the tags matcher
9468 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9469 (setq tagsmatcher t)
9470 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9471 (while (setq term (pop orterms))
9472 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
9473 (setq minus (and (match-end 1)
9474 (equal (match-string 1 term) "-"))
9475 tag (match-string 2 term)
9476 term (substring term (match-end 0))
9477 mm (list 'member (downcase tag) 'tags-list)
9478 mm (if minus (list 'not mm) mm))
9479 (push mm tagsmatcher))
9480 (push (if (> (length tagsmatcher) 1)
9481 (cons 'and tagsmatcher)
9482 (car tagsmatcher))
9483 orlist)
9484 (setq tagsmatcher nil))
9485 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
9487 ;; Make the todo matcher ;; FIXME: reduce syntax richness?
9488 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9489 (setq todomatcher t)
9490 (setq orterms (org-split-string todomatch "|") orlist nil)
9491 (while (setq term (pop orterms))
9492 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
9493 (setq minus (and (match-end 1)
9494 (equal (match-string 1 term) "-"))
9495 kwd (match-string 2 term)
9496 term (substring term (match-end 0))
9497 mm (list 'equal 'todo kwd)
9498 mm (if minus (list 'not mm) mm))
9499 (push mm todomatcher))
9500 (push (if (> (length todomatcher) 1)
9501 (cons 'and todomatcher)
9502 (car todomatcher))
9503 orlist)
9504 (setq todomatcher nil))
9505 (setq todomatcher (if (> (length orlist) 1)
9506 (cons 'or orlist) (car orlist))))
9508 ;; Return the string and lisp forms of the matcher
9509 (setq matcher (if todomatcher
9510 (list 'and tagsmatcher todomatcher)
9511 tagsmatcher))
9512 (cons match0 matcher)))
9514 ;;;###autoload
9515 (defun org-tags-view (&optional todo-only match)
9516 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
9517 The prefix arg TODO-ONLY limits the search to TODO entries."
9518 (interactive "P")
9519 (org-compile-prefix-format 'tags)
9520 (org-set-sorting-strategy 'tags)
9521 (let* ((org-tags-match-list-sublevels
9522 (if todo-only t org-tags-match-list-sublevels))
9523 (win (selected-window))
9524 (completion-ignore-case t)
9525 rtn rtnall files file pos matcher
9526 buffer)
9527 (setq matcher (org-make-tags-matcher match)
9528 match (car matcher) matcher (cdr matcher))
9529 (org-prepare-agenda)
9530 (setq org-agenda-redo-command
9531 (list 'org-tags-view (list 'quote todo-only)
9532 (list 'if 'current-prefix-arg nil match)))
9533 (setq files (org-agenda-files)
9534 rtnall nil)
9535 (while (setq file (pop files))
9536 (catch 'nextfile
9537 (org-check-agenda-file file)
9538 (setq buffer (if (file-exists-p file)
9539 (org-get-agenda-file-buffer file)
9540 (error "No such file %s" file)))
9541 (if (not buffer)
9542 ;; If file does not exist, merror message to agenda
9543 (setq rtn (list
9544 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
9545 rtnall (append rtnall rtn))
9546 (with-current-buffer buffer
9547 (unless (org-mode-p)
9548 (error "Agenda file %s is not in `org-mode'" file))
9549 (setq org-category-table (org-get-category-table))
9550 (save-excursion
9551 (save-restriction
9552 (if org-agenda-restrict
9553 (narrow-to-region org-agenda-restrict-begin
9554 org-agenda-restrict-end)
9555 (widen))
9556 (setq rtn (org-scan-tags 'agenda matcher todo-only))
9557 (setq rtnall (append rtnall rtn))))))))
9558 (insert "Headlines with TAGS match: ")
9559 (add-text-properties (point-min) (1- (point))
9560 (list 'face 'org-level-3))
9561 (setq pos (point))
9562 (insert match "\n")
9563 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
9564 (setq pos (point))
9565 (unless org-agenda-multi
9566 (insert "Press `C-u r' to search again with new search string\n"))
9567 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
9568 (when rtnall
9569 (insert (org-finalize-agenda-entries rtnall) "\n"))
9570 (goto-char (point-min))
9571 (org-fit-agenda-window)
9572 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
9573 (org-finalize-agenda)
9574 (setq buffer-read-only t)
9575 (if (not org-select-agenda-window) (select-window win))))
9577 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9578 (defvar org-tags-overlay (org-make-overlay 1 1))
9579 (org-detach-overlay org-tags-overlay)
9581 (defun org-set-tags (&optional arg just-align)
9582 "Set the tags for the current headline.
9583 With prefix ARG, realign all tags in headings in the current buffer."
9584 (interactive "P")
9585 (let* ((re (concat "^" outline-regexp))
9586 (current (org-get-tags))
9587 table current-tags inherited-tags ; computed below when needed
9588 tags p0 c0 c1 rpl)
9589 (if arg
9590 (save-excursion
9591 (goto-char (point-min))
9592 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
9593 (while (re-search-forward re nil t)
9594 (org-set-tags nil t)
9595 (end-of-line 1)))
9596 (message "All tags realigned to column %d" org-tags-column))
9597 (if just-align
9598 (setq tags current)
9599 ;; Get a new set of tags from the user
9600 (setq table (or org-tag-alist (org-get-buffer-tags))
9601 org-last-tags-completion-table table
9602 current-tags (org-split-string current ":")
9603 inherited-tags (nreverse
9604 (nthcdr (length current-tags)
9605 (nreverse (org-get-tags-at))))
9606 tags
9607 (if (or (eq t org-use-fast-tag-selection)
9608 (and org-use-fast-tag-selection
9609 (delq nil (mapcar 'cdr table))))
9610 (org-fast-tag-selection current-tags inherited-tags table)
9611 (let ((org-add-colon-after-tag-completion t))
9612 (org-trim
9613 (completing-read "Tags: " 'org-tags-completion-function
9614 nil nil current 'org-tags-history)))))
9615 (while (string-match "[-+&]+" tags)
9616 ;; No boolean logic, just a list
9617 (setq tags (replace-match ":" t t tags))))
9618 (if (string-match "\\`[\t ]*\\'" tags)
9619 (setq tags "")
9620 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9621 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9623 ;; Insert new tags at the correct column
9624 (beginning-of-line 1)
9625 (if (re-search-forward
9626 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9627 (point-at-eol) t)
9628 (progn
9629 (if (equal tags "")
9630 (setq rpl "")
9631 (goto-char (match-beginning 0))
9632 (setq c0 (current-column) p0 (point)
9633 c1 (max (1+ c0) (if (> org-tags-column 0)
9634 org-tags-column
9635 (- (- org-tags-column) (length tags))))
9636 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9637 (replace-match rpl)
9638 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
9639 tags)
9640 (error "Tags alignment failed")))))
9642 (defun org-tags-completion-function (string predicate &optional flag)
9643 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9644 (confirm (lambda (x) (stringp (car x)))))
9645 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9646 (setq s1 (match-string 1 string)
9647 s2 (match-string 2 string))
9648 (setq s1 "" s2 string))
9649 (cond
9650 ((eq flag nil)
9651 ;; try completion
9652 (setq rtn (try-completion s2 ctable confirm))
9653 (if (stringp rtn)
9654 (concat s1 s2 (substring rtn (length s2))
9655 (if (and org-add-colon-after-tag-completion
9656 (assoc rtn ctable))
9657 ":" "")))
9659 ((eq flag t)
9660 ;; all-completions
9661 (all-completions s2 ctable confirm)
9663 ((eq flag 'lambda)
9664 ;; exact match?
9665 (assoc s2 ctable)))
9668 (defun org-fast-tag-insert (kwd tags face &optional end)
9669 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9670 (insert (format "%-12s" (concat kwd ":"))
9671 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9672 (or end "")))
9674 (defun org-fast-tag-show-exit (flag)
9675 (save-excursion
9676 (goto-line 3)
9677 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9678 (replace-match ""))
9679 (when flag
9680 (end-of-line 1)
9681 (move-to-column (- (window-width) 19) t)
9682 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9684 (defun org-set-current-tags-overlay (current prefix)
9685 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9686 (if (featurep 'xemacs)
9687 (org-overlay-display org-tags-overlay (concat prefix s)
9688 'secondary-selection)
9689 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9690 (org-overlay-display org-tags-overlay (concat prefix s)))))
9692 (defun org-fast-tag-selection (current inherited table)
9693 "Fast tag selection with single keys.
9694 CURRENT is the current list of tags in the headline, INHERITED is the
9695 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9696 possibly with grouping information.
9697 If the keys are nil, a-z are automatically assigned.
9698 Returns the new tags string, or nil to not change the current settings."
9699 (let* ((maxlen (apply 'max (mapcar
9700 (lambda (x)
9701 (if (stringp (car x)) (string-width (car x)) 0))
9702 table)))
9703 (buf (current-buffer))
9704 (buffer-tags nil)
9705 (fwidth (+ maxlen 3 1 3))
9706 (ncol (/ (- (window-width) 4) fwidth))
9707 (i-face 'org-done)
9708 (c-face 'org-tag)
9709 tg cnt e c char c1 c2 ntable tbl rtn
9710 ov-start ov-end ov-prefix
9711 (exit-after-next org-fast-tag-selection-single-key)
9712 groups ingroup)
9713 (save-excursion
9714 (beginning-of-line 1)
9715 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9716 (setq ov-start (match-beginning 1)
9717 ov-end (match-end 1)
9718 ov-prefix "")
9719 (setq ov-start (1- (point-at-eol))
9720 ov-end (1+ ov-start))
9721 (skip-chars-forward "^\n\r")
9722 (setq ov-prefix
9723 (concat
9724 (buffer-substring (1- (point)) (point))
9725 (if (> (current-column) org-tags-column)
9727 (make-string (- org-tags-column (current-column)) ?\ ))))))
9728 (org-move-overlay org-tags-overlay ov-start ov-end)
9729 (save-window-excursion
9730 ;; FIXME: would it be better to keep the other windows?
9731 (delete-other-windows)
9732 (split-window-vertically)
9733 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
9734 (erase-buffer)
9735 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9736 (org-fast-tag-insert "Current" current c-face "\n\n")
9737 (org-fast-tag-show-exit exit-after-next)
9738 (org-set-current-tags-overlay current ov-prefix)
9739 (setq tbl table char ?a cnt 0)
9740 (while (setq e (pop tbl))
9741 (cond
9742 ((equal e '(:startgroup))
9743 (push '() groups) (setq ingroup t)
9744 (when (not (= cnt 0))
9745 (setq cnt 0)
9746 (insert "\n"))
9747 (insert "{ "))
9748 ((equal e '(:endgroup))
9749 (setq ingroup nil cnt 0)
9750 (insert "}\n"))
9752 (setq tg (car e) c2 nil)
9753 (if (cdr e)
9754 (setq c (cdr e))
9755 ;; automatically assign a character.
9756 (setq c1 (string-to-char
9757 (downcase (substring
9758 tg (if (= (string-to-char tg) ?@) 1 0)))))
9759 (if (or (rassoc c1 ntable) (rassoc c1 table))
9760 (while (or (rassoc char ntable) (rassoc char table))
9761 (setq char (1+ char)))
9762 (setq c2 c1))
9763 (setq c (or c2 char)))
9764 (if ingroup (push tg (car groups)))
9765 (setq tg (org-add-props tg nil 'face
9766 (cond
9767 ((member tg current) c-face)
9768 ((member tg inherited) i-face)
9769 (t nil))))
9770 (if (and (= cnt 0) (not ingroup)) (insert " "))
9771 (insert "[" c "] " tg (make-string
9772 (- fwidth 4 (length tg)) ?\ ))
9773 (push (cons tg c) ntable)
9774 (when (= (setq cnt (1+ cnt)) ncol)
9775 (insert "\n")
9776 (if ingroup (insert " "))
9777 (setq cnt 0)))))
9778 (setq ntable (nreverse ntable))
9779 (insert "\n")
9780 (goto-char (point-min))
9781 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
9782 (setq rtn
9783 (catch 'exit
9784 (while t
9785 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [C-c]: multi%s"
9786 (if groups " [!] no groups" ""))
9787 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9788 (cond
9789 ((= c ?\r) (throw 'exit t))
9790 ((= c ?!)
9791 (setq groups nil)
9792 (goto-char (point-min))
9793 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9794 ((= c ?\C-c)
9795 (org-fast-tag-show-exit
9796 (setq exit-after-next (not exit-after-next))))
9797 ((or (= c ?\C-g)
9798 (and (= c ?q) (not (rassoc c ntable))))
9799 (org-detach-overlay org-tags-overlay)
9800 (setq quit-flag t))
9801 ((= c ?\ )
9802 (setq current nil)
9803 (if exit-after-next (setq exit-after-next 'now)))
9804 ((= c ?\t)
9805 (condition-case nil
9806 (setq tg (completing-read
9807 "Tag: "
9808 (or buffer-tags
9809 (with-current-buffer buf
9810 (org-get-buffer-tags)))))
9811 (quit (setq tg "")))
9812 (when (string-match "\\S-" tg)
9813 (add-to-list 'buffer-tags (list tg))
9814 (if (member tg current)
9815 (setq current (delete tg current))
9816 (push tg current)))
9817 (if exit-after-next (setq exit-after-next 'now)))
9818 ((setq e (rassoc c ntable) tg (car e))
9819 (if (member tg current)
9820 (setq current (delete tg current))
9821 (loop for g in groups do
9822 (if (member tg g)
9823 (mapcar (lambda (x)
9824 (setq current (delete x current)))
9825 g)))
9826 (push tg current))
9827 (if exit-after-next (setq exit-after-next 'now))))
9829 ;; Create a sorted list
9830 (setq current
9831 (sort current
9832 (lambda (a b)
9833 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9834 (if (eq exit-after-next 'now) (throw 'exit t))
9835 (goto-char (point-min))
9836 (beginning-of-line 2)
9837 (delete-region (point) (point-at-eol))
9838 (org-fast-tag-insert "Current" current c-face)
9839 (org-set-current-tags-overlay current ov-prefix)
9840 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
9841 (setq tg (match-string 1))
9842 (add-text-properties (match-beginning 1) (match-end 1)
9843 (list 'face
9844 (cond
9845 ((member tg current) c-face)
9846 ((member tg inherited) i-face)
9847 (t nil)))))
9848 (goto-char (point-min)))))
9849 (org-detach-overlay org-tags-overlay)
9850 (if rtn
9851 (mapconcat 'identity current ":")
9852 nil))))
9854 (defun org-get-tags ()
9855 "Get the TAGS string in the current headline."
9856 (unless (org-on-heading-p t)
9857 (error "Not on a heading"))
9858 (save-excursion
9859 (beginning-of-line 1)
9860 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9861 (org-match-string-no-properties 1)
9862 "")))
9864 (defun org-get-buffer-tags ()
9865 "Get a table of all tags used in the buffer, for completion."
9866 (let (tags)
9867 (save-excursion
9868 (goto-char (point-min))
9869 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9870 (mapc (lambda (x) (add-to-list 'tags x))
9871 (org-split-string (org-match-string-no-properties 1) ":"))))
9872 (mapcar 'list tags)))
9874 ;;; Link Stuff
9876 (defvar org-create-file-search-functions nil
9877 "List of functions to construct the right search string for a file link.
9878 These functions are called in turn with point at the location to
9879 which the link should point.
9881 A function in the hook should first test if it would like to
9882 handle this file type, for example by checking the major-mode or
9883 the file extension. If it decides not to handle this file, it
9884 should just return nil to give other functions a chance. If it
9885 does handle the file, it must return the search string to be used
9886 when following the link. The search string will be part of the
9887 file link, given after a double colon, and `org-open-at-point'
9888 will automatically search for it. If special measures must be
9889 taken to make the search successful, another function should be
9890 added to the companion hook `org-execute-file-search-functions',
9891 which see.
9893 A function in this hook may also use `setq' to set the variable
9894 `description' to provide a suggestion for the descriptive text to
9895 be used for this link when it gets inserted into an Org-mode
9896 buffer with \\[org-insert-link].")
9898 (defvar org-execute-file-search-functions nil
9899 "List of functions to execute a file search triggered by a link.
9901 Functions added to this hook must accept a single argument, the
9902 search string that was part of the file link, the part after the
9903 double colon. The function must first check if it would like to
9904 handle this search, for example by checking the major-mode or the
9905 file extension. If it decides not to handle this search, it
9906 should just return nil to give other functions a chance. If it
9907 does handle the search, it must return a non-nil value to keep
9908 other functions from trying.
9910 Each function can access the current prefix argument through the
9911 variable `current-prefix-argument'. Note that a single prefix is
9912 used to force opening a link in Emacs, so it may be good to only
9913 use a numeric or double prefix to guide the search function.
9915 In case this is needed, a function in this hook can also restore
9916 the window configuration before `org-open-at-point' was called using:
9918 (set-window-configuration org-window-config-before-follow-link)")
9920 (defun org-find-file-at-mouse (ev)
9921 "Open file link or URL at mouse."
9922 (interactive "e")
9923 (mouse-set-point ev)
9924 (org-open-at-point 'in-emacs))
9926 (defun org-open-at-mouse (ev)
9927 "Open file link or URL at mouse."
9928 (interactive "e")
9929 (mouse-set-point ev)
9930 (org-open-at-point))
9932 (defvar org-window-config-before-follow-link nil
9933 "The window configuration before following a link.
9934 This is saved in case the need arises to restore it.")
9936 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
9937 (defun org-open-at-point (&optional in-emacs)
9938 "Open link at or after point.
9939 If there is no link at point, this function will search forward up to
9940 the end of the current subtree.
9941 Normally, files will be opened by an appropriate application. If the
9942 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9943 (interactive "P")
9944 (setq org-window-config-before-follow-link (current-window-configuration))
9945 (org-remove-occur-highlights nil nil t)
9946 (if (org-at-timestamp-p t)
9947 (org-follow-timestamp-link)
9948 (let (type path link line search (pos (point)))
9949 (catch 'match
9950 (save-excursion
9951 (skip-chars-forward "^]\n\r")
9952 (when (and (re-search-backward "\\[\\[" nil t)
9953 (looking-at org-bracket-link-regexp)
9954 (<= (match-beginning 0) pos)
9955 (>= (match-end 0) pos))
9956 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9957 (while (string-match " *\n *" link)
9958 (setq link (replace-match " " t t link)))
9959 (setq link (org-link-expand-abbrev link))
9960 (if (string-match org-link-re-with-space2 link)
9961 (setq type (match-string 1 link)
9962 path (match-string 2 link))
9963 (setq type "thisfile"
9964 path link))
9965 (throw 'match t)))
9967 (when (get-text-property (point) 'org-linked-text)
9968 (setq type "thisfile"
9969 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9970 (1+ (point)) (point))
9971 path (buffer-substring
9972 (previous-single-property-change pos 'org-linked-text)
9973 (next-single-property-change pos 'org-linked-text)))
9974 (throw 'match t))
9976 (save-excursion
9977 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9978 (if (equal (char-before) ?<) (backward-char 1))
9979 (when (or (looking-at org-angle-link-re)
9980 (looking-at org-plain-link-re)
9981 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9982 (re-search-forward org-plain-link-re (point-at-eol) t))
9983 (<= (match-beginning 0) pos)
9984 (>= (match-end 0) pos)))
9985 (setq type (match-string 1)
9986 path (match-string 2))
9987 (throw 'match t)))
9988 (save-excursion
9989 (skip-chars-backward "^ \t\n\r")
9990 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9991 (setq type "tags"
9992 path (match-string 1))
9993 (while (string-match ":" path)
9994 (setq path (replace-match "+" t t path)))
9995 (throw 'match t)))
9996 (save-excursion
9997 (skip-chars-backward "a-zA-Z_")
9998 (when (and (memq 'camel org-activate-links)
9999 (looking-at org-camel-regexp))
10000 (setq type "camel" path (match-string 0))
10001 (if (equal (char-before) ?*)
10002 (setq path (concat "*" path))))
10003 (throw 'match t)))
10004 (unless path
10005 (error "No link found"))
10006 ;; Remove any trailing spaces in path
10007 (if (string-match " +\\'" path)
10008 (setq path (replace-match "" t t path)))
10010 (cond
10012 ((equal type "mailto")
10013 (let ((cmd (car org-link-mailto-program))
10014 (args (cdr org-link-mailto-program)) args1
10015 (address path) (subject "") a)
10016 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10017 (setq address (match-string 1 path)
10018 subject (org-link-escape (match-string 2 path))))
10019 (while args
10020 (cond
10021 ((not (stringp (car args))) (push (pop args) args1))
10022 (t (setq a (pop args))
10023 (if (string-match "%a" a)
10024 (setq a (replace-match address t t a)))
10025 (if (string-match "%s" a)
10026 (setq a (replace-match subject t t a)))
10027 (push a args1))))
10028 (apply cmd (nreverse args1))))
10030 ((member type '("http" "https" "ftp" "news"))
10031 (browse-url (concat type ":" path)))
10033 ((string= type "tags")
10034 (org-tags-view in-emacs path))
10035 ((or (string= type "camel")
10036 (string= type "thisfile"))
10037 (if in-emacs
10038 (switch-to-buffer-other-window
10039 (org-get-buffer-for-internal-link (current-buffer)))
10040 (org-mark-ring-push))
10041 (org-link-search
10042 path
10043 (cond ((equal in-emacs '(4)) 'occur)
10044 ((equal in-emacs '(16)) 'org-occur)
10045 (t nil))))
10047 ((string= type "file")
10048 (if (string-match "::\\([0-9]+\\)\\'" path)
10049 (setq line (string-to-number (match-string 1 path))
10050 path (substring path 0 (match-beginning 0)))
10051 (if (string-match "::\\(.+\\)\\'" path)
10052 (setq search (match-string 1 path)
10053 path (substring path 0 (match-beginning 0)))))
10054 (org-open-file path in-emacs line search))
10056 ((string= type "news")
10057 (org-follow-gnus-link path))
10059 ((string= type "bbdb")
10060 (org-follow-bbdb-link path))
10062 ((string= type "info")
10063 (org-follow-info-link path))
10065 ((string= type "gnus")
10066 (let (group article)
10067 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10068 (error "Error in Gnus link"))
10069 (setq group (match-string 1 path)
10070 article (match-string 3 path))
10071 (org-follow-gnus-link group article)))
10073 ((string= type "vm")
10074 (let (folder article)
10075 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10076 (error "Error in VM link"))
10077 (setq folder (match-string 1 path)
10078 article (match-string 3 path))
10079 ;; in-emacs is the prefix arg, will be interpreted as read-only
10080 (org-follow-vm-link folder article in-emacs)))
10082 ((string= type "wl")
10083 (let (folder article)
10084 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10085 (error "Error in Wanderlust link"))
10086 (setq folder (match-string 1 path)
10087 article (match-string 3 path))
10088 (org-follow-wl-link folder article)))
10090 ((string= type "mhe")
10091 (let (folder article)
10092 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10093 (error "Error in MHE link"))
10094 (setq folder (match-string 1 path)
10095 article (match-string 3 path))
10096 (org-follow-mhe-link folder article)))
10098 ((string= type "rmail")
10099 (let (folder article)
10100 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10101 (error "Error in RMAIL link"))
10102 (setq folder (match-string 1 path)
10103 article (match-string 3 path))
10104 (org-follow-rmail-link folder article)))
10106 ((string= type "shell")
10107 (let ((cmd path))
10108 (while (string-match "@{" cmd) ; FIXME: not needed for [[]] links
10109 (setq cmd (replace-match "<" t t cmd)))
10110 (while (string-match "@}" cmd) ; FIXME: not needed for [[]] links
10111 (setq cmd (replace-match ">" t t cmd)))
10112 (if (or (not org-confirm-shell-link-function)
10113 (funcall org-confirm-shell-link-function
10114 (format "Execute \"%s\" in shell? "
10115 (org-add-props cmd nil
10116 'face 'org-warning))))
10117 (progn
10118 (message "Executing %s" cmd)
10119 (shell-command cmd))
10120 (error "Abort"))))
10122 ((string= type "elisp")
10123 (let ((cmd path))
10124 (if (or (not org-confirm-elisp-link-function)
10125 (funcall org-confirm-elisp-link-function
10126 (format "Execute \"%s\" as elisp? "
10127 (org-add-props cmd nil
10128 'face 'org-warning))))
10129 (message "%s => %s" cmd (eval (read cmd)))
10130 (error "Abort"))))
10133 (browse-url-at-point))))))
10135 (defun org-link-expand-abbrev (link)
10136 "Apply replacements as defined in `org-link-abbrev-alist."
10137 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
10138 (let* ((key (match-string 1 link))
10139 (as (or (assoc key org-link-abbrev-alist-local)
10140 (assoc key org-link-abbrev-alist)))
10141 (tag (and (match-end 2) (match-string 3 link)))
10142 rpl)
10143 (if (not as)
10144 link
10145 (setq rpl (cdr as))
10146 (cond
10147 ((symbolp rpl) (funcall rpl tag))
10148 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10149 (t (concat rpl tag)))))
10150 link))
10152 (defun org-link-search (s &optional type)
10153 "Search for a link search option.
10154 When S is a CamelCaseWord, search for a target, or for a sentence containing
10155 the words. If S is surrounded by forward slashes, it is interpreted as a
10156 regular expression. In org-mode files, this will create an `org-occur'
10157 sparse tree. In ordinary files, `occur' will be used to list matches.
10158 If the current buffer is in `dired-mode', grep will be used to search
10159 in all files."
10160 (let ((case-fold-search t)
10161 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10162 (pos (point))
10163 (pre "") (post "")
10164 words re0 re1 re2 re3 re4 re5 re2a reall camel)
10165 (cond
10166 ;; First check if there are any special
10167 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10168 ;; Now try the builtin stuff
10169 ((save-excursion
10170 (goto-char (point-min))
10171 (and
10172 (re-search-forward
10173 (concat "<<" (regexp-quote s0) ">>") nil t)
10174 (setq pos (match-beginning 0))))
10175 ;; There is an exact target for this
10176 (goto-char pos))
10177 ((string-match "^/\\(.*\\)/$" s)
10178 ;; A regular expression
10179 (cond
10180 ((org-mode-p)
10181 (org-occur (match-string 1 s)))
10182 ;;((eq major-mode 'dired-mode)
10183 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10184 (t (org-do-occur (match-string 1 s)))))
10185 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
10187 ;; A camel or a normal search string
10188 (when (equal (string-to-char s) ?*)
10189 ;; Anchor on headlines, post may include tags.
10190 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10191 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
10192 s (substring s 1)))
10193 (remove-text-properties
10194 0 (length s)
10195 '(face nil mouse-face nil keymap nil fontified nil) s)
10196 ;; Make a series of regular expressions to find a match
10197 (setq words
10198 (if camel
10199 (org-camel-to-words s)
10200 (org-split-string s "[ \n\r\t]+"))
10201 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10202 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
10203 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10204 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10205 re1 (concat pre re2 post)
10206 re3 (concat pre re4 post)
10207 re5 (concat pre ".*" re4)
10208 re2 (concat pre re2)
10209 re2a (concat pre re2a)
10210 re4 (concat pre re4)
10211 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10212 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10213 re5 "\\)"
10215 (cond
10216 ((eq type 'org-occur) (org-occur reall))
10217 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10218 (t (goto-char (point-min))
10219 (if (or (org-search-not-link re0 nil t)
10220 (org-search-not-link re1 nil t)
10221 (org-search-not-link re2 nil t)
10222 (org-search-not-link re2a nil t)
10223 (org-search-not-link re3 nil t)
10224 (org-search-not-link re4 nil t)
10225 (org-search-not-link re5 nil t)
10227 (goto-char (match-beginning 1))
10228 (goto-char pos)
10229 (error "No match")))))
10231 ;; Normal string-search
10232 (goto-char (point-min))
10233 (if (search-forward s nil t)
10234 (goto-char (match-beginning 0))
10235 (error "No match"))))
10236 (and (org-mode-p) (org-show-context 'link-search))))
10238 (defun org-search-not-link (&rest args)
10239 "Execute `re-search-forward', but only accept matches that are not a link."
10240 (catch 'exit
10241 (let (p1)
10242 (while (apply 're-search-forward args)
10243 (setq p1 (point))
10244 (if (not (save-match-data
10245 (and (re-search-backward "\\[\\[" nil t)
10246 (looking-at org-bracket-link-regexp)
10247 (<= (match-beginning 0) p1)
10248 (>= (match-end 0) p1))))
10249 (progn (goto-char (match-end 0))
10250 (throw 'exit (point)))
10251 (goto-char (match-end 0)))))))
10253 (defun org-get-buffer-for-internal-link (buffer)
10254 "Return a buffer to be used for displaying the link target of internal links."
10255 (cond
10256 ((not org-display-internal-link-with-indirect-buffer)
10257 buffer)
10258 ((string-match "(Clone)$" (buffer-name buffer))
10259 (message "Buffer is already a clone, not making another one")
10260 ;; we also do not modify visibility in this case
10261 buffer)
10262 (t ; make a new indirect buffer for displaying the link
10263 (let* ((bn (buffer-name buffer))
10264 (ibn (concat bn "(Clone)"))
10265 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10266 (with-current-buffer ib (org-overview))
10267 ib))))
10269 (defun org-do-occur (regexp &optional cleanup)
10270 "Call the Emacs command `occur'.
10271 If CLEANUP is non-nil, remove the printout of the regular expression
10272 in the *Occur* buffer. This is useful if the regex is long and not useful
10273 to read."
10274 (occur regexp)
10275 (when cleanup
10276 (let ((cwin (selected-window)) win beg end)
10277 (when (setq win (get-buffer-window "*Occur*"))
10278 (select-window win))
10279 (goto-char (point-min))
10280 (when (re-search-forward "match[a-z]+" nil t)
10281 (setq beg (match-end 0))
10282 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10283 (setq end (1- (match-beginning 0)))))
10284 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10285 (goto-char (point-min))
10286 (select-window cwin))))
10288 (defvar org-mark-ring nil
10289 "Mark ring for positions before jumps in Org-mode.")
10290 (defvar org-mark-ring-last-goto nil
10291 "Last position in the mark ring used to go back.")
10292 ;; Fill and close the ring
10293 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10294 (loop for i from 1 to org-mark-ring-length do
10295 (push (make-marker) org-mark-ring))
10296 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10297 org-mark-ring)
10299 (defun org-mark-ring-push (&optional pos buffer)
10300 "Put the current position or POS into the mark ring and rotate it."
10301 (interactive)
10302 (setq pos (or pos (point)))
10303 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10304 (move-marker (car org-mark-ring)
10305 (or pos (point))
10306 (or buffer (current-buffer)))
10307 (message
10308 (substitute-command-keys
10309 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10311 (defun org-mark-ring-goto (&optional n)
10312 "Jump to the previous position in the mark ring.
10313 With prefix arg N, jump back that many stored positions. When
10314 called several times in succession, walk through the entire ring.
10315 Org-mode commands jumping to a different position in the current file,
10316 or to another Org-mode file, automatically push the old position
10317 onto the ring."
10318 (interactive "p")
10319 (let (p m)
10320 (if (eq last-command this-command)
10321 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10322 (setq p org-mark-ring))
10323 (setq org-mark-ring-last-goto p)
10324 (setq m (car p))
10325 (switch-to-buffer (marker-buffer m))
10326 (goto-char m)
10327 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10329 (defun org-camel-to-words (s)
10330 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
10331 (let ((case-fold-search nil)
10332 words)
10333 (while (string-match "[a-z][A-Z]" s)
10334 (push (substring s 0 (1+ (match-beginning 0))) words)
10335 (setq s (substring s (1+ (match-beginning 0)))))
10336 (nreverse (cons s words))))
10338 (defun org-remove-angle-brackets (s)
10339 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10340 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10342 (defun org-add-angle-brackets (s)
10343 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10344 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10347 (defun org-follow-timestamp-link ()
10348 (cond
10349 ((org-at-date-range-p t)
10350 (let ((org-agenda-start-on-weekday)
10351 (t1 (match-string 1))
10352 (t2 (match-string 2)))
10353 (setq t1 (time-to-days (org-time-string-to-time t1))
10354 t2 (time-to-days (org-time-string-to-time t2)))
10355 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10356 ((org-at-timestamp-p t)
10357 (org-agenda-list nil (time-to-days (org-time-string-to-time
10358 (substring (match-string 1) 0 10)))
10360 (t (error "This should not happen"))))
10363 (defun org-follow-bbdb-link (name)
10364 "Follow a BBDB link to NAME."
10365 (require 'bbdb)
10366 (let ((inhibit-redisplay t)
10367 (bbdb-electric-p nil))
10368 (catch 'exit
10369 ;; Exact match on name
10370 (bbdb-name (concat "\\`" name "\\'") nil)
10371 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10372 ;; Exact match on name
10373 (bbdb-company (concat "\\`" name "\\'") nil)
10374 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10375 ;; Partial match on name
10376 (bbdb-name name nil)
10377 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10378 ;; Partial match on company
10379 (bbdb-company name nil)
10380 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10381 ;; General match including network address and notes
10382 (bbdb name nil)
10383 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10384 (delete-window (get-buffer-window "*BBDB*"))
10385 (error "No matching BBDB record")))))
10388 (defun org-follow-info-link (name)
10389 "Follow an info file & node link to NAME."
10390 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10391 (string-match "\\(.*\\)" name))
10392 (progn
10393 (require 'info)
10394 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10395 (Info-find-node (match-string 1 name) (match-string 2 name))
10396 (Info-find-node (match-string 1 name) "Top")))
10397 (message (concat "Could not open: " name))))
10399 (defun org-follow-gnus-link (&optional group article)
10400 "Follow a Gnus link to GROUP and ARTICLE."
10401 (require 'gnus)
10402 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10403 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10404 (if group (gnus-fetch-group group))
10405 (if article
10406 (or (gnus-summary-goto-article article nil 'force)
10407 (if (fboundp 'gnus-summary-insert-cached-articles)
10408 (progn
10409 (gnus-summary-insert-cached-articles)
10410 (gnus-summary-goto-article article nil 'force))
10411 (message "Message could not be found.")))))
10413 (defun org-follow-vm-link (&optional folder article readonly)
10414 "Follow a VM link to FOLDER and ARTICLE."
10415 (require 'vm)
10416 (setq article (org-add-angle-brackets article))
10417 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10418 ;; ange-ftp or efs or tramp access
10419 (let ((user (or (match-string 1 folder) (user-login-name)))
10420 (host (match-string 2 folder))
10421 (file (match-string 3 folder)))
10422 (cond
10423 ((featurep 'tramp)
10424 ;; use tramp to access the file
10425 (if (featurep 'xemacs)
10426 (setq folder (format "[%s@%s]%s" user host file))
10427 (setq folder (format "/%s@%s:%s" user host file))))
10429 ;; use ange-ftp or efs
10430 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10431 (setq folder (format "/%s@%s:%s" user host file))))))
10432 (when folder
10433 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10434 (sit-for 0.1)
10435 (when article
10436 (vm-select-folder-buffer)
10437 (widen)
10438 (let ((case-fold-search t))
10439 (goto-char (point-min))
10440 (if (not (re-search-forward
10441 (concat "^" "message-id: *" (regexp-quote article))))
10442 (error "Could not find the specified message in this folder"))
10443 (vm-isearch-update)
10444 (vm-isearch-narrow)
10445 (vm-beginning-of-message)
10446 (vm-summarize)))))
10448 (defun org-follow-wl-link (folder article)
10449 "Follow a Wanderlust link to FOLDER and ARTICLE."
10450 (setq article (org-add-angle-brackets article))
10451 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
10452 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
10453 (wl-summary-redisplay))
10455 (defun org-follow-rmail-link (folder article)
10456 "Follow an RMAIL link to FOLDER and ARTICLE."
10457 (setq article (org-add-angle-brackets article))
10458 (let (message-number)
10459 (save-excursion
10460 (save-window-excursion
10461 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10462 (setq message-number
10463 (save-restriction
10464 (widen)
10465 (goto-char (point-max))
10466 (if (re-search-backward
10467 (concat "^Message-ID:\\s-+" (regexp-quote
10468 (or article "")))
10469 nil t)
10470 (rmail-what-message))))))
10471 (if message-number
10472 (progn
10473 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10474 (rmail-show-message message-number)
10475 message-number)
10476 (error "Message not found"))))
10478 ;; mh-e integration based on planner-mode
10479 (defun org-mhe-get-message-real-folder ()
10480 "Return the name of the current message real folder, so if you use
10481 sequences, it will now work."
10482 (save-excursion
10483 (let* ((folder
10484 (if (equal major-mode 'mh-folder-mode)
10485 mh-current-folder
10486 ;; Refer to the show buffer
10487 mh-show-folder-buffer))
10488 (end-index
10489 (if (boundp 'mh-index-folder)
10490 (min (length mh-index-folder) (length folder))))
10492 ;; a simple test on mh-index-data does not work, because
10493 ;; mh-index-data is always nil in a show buffer.
10494 (if (and (boundp 'mh-index-folder)
10495 (string= mh-index-folder (substring folder 0 end-index)))
10496 (if (equal major-mode 'mh-show-mode)
10497 (save-window-excursion
10498 (when (buffer-live-p (get-buffer folder))
10499 (progn
10500 (pop-to-buffer folder)
10501 (org-mhe-get-message-folder-from-index)
10504 (org-mhe-get-message-folder-from-index)
10506 folder
10510 (defun org-mhe-get-message-folder-from-index ()
10511 "Returns the name of the message folder in a index folder buffer."
10512 (save-excursion
10513 (mh-index-previous-folder)
10514 (re-search-forward "^\\(+.*\\)$" nil t)
10515 (message (match-string 1))))
10517 (defun org-mhe-get-message-folder ()
10518 "Return the name of the current message folder. Be careful if you
10519 use sequences."
10520 (save-excursion
10521 (if (equal major-mode 'mh-folder-mode)
10522 mh-current-folder
10523 ;; Refer to the show buffer
10524 mh-show-folder-buffer)))
10526 (defun org-mhe-get-message-num ()
10527 "Return the number of the current message. Be careful if you
10528 use sequences."
10529 (save-excursion
10530 (if (equal major-mode 'mh-folder-mode)
10531 (mh-get-msg-num nil)
10532 ;; Refer to the show buffer
10533 (mh-show-buffer-message-number))))
10535 (defun org-mhe-get-header (header)
10536 "Return a header of the message in folder mode. This will create a
10537 show buffer for the corresponding message. If you have a more clever
10538 idea..."
10539 (let* ((folder (org-mhe-get-message-folder))
10540 (num (org-mhe-get-message-num))
10541 (buffer (get-buffer-create (concat "show-" folder)))
10542 (header-field))
10543 (with-current-buffer buffer
10544 (mh-display-msg num folder)
10545 (if (equal major-mode 'mh-folder-mode)
10546 (mh-header-display)
10547 (mh-show-header-display))
10548 (set-buffer buffer)
10549 (setq header-field (mh-get-header-field header))
10550 (if (equal major-mode 'mh-folder-mode)
10551 (mh-show)
10552 (mh-show-show))
10553 header-field)))
10555 (defun org-follow-mhe-link (folder article)
10556 "Follow an MHE link to FOLDER and ARTICLE.
10557 If ARTICLE is nil FOLDER is shown. If the configuration variable
10558 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10559 ARTICLE is searched in all folders. Indexed searches (swish++,
10560 namazu, and others supported by MH-E) will always search in all
10561 folders."
10562 (require 'mh-e)
10563 (require 'mh-search)
10564 (require 'mh-utils)
10565 (mh-find-path)
10566 (if (not article)
10567 (mh-visit-folder (mh-normalize-folder-name folder))
10568 (setq article (org-add-angle-brackets article))
10569 (mh-search-choose)
10570 (if (equal mh-searcher 'pick)
10571 (progn
10572 (mh-search folder (list "--message-id" article))
10573 (when (and org-mhe-search-all-folders
10574 (not (org-mhe-get-message-real-folder)))
10575 (kill-this-buffer)
10576 (mh-search "+" (list "--message-id" article))))
10577 (mh-search "+" article))
10578 (if (org-mhe-get-message-real-folder)
10579 (mh-show-msg 1)
10580 (kill-this-buffer)
10581 (error "Message not found"))))
10583 ;; BibTeX links
10585 ;; Use the custom search meachnism to construct and use search strings for
10586 ;; file links to BibTeX database entries.
10588 (defun org-create-file-search-in-bibtex ()
10589 "Create the search string and description for a BibTeX database entry."
10590 (when (eq major-mode 'bibtex-mode)
10591 ;; yes, we want to construct this search string.
10592 ;; Make a good description for this entry, using names, year and the title
10593 ;; Put it into the `description' variable which is dynamically scoped.
10594 (let ((bibtex-autokey-names 1)
10595 (bibtex-autokey-names-stretch 1)
10596 (bibtex-autokey-name-case-convert-function 'identity)
10597 (bibtex-autokey-name-separator " & ")
10598 (bibtex-autokey-additional-names " et al.")
10599 (bibtex-autokey-year-length 4)
10600 (bibtex-autokey-name-year-separator " ")
10601 (bibtex-autokey-titlewords 3)
10602 (bibtex-autokey-titleword-separator " ")
10603 (bibtex-autokey-titleword-case-convert-function 'identity)
10604 (bibtex-autokey-titleword-length 'infty)
10605 (bibtex-autokey-year-title-separator ": "))
10606 (setq description (bibtex-generate-autokey)))
10607 ;; Now parse the entry, get the key and return it.
10608 (save-excursion
10609 (bibtex-beginning-of-entry)
10610 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10612 (defun org-execute-file-search-in-bibtex (s)
10613 "Find the link search string S as a key for a database entry."
10614 (when (eq major-mode 'bibtex-mode)
10615 ;; Yes, we want to do the search in this file.
10616 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10617 (goto-char (point-min))
10618 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10619 (regexp-quote s) "[ \t\n]*,") nil t)
10620 (goto-char (match-beginning 0)))
10621 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10622 ;; Use double prefix to indicate that any web link should be browsed
10623 (let ((b (current-buffer)) (p (point)))
10624 ;; Restore the window configuration because we just use the web link
10625 (set-window-configuration org-window-config-before-follow-link)
10626 (save-excursion (set-buffer b) (goto-char p)
10627 (bibtex-url)))
10628 (recenter 0)) ; Move entry start to beginning of window
10629 ;; return t to indicate that the search is done.
10632 ;; Finally add the functions to the right hooks.
10633 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10634 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10636 ;; end of Bibtex link setup
10638 (defun org-upgrade-old-links (&optional query-description)
10639 "Transfer old <...> style links to new [[...]] style links.
10640 With arg query-description, ask at each match for a description text to use
10641 for this link."
10642 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
10643 (save-excursion
10644 (goto-char (point-min))
10645 (let ((re (concat "\\([^[]\\)<\\("
10646 "\\(" (mapconcat 'identity org-link-types "\\|")
10647 "\\):"
10648 "[^" org-non-link-chars "]+\\)>"))
10649 l1 l2 (cnt 0))
10650 (while (re-search-forward re nil t)
10651 (setq cnt (1+ cnt)
10652 l1 (org-match-string-no-properties 2)
10653 l2 (save-match-data (org-link-escape l1)))
10654 (when query-description (setq l1 (read-string "Desc: " l1)))
10655 (if (equal l1 l2)
10656 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
10657 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
10658 (message "%d matches have beed treated" cnt))))
10660 (defun org-open-file (path &optional in-emacs line search)
10661 "Open the file at PATH.
10662 First, this expands any special file name abbreviations. Then the
10663 configuration variable `org-file-apps' is checked if it contains an
10664 entry for this file type, and if yes, the corresponding command is launched.
10665 If no application is found, Emacs simply visits the file.
10666 With optional argument IN-EMACS, Emacs will visit the file.
10667 Optional LINE specifies a line to go to, optional SEARCH a string to
10668 search for. If LINE or SEARCH is given, the file will always be
10669 opened in Emacs.
10670 If the file does not exist, an error is thrown."
10671 (setq in-emacs (or in-emacs line search))
10672 (let* ((file (if (equal path "")
10673 buffer-file-name
10674 (substitute-in-file-name (expand-file-name path))))
10675 (apps (append org-file-apps (org-default-apps)))
10676 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10677 (dirp (if remp nil (file-directory-p file)))
10678 (dfile (downcase file))
10679 (old-buffer (current-buffer))
10680 (old-pos (point))
10681 (old-mode major-mode)
10682 ext cmd)
10683 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10684 (setq ext (match-string 1 dfile))
10685 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10686 (setq ext (match-string 1 dfile))))
10687 (if in-emacs
10688 (setq cmd 'emacs)
10689 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10690 (and dirp (cdr (assoc 'directory apps)))
10691 (cdr (assoc ext apps))
10692 (cdr (assoc t apps)))))
10693 (when (eq cmd 'mailcap)
10694 (require 'mailcap)
10695 (mailcap-parse-mailcaps)
10696 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10697 (command (mailcap-mime-info mime-type)))
10698 (if (stringp command)
10699 (setq cmd command)
10700 (setq cmd 'emacs))))
10701 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10702 (not (file-exists-p file))
10703 (not org-open-non-existing-files))
10704 (error "No such file: %s" file))
10705 (cond
10706 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10707 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10708 (if (string-match "['\"]%s['\"]" cmd)
10709 (setq cmd (replace-match "%s" t t cmd)))
10710 (setq cmd (format cmd (shell-quote-argument file)))
10711 (save-window-excursion
10712 (shell-command (concat cmd " &"))))
10713 ((or (stringp cmd)
10714 (eq cmd 'emacs))
10715 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
10716 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
10717 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10718 (if line (goto-line line)
10719 (if search (org-link-search search))))
10720 ((consp cmd)
10721 (eval cmd))
10722 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10723 (and (org-mode-p) (eq old-mode 'org-mode)
10724 (or (not (equal old-buffer (current-buffer)))
10725 (not (equal old-pos (point))))
10726 (org-mark-ring-push old-pos old-buffer))))
10728 (defun org-default-apps ()
10729 "Return the default applications for this operating system."
10730 (cond
10731 ((eq system-type 'darwin)
10732 org-file-apps-defaults-macosx)
10733 ((eq system-type 'windows-nt)
10734 org-file-apps-defaults-windowsnt)
10735 (t org-file-apps-defaults-gnu)))
10737 (defun org-expand-file-name (path)
10738 "Replace special path abbreviations and expand the file name."
10739 (expand-file-name path))
10741 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10742 (defun org-file-remote-p (file)
10743 "Test whether FILE specifies a location on a remote system.
10744 Return non-nil if the location is indeed remote.
10746 For example, the filename \"/user@host:/foo\" specifies a location
10747 on the system \"/user@host:\"."
10748 (cond ((fboundp 'file-remote-p)
10749 (file-remote-p file))
10750 ((fboundp 'tramp-handle-file-remote-p)
10751 (tramp-handle-file-remote-p file))
10752 ((and (boundp 'ange-ftp-name-format)
10753 (string-match (car ange-ftp-name-format) file))
10755 (t nil)))
10757 (defvar org-insert-link-history nil
10758 "Minibuffer history for links inserted with `org-insert-link'.")
10760 (defvar org-stored-links nil
10761 "Contains the links stored with `org-store-link'.")
10763 ;;;###autoload
10764 (defun org-store-link (arg)
10765 "\\<org-mode-map>Store an org-link to the current location.
10766 This link can later be inserted into an org-buffer with
10767 \\[org-insert-link].
10768 For some link types, a prefix arg is interpreted:
10769 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10770 For file links, arg negates `org-context-in-file-links'."
10771 (interactive "P")
10772 (let (link cpltxt desc description search txt (pos (point)))
10773 (cond
10775 ((eq major-mode 'bbdb-mode)
10776 (setq cpltxt (concat
10777 "bbdb:"
10778 (or (bbdb-record-name (bbdb-current-record))
10779 (bbdb-record-company (bbdb-current-record))))
10780 link (org-make-link cpltxt)))
10782 ((eq major-mode 'Info-mode)
10783 (setq link (org-make-link "info:"
10784 (file-name-nondirectory Info-current-file)
10785 ":" Info-current-node))
10786 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10787 ":" Info-current-node)))
10789 ((eq major-mode 'calendar-mode)
10790 (let ((cd (calendar-cursor-to-date)))
10791 (setq link
10792 (format-time-string
10793 (car org-time-stamp-formats)
10794 (apply 'encode-time
10795 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10796 nil nil nil))))))
10798 ((or (eq major-mode 'vm-summary-mode)
10799 (eq major-mode 'vm-presentation-mode))
10800 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10801 (vm-follow-summary-cursor)
10802 (save-excursion
10803 (vm-select-folder-buffer)
10804 (let* ((message (car vm-message-pointer))
10805 (folder buffer-file-name)
10806 (subject (vm-su-subject message))
10807 (author (vm-su-full-name message))
10808 (message-id (vm-su-message-id message)))
10809 (setq message-id (org-remove-angle-brackets message-id))
10810 (setq folder (abbreviate-file-name folder))
10811 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10812 folder)
10813 (setq folder (replace-match "" t t folder)))
10814 (setq cpltxt (concat author " on: " subject))
10815 (setq link (org-make-link "vm:" folder "#" message-id)))))
10817 ((eq major-mode 'wl-summary-mode)
10818 (let* ((msgnum (wl-summary-message-number))
10819 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10820 msgnum 'message-id))
10821 (wl-message-entity (elmo-msgdb-overview-get-entity
10822 msgnum (wl-summary-buffer-msgdb)))
10823 (author (wl-summary-line-from)) ; FIXME: correct?
10824 (subject "???")) ; FIXME:
10825 (setq message-id (org-remove-angle-brackets message-id))
10826 (setq cpltxt (concat author " on: " subject))
10827 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10828 "#" message-id))))
10830 ((or (equal major-mode 'mh-folder-mode)
10831 (equal major-mode 'mh-show-mode))
10832 (let ((from-header (org-mhe-get-header "From:"))
10833 (to-header (org-mhe-get-header "To:"))
10834 (subject (org-mhe-get-header "Subject:")))
10835 (setq cpltxt (concat from-header " on: " subject))
10836 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10837 (org-remove-angle-brackets
10838 (org-mhe-get-header "Message-Id:"))))))
10840 ((eq major-mode 'rmail-mode)
10841 (save-excursion
10842 (save-restriction
10843 (rmail-narrow-to-non-pruned-header)
10844 (let ((folder buffer-file-name)
10845 (message-id (mail-fetch-field "message-id"))
10846 (author (mail-fetch-field "from"))
10847 (subject (mail-fetch-field "subject")))
10848 (setq message-id (org-remove-angle-brackets message-id))
10849 (setq cpltxt (concat author " on: " subject))
10850 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10852 ((eq major-mode 'gnus-group-mode)
10853 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10854 (gnus-group-group-name)) ; version
10855 ((fboundp 'gnus-group-name)
10856 (gnus-group-name))
10857 (t "???"))))
10858 (setq cpltxt (concat
10859 (if (org-xor arg org-usenet-links-prefer-google)
10860 "http://groups.google.com/groups?group="
10861 "gnus:")
10862 group)
10863 link (org-make-link cpltxt))))
10865 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10866 (require 'gnus-sum)
10867 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10868 (gnus-summary-beginning-of-article)
10869 (let* ((group (car gnus-article-current))
10870 (article (cdr gnus-article-current))
10871 (header (gnus-summary-article-header article))
10872 (author (mail-header-from header))
10873 (message-id (mail-header-id header))
10874 (date (mail-header-date header))
10875 (subject (gnus-summary-subject-string)))
10876 (setq cpltxt (concat author " on: " subject))
10877 (if (org-xor arg org-usenet-links-prefer-google)
10878 (setq link
10879 (concat
10880 cpltxt "\n "
10881 (format "http://groups.google.com/groups?as_umsgid=%s"
10882 (org-fixup-message-id-for-http message-id))))
10883 (setq link (org-make-link "gnus:" group
10884 "#" (number-to-string article))))))
10886 ((eq major-mode 'w3-mode)
10887 (setq cpltxt (url-view-url t)
10888 link (org-make-link cpltxt)))
10889 ((eq major-mode 'w3m-mode)
10890 (setq cpltxt (or w3m-current-title w3m-current-url)
10891 link (org-make-link w3m-current-url)))
10893 ((setq search (run-hook-with-args-until-success
10894 'org-create-file-search-functions))
10895 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10896 "::" search))
10897 (setq cpltxt (or description link)))
10899 ((eq major-mode 'image-mode)
10900 (setq cpltxt (concat "file:"
10901 (abbreviate-file-name buffer-file-name))
10902 link (org-make-link cpltxt)))
10904 ((eq major-mode 'dired-mode)
10905 ;; link to the file in the current line
10906 (setq cpltxt (concat "file:"
10907 (abbreviate-file-name
10908 (expand-file-name
10909 (dired-get-filename nil t))))
10910 link (org-make-link cpltxt)))
10912 ((and buffer-file-name (org-mode-p))
10913 ;; Just link to current headline
10914 (setq cpltxt (concat "file:"
10915 (abbreviate-file-name buffer-file-name)))
10916 ;; Add a context search string
10917 (when (org-xor org-context-in-file-links arg)
10918 ;; Check if we are on a target
10919 (if (save-excursion
10920 (skip-chars-forward "^>\n\r")
10921 (and (re-search-backward "<<" nil t)
10922 (looking-at "<<\\(.*?\\)>>")
10923 (<= (match-beginning 0) pos)
10924 (>= (match-end 0) pos)))
10925 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10926 (setq txt (cond
10927 ((org-on-heading-p) nil)
10928 ((org-region-active-p)
10929 (buffer-substring (region-beginning) (region-end)))
10930 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10931 (when (or (null txt) (string-match "\\S-" txt))
10932 (setq cpltxt
10933 (concat cpltxt "::"
10934 (if org-file-link-context-use-camel-case
10935 (org-make-org-heading-camel txt)
10936 (org-make-org-heading-search-string txt)))
10937 desc "NONE"))))
10938 (if (string-match "::\\'" cpltxt)
10939 (setq cpltxt (substring cpltxt 0 -2)))
10940 (setq link (org-make-link cpltxt)))
10942 (buffer-file-name
10943 ;; Just link to this file here.
10944 (setq cpltxt (concat "file:"
10945 (abbreviate-file-name buffer-file-name)))
10946 ;; Add a context string
10947 (when (org-xor org-context-in-file-links arg)
10948 (setq txt (if (org-region-active-p)
10949 (buffer-substring (region-beginning) (region-end))
10950 (buffer-substring (point-at-bol) (point-at-eol))))
10951 ;; Only use search option if there is some text.
10952 (when (string-match "\\S-" txt)
10953 (setq cpltxt
10954 (concat cpltxt "::"
10955 (if org-file-link-context-use-camel-case
10956 (org-make-org-heading-camel txt)
10957 (org-make-org-heading-search-string txt)))
10958 desc "NONE")))
10959 (setq link (org-make-link cpltxt)))
10961 ((interactive-p)
10962 (error "Cannot link to a buffer which is not visiting a file"))
10964 (t (setq link nil)))
10966 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10967 (setq link (or link cpltxt)
10968 desc (or desc cpltxt))
10969 (if (equal desc "NONE") (setq desc nil))
10971 (if (and (interactive-p) link)
10972 (progn
10973 (setq org-stored-links
10974 (cons (list cpltxt link desc) org-stored-links))
10975 (message "Stored: %s" (or cpltxt link)))
10976 (org-make-link-string link desc))))
10978 (defun org-make-org-heading-search-string (&optional string heading)
10979 "Make search string for STRING or current headline."
10980 (interactive)
10981 (let ((s (or string (org-get-heading))))
10982 (unless (and string (not heading))
10983 ;; We are using a headline, clean up garbage in there.
10984 (if (string-match org-todo-regexp s)
10985 (setq s (replace-match "" t t s)))
10986 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10987 (setq s (replace-match "" t t s)))
10988 (setq s (org-trim s))
10989 (if (string-match (concat "^\\(" org-quote-string "\\|"
10990 org-comment-string "\\)") s)
10991 (setq s (replace-match "" t t s)))
10992 (while (string-match org-ts-regexp s)
10993 (setq s (replace-match "" t t s))))
10994 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10995 (setq s (replace-match " " t t s)))
10996 (or string (setq s (concat "*" s))) ; Add * for headlines
10997 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10999 (defun org-make-org-heading-camel (&optional string heading)
11000 "Make a CamelCase string for STRING or the current headline."
11001 (interactive)
11002 (let ((s (or string (org-get-heading))))
11003 (unless (and string (not heading))
11004 ;; We are using a headline, clean up garbage in there.
11005 (if (string-match org-todo-regexp s)
11006 (setq s (replace-match "" t t s)))
11007 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
11008 (setq s (replace-match "" t t s)))
11009 (setq s (org-trim s))
11010 (if (string-match (concat "^\\(" org-quote-string "\\|"
11011 org-comment-string "\\)") s)
11012 (setq s (replace-match "" t t s)))
11013 (while (string-match org-ts-regexp s)
11014 (setq s (replace-match "" t t s))))
11015 (while (string-match "[^a-zA-Z_ \t]+" s)
11016 (setq s (replace-match " " t t s)))
11017 (or string (setq s (concat "*" s))) ; Add * for headlines
11018 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
11020 (defun org-make-link (&rest strings)
11021 "Concatenate STRINGS, format resulting string with `org-link-format'."
11022 (format org-link-format (apply 'concat strings)))
11024 (defun org-make-link-string (link &optional description)
11025 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11026 (if (eq org-link-style 'plain)
11027 (if (equal description link)
11028 link
11029 (concat description "\n" link))
11030 (when (stringp description)
11031 ;; Remove brackets from the description, they are fatal.
11032 (while (string-match "\\[\\|\\]" description)
11033 (setq description (replace-match "" t t description))))
11034 (when (equal (org-link-escape link) description)
11035 ;; No description needed, it is identical
11036 (setq description nil))
11037 (when (and (not description)
11038 (not (equal link (org-link-escape link))))
11039 (setq description link))
11040 (concat "[[" (org-link-escape link) "]"
11041 (if description (concat "[" description "]") "")
11042 "]")))
11044 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
11045 "Association list of escapes for some characters problematic in links.")
11047 (defun org-link-escape (text)
11048 "Escape charaters in TEXT that are problematic for links."
11049 (when text
11050 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11051 org-link-escape-chars "\\|")))
11052 (while (string-match re text)
11053 (setq text
11054 (replace-match
11055 (cdr (assoc (match-string 0 text) org-link-escape-chars))
11056 t t text)))
11057 text)))
11059 (defun org-link-unescape (text)
11060 "Reverse the action of `org-link-escape'."
11061 (when text
11062 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11063 org-link-escape-chars "\\|")))
11064 (while (string-match re text)
11065 (setq text
11066 (replace-match
11067 (car (rassoc (match-string 0 text) org-link-escape-chars))
11068 t t text)))
11069 text)))
11071 (defun org-xor (a b)
11072 "Exclusive or."
11073 (if a (not b) b))
11075 (defun org-get-header (header)
11076 "Find a header field in the current buffer."
11077 (save-excursion
11078 (goto-char (point-min))
11079 (let ((case-fold-search t) s)
11080 (cond
11081 ((eq header 'from)
11082 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11083 (setq s (match-string 1)))
11084 (while (string-match "\"" s)
11085 (setq s (replace-match "" t t s)))
11086 (if (string-match "[<(].*" s)
11087 (setq s (replace-match "" t t s))))
11088 ((eq header 'message-id)
11089 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11090 (setq s (match-string 1))))
11091 ((eq header 'subject)
11092 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11093 (setq s (match-string 1)))))
11094 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11095 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11096 s)))
11099 (defun org-fixup-message-id-for-http (s)
11100 "Replace special characters in a message id, so it can be used in an http query."
11101 (while (string-match "<" s)
11102 (setq s (replace-match "%3C" t t s)))
11103 (while (string-match ">" s)
11104 (setq s (replace-match "%3E" t t s)))
11105 (while (string-match "@" s)
11106 (setq s (replace-match "%40" t t s)))
11109 (defun org-insert-link (&optional complete-file)
11110 "Insert a link. At the prompt, enter the link.
11112 Completion can be used to select a link previously stored with
11113 `org-store-link'. When the empty string is entered (i.e. if you just
11114 press RET at the prompt), the link defaults to the most recently
11115 stored link. As SPC triggers completion in the minibuffer, you need to
11116 use M-SPC or C-q SPC to force the insertion of a space character.
11118 You will also be prompted for a description, and if one is given, it will
11119 be displayed in the buffer instead of the link.
11121 If there is already a link at point, this command will allow you to edit link
11122 and description parts.
11124 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11125 selected using completion. The path to the file will be relative to
11126 the current directory if the file is in the current directory or a
11127 subdirectory. Otherwise, the link will be the absolute path as
11128 completed in the minibuffer (i.e. normally ~/path/to/file).
11130 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11131 is in the current directory or below.
11132 With three \\[universal-argument] prefixes, negate the meaning of
11133 `org-keep-stored-link-after-insertion'."
11134 (interactive "P")
11135 (let (link desc entry remove file (pos (point)))
11136 (cond
11137 ((save-excursion
11138 (skip-chars-forward "^]\n\r")
11139 (and (re-search-backward "\\[\\[" nil t)
11140 (looking-at org-bracket-link-regexp)
11141 (<= (match-beginning 0) pos)
11142 (>= (match-end 0) pos)))
11143 ;; We do have a link at point, and we are going to edit it.
11144 (setq remove (list (match-beginning 0) (match-end 0)))
11145 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11146 (setq link (read-string "Link: "
11147 (org-link-unescape
11148 (org-match-string-no-properties 1)))))
11149 ((equal complete-file '(4))
11150 ;; Completing read for file names.
11151 (setq file (read-file-name "File: "))
11152 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11153 (pwd1 (file-name-as-directory (abbreviate-file-name
11154 (expand-file-name ".")))))
11155 (cond
11156 ((equal complete-file '(16))
11157 (setq link (org-make-link
11158 "file:"
11159 (abbreviate-file-name (expand-file-name file)))))
11160 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11161 (setq link (org-make-link "file:" (match-string 1 file))))
11162 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11163 (expand-file-name file))
11164 (setq link (org-make-link
11165 "file:" (match-string 1 (expand-file-name file)))))
11166 (t (setq link (org-make-link "file:" file))))))
11168 ;; Read link, with completion for stored links.
11169 (setq link (org-completing-read
11170 "Link: " org-stored-links nil nil nil
11171 org-insert-link-history
11172 (or (car (car org-stored-links)))))
11173 (setq entry (assoc link org-stored-links))
11174 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11175 (not org-keep-stored-link-after-insertion))
11176 (setq org-stored-links (delq (assoc link org-stored-links)
11177 org-stored-links)))
11178 (setq link (if entry (nth 1 entry) link)
11179 desc (or desc (nth 2 entry)))))
11181 (if (string-match org-plain-link-re link)
11182 ;; URL-like link, normalize the use of angular brackets.
11183 (setq link (org-make-link (org-remove-angle-brackets link))))
11185 ;; Check if we are linking to the current file with a search option
11186 ;; If yes, simplify the link by using only the search option.
11187 (when (and buffer-file-name
11188 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11189 (let* ((path (match-string 1 link))
11190 (case-fold-search nil)
11191 (search (match-string 2 link)))
11192 (save-match-data
11193 (if (equal (file-truename buffer-file-name) (file-truename path))
11194 ;; We are linking to this same file, with a search option
11195 (setq link search)))))
11197 ;; Check if we can/should use a relative path. If yes, simplify the link
11198 (when (string-match "\\<file:\\(.*\\)" link)
11199 (let* ((path (match-string 1 link))
11200 (case-fold-search nil))
11201 (cond
11202 ((eq org-link-file-path-type 'absolute)
11203 (setq path (abbreviate-file-name (expand-file-name path))))
11204 ((eq org-link-file-path-type 'noabbrev)
11205 (setq path (expand-file-name path)))
11206 ((eq org-link-file-path-type 'relative)
11207 (setq path (file-relative-name path)))
11209 (save-match-data
11210 (if (string-match (concat "^" (regexp-quote
11211 (file-name-as-directory
11212 (expand-file-name "."))))
11213 (expand-file-name path))
11214 ;; We are linking a file with relative path name.
11215 (setq path (substring (expand-file-name path)
11216 (match-end 0)))))))
11217 (setq link (concat "file:" path))))
11219 (setq desc (read-string "Description: " desc))
11220 (unless (string-match "\\S-" desc) (setq desc nil))
11221 (if remove (apply 'delete-region remove))
11222 (insert (org-make-link-string link desc))))
11224 (defun org-completing-read (&rest args)
11225 (let ((minibuffer-local-completion-map
11226 (copy-keymap minibuffer-local-completion-map)))
11227 (define-key minibuffer-local-completion-map " " 'self-insert-command)
11228 (apply 'completing-read args)))
11230 ;;; Hooks for remember.el
11232 (defvar org-finish-function nil)
11234 ;;;###autoload
11235 (defun org-remember-annotation ()
11236 "Return a link to the current location as an annotation for remember.el.
11237 If you are using Org-mode files as target for data storage with
11238 remember.el, then the annotations should include a link compatible with the
11239 conventions in Org-mode. This function returns such a link."
11240 (org-store-link nil))
11242 (defconst org-remember-help
11243 "Select a destination location for the note.
11244 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
11245 RET at beg-of-buf -> Append to file as level 2 headline
11246 RET on headline -> Store as sublevel entry to current headline
11247 <left>/<right> -> before/after current headline, same headings level")
11249 ;;;###autoload
11250 (defun org-remember-apply-template ()
11251 "Initialize *remember* buffer with template, invoke `org-mode'.
11252 This function should be placed into `remember-mode-hook' and in fact requires
11253 to be run from that hook to fucntion properly."
11254 (if org-remember-templates
11256 (let* ((entry (if (= (length org-remember-templates) 1)
11257 (cdar org-remember-templates)
11258 (message "Select template: %s"
11259 (mapconcat
11260 (lambda (x) (char-to-string (car x)))
11261 org-remember-templates " "))
11262 (cdr (assoc (read-char-exclusive) org-remember-templates))))
11263 (tpl (car entry))
11264 (file (if (consp (cdr entry)) (nth 1 entry)))
11265 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
11266 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
11267 (v-u (concat "[" (substring v-t 1 -1) "]"))
11268 (v-U (concat "[" (substring v-T 1 -1) "]"))
11269 (v-a annotation) ; defined in `remember-mode'
11270 (v-i initial) ; defined in `remember-mode'
11271 (v-n user-full-name)
11273 (unless tpl (setq tpl "") (message "No template") (ding))
11274 (insert tpl) (goto-char (point-min))
11275 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
11276 (when (and initial (equal (match-string 0) "%i"))
11277 (save-match-data
11278 (let* ((lead (buffer-substring
11279 (point-at-bol) (match-beginning 0))))
11280 (setq v-i (mapconcat 'identity
11281 (org-split-string initial "\n")
11282 (concat "\n" lead))))))
11283 (replace-match
11284 (or (eval (intern (concat "v-" (match-string 1)))) "")
11285 t t))
11286 (let ((org-startup-folded nil)
11287 (org-startup-with-deadline-check nil))
11288 (org-mode))
11289 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
11290 (org-set-local 'org-default-notes-file file))
11291 (goto-char (point-min))
11292 (if (re-search-forward "%\\?" nil t) (replace-match "")))
11293 (let ((org-startup-folded nil)
11294 (org-startup-with-deadline-check nil))
11295 (org-mode)))
11296 (org-set-local 'org-finish-function 'remember-buffer))
11298 ;;;###autoload
11299 (defun org-remember-handler ()
11300 "Store stuff from remember.el into an org file.
11301 First prompts for an org file. If the user just presses return, the value
11302 of `org-default-notes-file' is used.
11303 Then the command offers the headings tree of the selected file in order to
11304 file the text at a specific location.
11305 You can either immediately press RET to get the note appended to the
11306 file, or you can use vertical cursor motion and visibility cycling (TAB) to
11307 find a better place. Then press RET or <left> or <right> in insert the note.
11309 Key Cursor position Note gets inserted
11310 -----------------------------------------------------------------------------
11311 RET buffer-start as level 2 heading at end of file
11312 RET on headline as sublevel of the heading at cursor
11313 RET no heading at cursor position, level taken from context.
11314 Or use prefix arg to specify level manually.
11315 <left> on headline as same level, before current heading
11316 <right> on headline as same level, after current heading
11318 So the fastest way to store the note is to press RET RET to append it to
11319 the default file. This way your current train of thought is not
11320 interrupted, in accordance with the principles of remember.el. But with
11321 little extra effort, you can push it directly to the correct location.
11323 Before being stored away, the function ensures that the text has a
11324 headline, i.e. a first line that starts with a \"*\". If not, a headline
11325 is constructed from the current date and some additional data.
11327 If the variable `org-adapt-indentation' is non-nil, the entire text is
11328 also indented so that it starts in the same column as the headline
11329 \(i.e. after the stars).
11331 See also the variable `org-reverse-note-order'."
11332 (catch 'quit
11333 (let* ((txt (buffer-substring (point-min) (point-max)))
11334 (fastp current-prefix-arg)
11335 (file (if fastp org-default-notes-file (org-get-org-file)))
11336 (visiting (find-buffer-visiting file))
11337 (org-startup-with-deadline-check nil)
11338 (org-startup-folded nil)
11339 (org-startup-align-all-tables nil)
11340 spos level indent reversed)
11341 ;; Modify text so that it becomes a nice subtree which can be inserted
11342 ;; into an org tree.
11343 (let* ((lines (split-string txt "\n"))
11344 first)
11345 ;; remove empty lines at the beginning
11346 (while (and lines (string-match "^[ \t]*\n" (car lines)))
11347 (setq lines (cdr lines)))
11348 (setq first (car lines) lines (cdr lines))
11349 (if (string-match "^\\*+" first)
11350 ;; Is already a headline
11351 (setq indent nil)
11352 ;; We need to add a headline: Use time and first buffer line
11353 (setq lines (cons first lines)
11354 first (concat "* " (current-time-string)
11355 " (" (remember-buffer-desc) ")")
11356 indent " "))
11357 (if (and org-adapt-indentation indent)
11358 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
11359 (setq txt (concat first "\n"
11360 (mapconcat 'identity lines "\n"))))
11361 ;; Find the file
11362 (if (not visiting)
11363 (find-file-noselect file))
11364 (with-current-buffer (get-file-buffer file)
11365 (save-excursion (and (goto-char (point-min))
11366 (not (re-search-forward "^\\* " nil t))
11367 (insert "\n* Notes\n")))
11368 (setq reversed (org-notes-order-reversed-p))
11369 (save-excursion
11370 (save-restriction
11371 (widen)
11372 ;; Ask the User for a location
11373 (setq spos (if fastp 1 (org-get-location
11374 (current-buffer)
11375 org-remember-help)))
11376 (if (not spos) (throw 'quit nil)) ; return nil to show we did
11377 ; not handle this note
11378 (goto-char spos)
11379 (cond ((bobp)
11380 ;; Put it at the start or end, as level 2
11381 (save-restriction
11382 (widen)
11383 (goto-char (if reversed (point-min) (point-max)))
11384 (if (not (bolp)) (newline))
11385 (org-paste-subtree 2 txt)))
11386 ((and (org-on-heading-p nil) (not current-prefix-arg))
11387 ;; Put it below this entry, at the beg/end of the subtree
11388 (org-back-to-heading)
11389 (setq level (funcall outline-level))
11390 (if reversed
11391 (outline-end-of-heading)
11392 (outline-end-of-subtree))
11393 (if (not (bolp)) (newline))
11394 (beginning-of-line 1)
11395 (org-paste-subtree (org-get-legal-level level 1) txt))
11397 ;; Put it right there, with automatic level determined by
11398 ;; org-paste-subtree or from prefix arg
11399 (org-paste-subtree current-prefix-arg txt)))
11400 (when remember-save-after-remembering
11401 (save-buffer)
11402 (if (not visiting) (kill-buffer (current-buffer)))))))))
11403 t) ;; return t to indicate that we took care of this note.
11405 (defun org-get-org-file ()
11406 "Read a filename, with default directory `org-directory'."
11407 (let ((default (or org-default-notes-file remember-data-file)))
11408 (read-file-name (format "File name [%s]: " default)
11409 (file-name-as-directory org-directory)
11410 default)))
11412 (defun org-notes-order-reversed-p ()
11413 "Check if the current file should receive notes in reversed order."
11414 (cond
11415 ((not org-reverse-note-order) nil)
11416 ((eq t org-reverse-note-order) t)
11417 ((not (listp org-reverse-note-order)) nil)
11418 (t (catch 'exit
11419 (let ((all org-reverse-note-order)
11420 entry)
11421 (while (setq entry (pop all))
11422 (if (string-match (car entry) buffer-file-name)
11423 (throw 'exit (cdr entry))))
11424 nil)))))
11426 ;;; Tables
11428 ;; Watch out: Here we are talking about two different kind of tables.
11429 ;; Most of the code is for the tables created with the Org-mode table editor.
11430 ;; Sometimes, we talk about tables created and edited with the table.el
11431 ;; Emacs package. We call the former org-type tables, and the latter
11432 ;; table.el-type tables.
11435 (defun org-before-change-function (beg end)
11436 "Every change indicates that a table might need an update."
11437 (setq org-table-may-need-update t))
11439 (defconst org-table-line-regexp "^[ \t]*|"
11440 "Detects an org-type table line.")
11441 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
11442 "Detects an org-type table line.")
11443 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
11444 "Detects a table line marked for automatic recalculation.")
11445 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
11446 "Detects a table line marked for automatic recalculation.")
11447 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
11448 "Detects a table line marked for automatic recalculation.")
11449 (defconst org-table-hline-regexp "^[ \t]*|-"
11450 "Detects an org-type table hline.")
11451 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
11452 "Detects a table-type table hline.")
11453 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
11454 "Detects an org-type or table-type table.")
11455 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
11456 "Searching from within a table (any type) this finds the first line
11457 outside the table.")
11458 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
11459 "Searching from within a table (any type) this finds the first line
11460 outside the table.")
11462 (defun org-table-create-with-table.el ()
11463 "Use the table.el package to insert a new table.
11464 If there is already a table at point, convert between Org-mode tables
11465 and table.el tables."
11466 (interactive)
11467 (require 'table)
11468 (cond
11469 ((org-at-table.el-p)
11470 (if (y-or-n-p "Convert table to Org-mode table? ")
11471 (org-table-convert)))
11472 ((org-at-table-p)
11473 (if (y-or-n-p "Convert table to table.el table? ")
11474 (org-table-convert)))
11475 (t (call-interactively 'table-insert))))
11477 (defun org-table-create-or-convert-from-region (arg)
11478 "Convert region to table, or create an empty table.
11479 If there is an active region, convert it to a table. If there is no such
11480 region, create an empty table."
11481 (interactive "P")
11482 (if (org-region-active-p)
11483 (org-table-convert-region (region-beginning) (region-end) arg)
11484 (org-table-create arg)))
11486 (defun org-table-create (&optional size)
11487 "Query for a size and insert a table skeleton.
11488 SIZE is a string Columns x Rows like for example \"3x2\"."
11489 (interactive "P")
11490 (unless size
11491 (setq size (read-string
11492 (concat "Table size Columns x Rows [e.g. "
11493 org-table-default-size "]: ")
11494 "" nil org-table-default-size)))
11496 (let* ((pos (point))
11497 (indent (make-string (current-column) ?\ ))
11498 (split (org-split-string size " *x *"))
11499 (rows (string-to-number (nth 1 split)))
11500 (columns (string-to-number (car split)))
11501 (line (concat (apply 'concat indent "|" (make-list columns " |"))
11502 "\n")))
11503 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
11504 (point-at-bol) (point)))
11505 (beginning-of-line 1)
11506 (newline))
11507 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
11508 (dotimes (i rows) (insert line))
11509 (goto-char pos)
11510 (if (> rows 1)
11511 ;; Insert a hline after the first row.
11512 (progn
11513 (end-of-line 1)
11514 (insert "\n|-")
11515 (goto-char pos)))
11516 (org-table-align)))
11518 (defun org-table-convert-region (beg0 end0 &optional nspace)
11519 "Convert region to a table.
11520 The region goes from BEG0 to END0, but these borders will be moved
11521 slightly, to make sure a beginning of line in the first line is included.
11522 When NSPACE is non-nil, it indicates the minimum number of spaces that
11523 separate columns (default: just one space)."
11524 (interactive "rP")
11525 (let* ((beg (min beg0 end0))
11526 (end (max beg0 end0))
11527 (tabsep t)
11529 (goto-char beg)
11530 (beginning-of-line 1)
11531 (setq beg (move-marker (make-marker) (point)))
11532 (goto-char end)
11533 (if (bolp) (backward-char 1) (end-of-line 1))
11534 (setq end (move-marker (make-marker) (point)))
11535 ;; Lets see if this is tab-separated material. If every nonempty line
11536 ;; contains a tab, we will assume that it is tab-separated material
11537 (if nspace
11538 (setq tabsep nil)
11539 (goto-char beg)
11540 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
11541 (if nspace (setq tabsep nil))
11542 (if tabsep
11543 (setq re "^\\|\t")
11544 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
11545 (max 1 (prefix-numeric-value nspace)))))
11546 (goto-char beg)
11547 (while (re-search-forward re end t)
11548 (replace-match "| " t t))
11549 (goto-char beg)
11550 (insert " ")
11551 (org-table-align)))
11553 (defun org-table-import (file arg)
11554 "Import FILE as a table.
11555 The file is assumed to be tab-separated. Such files can be produced by most
11556 spreadsheet and database applications. If no tabs (at least one per line)
11557 are found, lines will be split on whitespace into fields."
11558 (interactive "f\nP")
11559 (or (bolp) (newline))
11560 (let ((beg (point))
11561 (pm (point-max)))
11562 (insert-file-contents file)
11563 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
11565 (defun org-table-export ()
11566 "Export table as a tab-separated file.
11567 Such a file can be imported into a spreadsheet program like Excel."
11568 (interactive)
11569 (let* ((beg (org-table-begin))
11570 (end (org-table-end))
11571 (table (buffer-substring beg end))
11572 (file (read-file-name "Export table to: "))
11573 buf)
11574 (unless (or (not (file-exists-p file))
11575 (y-or-n-p (format "Overwrite file %s? " file)))
11576 (error "Abort"))
11577 (with-current-buffer (find-file-noselect file)
11578 (setq buf (current-buffer))
11579 (erase-buffer)
11580 (fundamental-mode)
11581 (insert table)
11582 (goto-char (point-min))
11583 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
11584 (replace-match "" t t)
11585 (end-of-line 1))
11586 (goto-char (point-min))
11587 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
11588 (replace-match "" t t)
11589 (goto-char (min (1+ (point)) (point-max))))
11590 (goto-char (point-min))
11591 (while (re-search-forward "^-[-+]*$" nil t)
11592 (replace-match "")
11593 (if (looking-at "\n")
11594 (delete-char 1)))
11595 (goto-char (point-min))
11596 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
11597 (replace-match "\t" t t))
11598 (save-buffer))
11599 (kill-buffer buf)))
11601 (defvar org-table-aligned-begin-marker (make-marker)
11602 "Marker at the beginning of the table last aligned.
11603 Used to check if cursor still is in that table, to minimize realignment.")
11604 (defvar org-table-aligned-end-marker (make-marker)
11605 "Marker at the end of the table last aligned.
11606 Used to check if cursor still is in that table, to minimize realignment.")
11607 (defvar org-table-last-alignment nil
11608 "List of flags for flushright alignment, from the last re-alignment.
11609 This is being used to correctly align a single field after TAB or RET.")
11610 (defvar org-table-last-column-widths nil
11611 "List of max width of fields in each column.
11612 This is being used to correctly align a single field after TAB or RET.")
11614 (defvar org-last-recalc-line nil)
11615 (defconst org-narrow-column-arrow "=>"
11616 "Used as display property in narrowed table columns.")
11618 (defun org-table-align ()
11619 "Align the table at point by aligning all vertical bars."
11620 (interactive)
11621 (let* (
11622 ;; Limits of table
11623 (beg (org-table-begin))
11624 (end (org-table-end))
11625 ;; Current cursor position
11626 (linepos (org-current-line))
11627 (colpos (org-table-current-column))
11628 (winstart (window-start))
11629 (winstartline (org-current-line (min winstart (1- (point-max)))))
11630 lines (new "") lengths l typenums ty fields maxfields i
11631 column
11632 (indent "") cnt frac
11633 rfmt hfmt
11634 (spaces '(1 . 1))
11635 (sp1 (car spaces))
11636 (sp2 (cdr spaces))
11637 (rfmt1 (concat
11638 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
11639 (hfmt1 (concat
11640 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
11641 emptystrings links dates narrow fmax f1 len c e)
11642 (untabify beg end)
11643 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
11644 ;; Check if we have links or dates
11645 (goto-char beg)
11646 (setq links (re-search-forward org-bracket-link-regexp end t))
11647 (goto-char beg)
11648 (setq dates (and org-display-custom-times
11649 (re-search-forward org-ts-regexp-both end t)))
11650 ;; Make sure the link properties are right
11651 (when links (goto-char beg) (while (org-activate-bracket-links end)))
11652 ;; Make sure the date properties are right
11653 (when dates (goto-char beg) (while (org-activate-dates end)))
11655 ;; Check if we are narrowing any columns
11656 (goto-char beg)
11657 (setq narrow (and org-format-transports-properties-p
11658 (re-search-forward "<[0-9]+>" end t)))
11659 ;; Get the rows
11660 (setq lines (org-split-string
11661 (buffer-substring beg end) "\n"))
11662 ;; Store the indentation of the first line
11663 (if (string-match "^ *" (car lines))
11664 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11665 ;; Mark the hlines by setting the corresponding element to nil
11666 ;; At the same time, we remove trailing space.
11667 (setq lines (mapcar (lambda (l)
11668 (if (string-match "^ *|-" l)
11670 (if (string-match "[ \t]+$" l)
11671 (substring l 0 (match-beginning 0))
11672 l)))
11673 lines))
11674 ;; Get the data fields by splitting the lines.
11675 (setq fields (mapcar
11676 (lambda (l)
11677 (org-split-string l " *| *"))
11678 (delq nil (copy-sequence lines))))
11679 ;; How many fields in the longest line?
11680 (condition-case nil
11681 (setq maxfields (apply 'max (mapcar 'length fields)))
11682 (error
11683 (kill-region beg end)
11684 (org-table-create org-table-default-size)
11685 (error "Empty table - created default table")))
11686 ;; A list of empty strings to fill any short rows on output
11687 (setq emptystrings (make-list maxfields ""))
11688 ;; Check for special formatting.
11689 (setq i -1)
11690 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
11691 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
11692 ;; Check if there is an explicit width specified
11693 (when (and org-table-limit-column-width narrow)
11694 (setq c column fmax nil)
11695 (while c
11696 (setq e (pop c))
11697 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
11698 (setq fmax (string-to-number (match-string 1 e)) c nil)))
11699 ;; Find fields that are wider than fmax, and shorten them
11700 (when fmax
11701 (loop for xx in column do
11702 (when (and (stringp xx)
11703 (> (org-string-width xx) fmax))
11704 (org-add-props xx nil
11705 'help-echo
11706 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
11707 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
11708 (unless (> f1 1)
11709 (error "Cannot narrow field starting with wide link \"%s\""
11710 (match-string 0 xx)))
11711 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
11712 (add-text-properties (- f1 2) f1
11713 (list 'display org-narrow-column-arrow)
11714 xx)))))
11715 ;; Get the maximum width for each column
11716 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
11717 ;; Get the fraction of numbers, to decide about alignment of the column
11718 (setq cnt 0 frac 0.0)
11719 (loop for x in column do
11720 (if (equal x "")
11722 (setq frac ( / (+ (* frac cnt)
11723 (if (string-match org-table-number-regexp x) 1 0))
11724 (setq cnt (1+ cnt))))))
11725 (push (>= frac org-table-number-fraction) typenums))
11726 (setq lengths (nreverse lengths) typenums (nreverse typenums))
11728 ;; Store the alignment of this table, for later editing of single fields
11729 (setq org-table-last-alignment typenums
11730 org-table-last-column-widths lengths)
11732 ;; With invisible characters, `format' does not get the field width right
11733 ;; So we need to make these fields wide by hand.
11734 (when links
11735 (loop for i from 0 upto (1- maxfields) do
11736 (setq len (nth i lengths))
11737 (loop for j from 0 upto (1- (length fields)) do
11738 (setq c (nthcdr i (car (nthcdr j fields))))
11739 (if (and (stringp (car c))
11740 (string-match org-bracket-link-regexp (car c))
11741 (< (org-string-width (car c)) len))
11742 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
11744 ;; Compute the formats needed for output of the table
11745 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
11746 (while (setq l (pop lengths))
11747 (setq ty (if (pop typenums) "" "-")) ; number types flushright
11748 (setq rfmt (concat rfmt (format rfmt1 ty l))
11749 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
11750 (setq rfmt (concat rfmt "\n")
11751 hfmt (concat (substring hfmt 0 -1) "|\n"))
11753 (setq new (mapconcat
11754 (lambda (l)
11755 (if l (apply 'format rfmt
11756 (append (pop fields) emptystrings))
11757 hfmt))
11758 lines ""))
11759 ;; Replace the old one
11760 (delete-region beg end)
11761 (move-marker end nil)
11762 (move-marker org-table-aligned-begin-marker (point))
11763 (insert new)
11764 (move-marker org-table-aligned-end-marker (point))
11765 (when (and orgtbl-mode (not (org-mode-p)))
11766 (goto-char org-table-aligned-begin-marker)
11767 (while (org-hide-wide-columns org-table-aligned-end-marker)))
11768 ;; Try to move to the old location
11769 (goto-line winstartline)
11770 (setq winstart (point-at-bol))
11771 (goto-line linepos)
11772 (set-window-start (selected-window) winstart 'noforce)
11773 (org-table-goto-column colpos)
11774 (setq org-table-may-need-update nil)
11777 (defun org-string-width (s)
11778 "Compute width of string, ignoring invisible characters.
11779 This ignores character with invisibility property `org-link', and also
11780 characters with property `org-cwidth', because these will become invisible
11781 upon the next fontification round."
11782 (let (b l)
11783 (when (or (eq t buffer-invisibility-spec)
11784 (assq 'org-link buffer-invisibility-spec))
11785 (while (setq b (text-property-any 0 (length s)
11786 'invisible 'org-link s))
11787 (setq s (concat (substring s 0 b)
11788 (substring s (or (next-single-property-change
11789 b 'invisible s) (length s)))))))
11790 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
11791 (setq s (concat (substring s 0 b)
11792 (substring s (or (next-single-property-change
11793 b 'org-cwidth s) (length s))))))
11794 (setq l (string-width s) b -1)
11795 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
11796 (setq l (- l (get-text-property b 'org-dwidth-n s))))
11799 (defun org-table-begin (&optional table-type)
11800 "Find the beginning of the table and return its position.
11801 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
11802 (save-excursion
11803 (if (not (re-search-backward
11804 (if table-type org-table-any-border-regexp
11805 org-table-border-regexp)
11806 nil t))
11807 (progn (goto-char (point-min)) (point))
11808 (goto-char (match-beginning 0))
11809 (beginning-of-line 2)
11810 (point))))
11812 (defun org-table-end (&optional table-type)
11813 "Find the end of the table and return its position.
11814 With argument TABLE-TYPE, go to the end of a table.el-type table."
11815 (save-excursion
11816 (if (not (re-search-forward
11817 (if table-type org-table-any-border-regexp
11818 org-table-border-regexp)
11819 nil t))
11820 (goto-char (point-max))
11821 (goto-char (match-beginning 0)))
11822 (point-marker)))
11824 (defun org-table-justify-field-maybe (&optional new)
11825 "Justify the current field, text to left, number to right.
11826 Optional argument NEW may specify text to replace the current field content."
11827 (cond
11828 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
11829 ((org-at-table-hline-p))
11830 ((and (not new)
11831 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
11832 (current-buffer)))
11833 (< (point) org-table-aligned-begin-marker)
11834 (>= (point) org-table-aligned-end-marker)))
11835 ;; This is not the same table, force a full re-align
11836 (setq org-table-may-need-update t))
11837 (t ;; realign the current field, based on previous full realign
11838 (let* ((pos (point)) s
11839 (col (org-table-current-column))
11840 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
11841 l f n o e)
11842 (when (> col 0)
11843 (skip-chars-backward "^|\n")
11844 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
11845 (progn
11846 (setq s (match-string 1)
11847 o (match-string 0)
11848 l (max 1 (- (match-end 0) (match-beginning 0) 3))
11849 e (not (= (match-beginning 2) (match-end 2))))
11850 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
11851 l (if e "|" (setq org-table-may-need-update t) ""))
11852 n (format f s))
11853 (if new
11854 (if (<= (length new) l) ;; FIXME: length -> str-width?
11855 (setq n (format f new))
11856 (setq n (concat new "|") org-table-may-need-update t)))
11857 (or (equal n o)
11858 (let (org-table-may-need-update)
11859 (replace-match n))))
11860 (setq org-table-may-need-update t))
11861 (goto-char pos))))))
11863 (defun org-table-next-field ()
11864 "Go to the next field in the current table, creating new lines as needed.
11865 Before doing so, re-align the table if necessary."
11866 (interactive)
11867 (org-table-maybe-eval-formula)
11868 (org-table-maybe-recalculate-line)
11869 (if (and org-table-automatic-realign
11870 org-table-may-need-update)
11871 (org-table-align))
11872 (let ((end (org-table-end)))
11873 (if (org-at-table-hline-p)
11874 (end-of-line 1))
11875 (condition-case nil
11876 (progn
11877 (re-search-forward "|" end)
11878 (if (looking-at "[ \t]*$")
11879 (re-search-forward "|" end))
11880 (if (and (looking-at "-")
11881 org-table-tab-jumps-over-hlines
11882 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
11883 (goto-char (match-beginning 1)))
11884 (if (looking-at "-")
11885 (progn
11886 (beginning-of-line 0)
11887 (org-table-insert-row 'below))
11888 (if (looking-at " ") (forward-char 1))))
11889 (error
11890 (org-table-insert-row 'below)))))
11892 (defun org-table-previous-field ()
11893 "Go to the previous field in the table.
11894 Before doing so, re-align the table if necessary."
11895 (interactive)
11896 (org-table-justify-field-maybe)
11897 (org-table-maybe-recalculate-line)
11898 (if (and org-table-automatic-realign
11899 org-table-may-need-update)
11900 (org-table-align))
11901 (if (org-at-table-hline-p)
11902 (end-of-line 1))
11903 (re-search-backward "|" (org-table-begin))
11904 (re-search-backward "|" (org-table-begin))
11905 (while (looking-at "|\\(-\\|[ \t]*$\\)")
11906 (re-search-backward "|" (org-table-begin)))
11907 (if (looking-at "| ?")
11908 (goto-char (match-end 0))))
11910 (defun org-table-next-row ()
11911 "Go to the next row (same column) in the current table.
11912 Before doing so, re-align the table if necessary."
11913 (interactive)
11914 (org-table-maybe-eval-formula)
11915 (org-table-maybe-recalculate-line)
11916 (if (or (looking-at "[ \t]*$")
11917 (save-excursion (skip-chars-backward " \t") (bolp)))
11918 (newline)
11919 (if (and org-table-automatic-realign
11920 org-table-may-need-update)
11921 (org-table-align))
11922 (let ((col (org-table-current-column)))
11923 (beginning-of-line 2)
11924 (if (or (not (org-at-table-p))
11925 (org-at-table-hline-p))
11926 (progn
11927 (beginning-of-line 0)
11928 (org-table-insert-row 'below)))
11929 (org-table-goto-column col)
11930 (skip-chars-backward "^|\n\r")
11931 (if (looking-at " ") (forward-char 1)))))
11933 (defun org-table-copy-down (n)
11934 "Copy a field down in the current column.
11935 If the field at the cursor is empty, copy into it the content of the nearest
11936 non-empty field above. With argument N, use the Nth non-empty field.
11937 If the current field is not empty, it is copied down to the next row, and
11938 the cursor is moved with it. Therefore, repeating this command causes the
11939 column to be filled row-by-row.
11940 If the variable `org-table-copy-increment' is non-nil and the field is an
11941 integer, it will be incremented while copying."
11942 (interactive "p")
11943 (let* ((colpos (org-table-current-column))
11944 (field (org-table-get-field))
11945 (non-empty (string-match "[^ \t]" field))
11946 (beg (org-table-begin))
11947 txt)
11948 (org-table-check-inside-data-field)
11949 (if non-empty
11950 (progn
11951 (setq txt (org-trim field))
11952 (org-table-next-row)
11953 (org-table-blank-field))
11954 (save-excursion
11955 (setq txt
11956 (catch 'exit
11957 (while (progn (beginning-of-line 1)
11958 (re-search-backward org-table-dataline-regexp
11959 beg t))
11960 (org-table-goto-column colpos t)
11961 (if (and (looking-at
11962 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11963 (= (setq n (1- n)) 0))
11964 (throw 'exit (match-string 1))))))))
11965 (if txt
11966 (progn
11967 (if (and org-table-copy-increment
11968 (string-match "^[0-9]+$" txt))
11969 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11970 (insert txt)
11971 (org-table-maybe-recalculate-line)
11972 (org-table-align))
11973 (error "No non-empty field found"))))
11975 (defun org-table-check-inside-data-field ()
11976 "Is point inside a table data field?
11977 I.e. not on a hline or before the first or after the last column?
11978 This actually throws an error, so it aborts the current command."
11979 (if (or (not (org-at-table-p))
11980 (= (org-table-current-column) 0)
11981 (org-at-table-hline-p)
11982 (looking-at "[ \t]*$"))
11983 (error "Not in table data field")))
11985 (defvar org-table-clip nil
11986 "Clipboard for table regions.")
11988 (defun org-table-blank-field ()
11989 "Blank the current table field or active region."
11990 (interactive)
11991 (org-table-check-inside-data-field)
11992 (if (and (interactive-p) (org-region-active-p))
11993 (let (org-table-clip)
11994 (org-table-cut-region (region-beginning) (region-end)))
11995 (skip-chars-backward "^|")
11996 (backward-char 1)
11997 (if (looking-at "|[^|\n]+")
11998 (let* ((pos (match-beginning 0))
11999 (match (match-string 0))
12000 (len (org-string-width match)))
12001 (replace-match (concat "|" (make-string (1- len) ?\ )))
12002 (goto-char (+ 2 pos))
12003 (substring match 1)))))
12005 (defun org-table-get-field (&optional n replace)
12006 "Return the value of the field in column N of current row.
12007 N defaults to current field.
12008 If REPLACE is a string, replace field with this value. The return value
12009 is always the old value."
12010 (and n (org-table-goto-column n))
12011 (skip-chars-backward "^|\n")
12012 (backward-char 1)
12013 (if (looking-at "|[^|\r\n]*")
12014 (let* ((pos (match-beginning 0))
12015 (val (buffer-substring (1+ pos) (match-end 0))))
12016 (if replace
12017 (replace-match (concat "|" replace)))
12018 (goto-char (min (point-at-eol) (+ 2 pos)))
12019 val)
12020 (forward-char 1) ""))
12022 (defun org-table-current-column ()
12023 "Find out which column we are in.
12024 When called interactively, column is also displayed in echo area."
12025 (interactive)
12026 (if (interactive-p) (org-table-check-inside-data-field))
12027 (save-excursion
12028 (let ((cnt 0) (pos (point)))
12029 (beginning-of-line 1)
12030 (while (search-forward "|" pos t)
12031 (setq cnt (1+ cnt)))
12032 (if (interactive-p) (message "This is table column %d" cnt))
12033 cnt)))
12035 (defun org-table-goto-column (n &optional on-delim force)
12036 "Move the cursor to the Nth column in the current table line.
12037 With optional argument ON-DELIM, stop with point before the left delimiter
12038 of the field.
12039 If there are less than N fields, just go to after the last delimiter.
12040 However, when FORCE is non-nil, create new columns if necessary."
12041 (interactive "p")
12042 (let ((pos (point-at-eol)))
12043 (beginning-of-line 1)
12044 (when (> n 0)
12045 (while (and (> (setq n (1- n)) -1)
12046 (or (search-forward "|" pos t)
12047 (and force
12048 (progn (end-of-line 1)
12049 (skip-chars-backward "^|")
12050 (insert " | "))))))
12051 ; (backward-char 2) t)))))
12052 (when (and force (not (looking-at ".*|")))
12053 (save-excursion (end-of-line 1) (insert " | ")))
12054 (if on-delim
12055 (backward-char 1)
12056 (if (looking-at " ") (forward-char 1))))))
12058 (defun org-at-table-p (&optional table-type)
12059 "Return t if the cursor is inside an org-type table.
12060 If TABLE-TYPE is non-nil, also check for table.el-type tables."
12061 (if org-enable-table-editor
12062 (save-excursion
12063 (beginning-of-line 1)
12064 (looking-at (if table-type org-table-any-line-regexp
12065 org-table-line-regexp)))
12066 nil))
12068 (defun org-at-table.el-p ()
12069 "Return t if and only if we are at a table.el table."
12070 (and (org-at-table-p 'any)
12071 (save-excursion
12072 (goto-char (org-table-begin 'any))
12073 (looking-at org-table1-hline-regexp))))
12075 (defun org-table-recognize-table.el ()
12076 "If there is a table.el table nearby, recognize it and move into it."
12077 (if org-table-tab-recognizes-table.el
12078 (if (org-at-table.el-p)
12079 (progn
12080 (beginning-of-line 1)
12081 (if (looking-at org-table-dataline-regexp)
12083 (if (looking-at org-table1-hline-regexp)
12084 (progn
12085 (beginning-of-line 2)
12086 (if (looking-at org-table-any-border-regexp)
12087 (beginning-of-line -1)))))
12088 (if (re-search-forward "|" (org-table-end t) t)
12089 (progn
12090 (require 'table)
12091 (if (table--at-cell-p (point))
12093 (message "recognizing table.el table...")
12094 (table-recognize-table)
12095 (message "recognizing table.el table...done")))
12096 (error "This should not happen..."))
12098 nil)
12099 nil))
12101 (defun org-at-table-hline-p ()
12102 "Return t if the cursor is inside a hline in a table."
12103 (if org-enable-table-editor
12104 (save-excursion
12105 (beginning-of-line 1)
12106 (looking-at org-table-hline-regexp))
12107 nil))
12109 (defun org-table-insert-column ()
12110 "Insert a new column into the table."
12111 (interactive)
12112 (if (not (org-at-table-p))
12113 (error "Not at a table"))
12114 (org-table-find-dataline)
12115 (let* ((col (max 1 (org-table-current-column)))
12116 (beg (org-table-begin))
12117 (end (org-table-end))
12118 ;; Current cursor position
12119 (linepos (org-current-line))
12120 (colpos col))
12121 (goto-char beg)
12122 (while (< (point) end)
12123 (if (org-at-table-hline-p)
12125 (org-table-goto-column col t)
12126 (insert "| "))
12127 (beginning-of-line 2))
12128 (move-marker end nil)
12129 (goto-line linepos)
12130 (org-table-goto-column colpos)
12131 (org-table-align)
12132 (org-table-modify-formulas 'insert col)))
12134 (defun org-table-find-dataline ()
12135 "Find a dataline in the current table, which is needed for column commands."
12136 (if (and (org-at-table-p)
12137 (not (org-at-table-hline-p)))
12139 (let ((col (current-column))
12140 (end (org-table-end)))
12141 (move-to-column col)
12142 (while (and (< (point) end)
12143 (or (not (= (current-column) col))
12144 (org-at-table-hline-p)))
12145 (beginning-of-line 2)
12146 (move-to-column col))
12147 (if (and (org-at-table-p)
12148 (not (org-at-table-hline-p)))
12150 (error
12151 "Please position cursor in a data line for column operations")))))
12153 (defun org-table-delete-column ()
12154 "Delete a column from the table."
12155 (interactive)
12156 (if (not (org-at-table-p))
12157 (error "Not at a table"))
12158 (org-table-find-dataline)
12159 (org-table-check-inside-data-field)
12160 (let* ((col (org-table-current-column))
12161 (beg (org-table-begin))
12162 (end (org-table-end))
12163 ;; Current cursor position
12164 (linepos (org-current-line))
12165 (colpos col))
12166 (goto-char beg)
12167 (while (< (point) end)
12168 (if (org-at-table-hline-p)
12170 (org-table-goto-column col t)
12171 (and (looking-at "|[^|\n]+|")
12172 (replace-match "|")))
12173 (beginning-of-line 2))
12174 (move-marker end nil)
12175 (goto-line linepos)
12176 (org-table-goto-column colpos)
12177 (org-table-align)
12178 (org-table-modify-formulas 'remove col)))
12180 (defun org-table-move-column-right ()
12181 "Move column to the right."
12182 (interactive)
12183 (org-table-move-column nil))
12184 (defun org-table-move-column-left ()
12185 "Move column to the left."
12186 (interactive)
12187 (org-table-move-column 'left))
12189 (defun org-table-move-column (&optional left)
12190 "Move the current column to the right. With arg LEFT, move to the left."
12191 (interactive "P")
12192 (if (not (org-at-table-p))
12193 (error "Not at a table"))
12194 (org-table-find-dataline)
12195 (org-table-check-inside-data-field)
12196 (let* ((col (org-table-current-column))
12197 (col1 (if left (1- col) col))
12198 (beg (org-table-begin))
12199 (end (org-table-end))
12200 ;; Current cursor position
12201 (linepos (org-current-line))
12202 (colpos (if left (1- col) (1+ col))))
12203 (if (and left (= col 1))
12204 (error "Cannot move column further left"))
12205 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
12206 (error "Cannot move column further right"))
12207 (goto-char beg)
12208 (while (< (point) end)
12209 (if (org-at-table-hline-p)
12211 (org-table-goto-column col1 t)
12212 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
12213 (replace-match "|\\2|\\1|")))
12214 (beginning-of-line 2))
12215 (move-marker end nil)
12216 (goto-line linepos)
12217 (org-table-goto-column colpos)
12218 (org-table-align)
12219 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
12221 (defun org-table-move-row-down ()
12222 "Move table row down."
12223 (interactive)
12224 (org-table-move-row nil))
12225 (defun org-table-move-row-up ()
12226 "Move table row up."
12227 (interactive)
12228 (org-table-move-row 'up))
12230 (defun org-table-move-row (&optional up)
12231 "Move the current table line down. With arg UP, move it up."
12232 (interactive "P")
12233 (let ((col (current-column))
12234 (pos (point))
12235 (tonew (if up 0 2))
12236 txt)
12237 (beginning-of-line tonew)
12238 (if (not (org-at-table-p))
12239 (progn
12240 (goto-char pos)
12241 (error "Cannot move row further")))
12242 (goto-char pos)
12243 (beginning-of-line 1)
12244 (setq pos (point))
12245 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
12246 (delete-region (point) (1+ (point-at-eol)))
12247 (beginning-of-line tonew)
12248 (insert txt)
12249 (beginning-of-line 0)
12250 (move-to-column col)))
12252 (defun org-table-insert-row (&optional arg)
12253 "Insert a new row above the current line into the table.
12254 With prefix ARG, insert below the current line."
12255 (interactive "P")
12256 (if (not (org-at-table-p))
12257 (error "Not at a table"))
12258 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
12259 (new (org-table-clean-line line)))
12260 ;; Fix the first field if necessary
12261 (if (string-match "^[ \t]*| *[#$] *|" line)
12262 (setq new (replace-match (match-string 0 line) t t new)))
12263 (beginning-of-line (if arg 2 1))
12264 (let (org-table-may-need-update) (insert-before-markers new "\n"))
12265 (beginning-of-line 0)
12266 (re-search-forward "| ?" (point-at-eol) t)
12267 (and org-table-may-need-update (org-table-align))))
12269 (defun org-table-insert-hline (&optional arg)
12270 "Insert a horizontal-line below the current line into the table.
12271 With prefix ARG, insert above the current line."
12272 (interactive "P")
12273 (if (not (org-at-table-p))
12274 (error "Not at a table"))
12275 (let ((line (org-table-clean-line
12276 (buffer-substring (point-at-bol) (point-at-eol))))
12277 (col (current-column)))
12278 (while (string-match "|\\( +\\)|" line)
12279 (setq line (replace-match
12280 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
12281 ?-) "|") t t line)))
12282 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
12283 (beginning-of-line (if arg 1 2))
12284 (insert line "\n")
12285 (beginning-of-line (if arg 1 -1))
12286 (move-to-column col)))
12288 (defun org-table-clean-line (s)
12289 "Convert a table line S into a string with only \"|\" and space.
12290 In particular, this does handle wide and invisible characters."
12291 (if (string-match "^[ \t]*|-" s)
12292 ;; It's a hline, just map the characters
12293 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
12294 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
12295 (setq s (replace-match
12296 (concat "|" (make-string (org-string-width (match-string 1 s))
12297 ?\ ) "|")
12298 t t s)))
12301 (defun org-table-kill-row ()
12302 "Delete the current row or horizontal line from the table."
12303 (interactive)
12304 (if (not (org-at-table-p))
12305 (error "Not at a table"))
12306 (let ((col (current-column)))
12307 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
12308 (if (not (org-at-table-p)) (beginning-of-line 0))
12309 (move-to-column col)))
12311 (defun org-table-sort-lines (beg end numericp)
12312 "Sort table lines in region.
12313 Point and mark define the first and last line to include. Both point and
12314 mark should be in the column that is used for sorting. For example, to
12315 sort according to column 3, put the mark in the first line to sort, in
12316 table column 3. Put point into the last line to be included in the sorting,
12317 also in table column 3. The command will prompt for the sorting method
12318 \(n for numerical, a for alphanumeric)."
12319 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
12320 (setq numericp (string-match "[nN]" numericp))
12321 (org-table-align) ;; Just to be safe
12322 (let* (bcol ecol cmp column lns)
12323 (goto-char beg)
12324 (org-table-check-inside-data-field)
12325 (setq column (org-table-current-column)
12326 beg (move-marker (make-marker) (point-at-bol)))
12327 (goto-char end)
12328 (org-table-check-inside-data-field)
12329 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
12330 (untabify beg end)
12331 (goto-char beg)
12332 (org-table-goto-column column)
12333 (skip-chars-backward "^|")
12334 (setq bcol (current-column))
12335 (org-table-goto-column (1+ column))
12336 (skip-chars-backward "^|")
12337 (setq ecol (1- (current-column)))
12338 (setq cmp (if numericp
12339 (lambda (a b) (< (car a) (car b)))
12340 (lambda (a b) (string< (car a) (car b)))))
12341 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
12342 (org-split-string (buffer-substring beg end) "\n")))
12343 (if numericp
12344 (setq lns (mapcar (lambda(x)
12345 (cons (string-to-number (car x)) (cdr x)))
12346 lns)))
12347 (delete-region beg end)
12348 (move-marker beg nil)
12349 (move-marker end nil)
12350 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
12351 (message "%d lines sorted %s based on column %d"
12352 (length lns)
12353 (if numericp "numerically" "alphabetically") column)))
12355 (defun org-table-cut-region (beg end)
12356 "Copy region in table to the clipboard and blank all relevant fields."
12357 (interactive "r")
12358 (org-table-copy-region beg end 'cut))
12360 (defun org-table-copy-region (beg end &optional cut)
12361 "Copy rectangular region in table to clipboard.
12362 A special clipboard is used which can only be accessed
12363 with `org-table-paste-rectangle'."
12364 (interactive "rP")
12365 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
12366 region cols
12367 (rpl (if cut " " nil)))
12368 (goto-char beg)
12369 (org-table-check-inside-data-field)
12370 (setq l01 (count-lines (point-min) (point))
12371 c01 (org-table-current-column))
12372 (goto-char end)
12373 (org-table-check-inside-data-field)
12374 (setq l02 (count-lines (point-min) (point))
12375 c02 (org-table-current-column))
12376 (setq l1 (min l01 l02) l2 (max l01 l02)
12377 c1 (min c01 c02) c2 (max c01 c02))
12378 (catch 'exit
12379 (while t
12380 (catch 'nextline
12381 (if (> l1 l2) (throw 'exit t))
12382 (goto-line l1)
12383 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
12384 (setq cols nil ic1 c1 ic2 c2)
12385 (while (< ic1 (1+ ic2))
12386 (push (org-table-get-field ic1 rpl) cols)
12387 (setq ic1 (1+ ic1)))
12388 (push (nreverse cols) region)
12389 (setq l1 (1+ l1)))))
12390 (setq org-table-clip (nreverse region))
12391 (if cut (org-table-align))
12392 org-table-clip))
12394 (defun org-table-paste-rectangle ()
12395 "Paste a rectangular region into a table.
12396 The upper right corner ends up in the current field. All involved fields
12397 will be overwritten. If the rectangle does not fit into the present table,
12398 the table is enlarged as needed. The process ignores horizontal separator
12399 lines."
12400 (interactive)
12401 (unless (and org-table-clip (listp org-table-clip))
12402 (error "First cut/copy a region to paste!"))
12403 (org-table-check-inside-data-field)
12404 (let* ((clip org-table-clip)
12405 (line (count-lines (point-min) (point)))
12406 (col (org-table-current-column))
12407 (org-enable-table-editor t)
12408 (org-table-automatic-realign nil)
12409 c cols field)
12410 (while (setq cols (pop clip))
12411 (while (org-at-table-hline-p) (beginning-of-line 2))
12412 (if (not (org-at-table-p))
12413 (progn (end-of-line 0) (org-table-next-field)))
12414 (setq c col)
12415 (while (setq field (pop cols))
12416 (org-table-goto-column c nil 'force)
12417 (org-table-get-field nil field)
12418 (setq c (1+ c)))
12419 (beginning-of-line 2))
12420 (goto-line line)
12421 (org-table-goto-column col)
12422 (org-table-align)))
12424 (defun org-table-convert ()
12425 "Convert from `org-mode' table to table.el and back.
12426 Obviously, this only works within limits. When an Org-mode table is
12427 converted to table.el, all horizontal separator lines get lost, because
12428 table.el uses these as cell boundaries and has no notion of horizontal lines.
12429 A table.el table can be converted to an Org-mode table only if it does not
12430 do row or column spanning. Multiline cells will become multiple cells.
12431 Beware, Org-mode does not test if the table can be successfully converted - it
12432 blindly applies a recipe that works for simple tables."
12433 (interactive)
12434 (require 'table)
12435 (if (org-at-table.el-p)
12436 ;; convert to Org-mode table
12437 (let ((beg (move-marker (make-marker) (org-table-begin t)))
12438 (end (move-marker (make-marker) (org-table-end t))))
12439 (table-unrecognize-region beg end)
12440 (goto-char beg)
12441 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
12442 (replace-match ""))
12443 (goto-char beg))
12444 (if (org-at-table-p)
12445 ;; convert to table.el table
12446 (let ((beg (move-marker (make-marker) (org-table-begin)))
12447 (end (move-marker (make-marker) (org-table-end))))
12448 ;; first, get rid of all horizontal lines
12449 (goto-char beg)
12450 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
12451 (replace-match ""))
12452 ;; insert a hline before first
12453 (goto-char beg)
12454 (org-table-insert-hline 'above)
12455 (beginning-of-line -1)
12456 ;; insert a hline after each line
12457 (while (progn (beginning-of-line 3) (< (point) end))
12458 (org-table-insert-hline))
12459 (goto-char beg)
12460 (setq end (move-marker end (org-table-end)))
12461 ;; replace "+" at beginning and ending of hlines
12462 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
12463 (replace-match "\\1+-"))
12464 (goto-char beg)
12465 (while (re-search-forward "-|[ \t]*$" end t)
12466 (replace-match "-+"))
12467 (goto-char beg)))))
12469 (defun org-table-wrap-region (arg)
12470 "Wrap several fields in a column like a paragraph.
12471 This is useful if you'd like to spread the contents of a field over several
12472 lines, in order to keep the table compact.
12474 If there is an active region, and both point and mark are in the same column,
12475 the text in the column is wrapped to minimum width for the given number of
12476 lines. Generally, this makes the table more compact. A prefix ARG may be
12477 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
12478 formats the selected text to two lines. If the region was longer than two
12479 lines, the remaining lines remain empty. A negative prefix argument reduces
12480 the current number of lines by that amount. The wrapped text is pasted back
12481 into the table. If you formatted it to more lines than it was before, fields
12482 further down in the table get overwritten - so you might need to make space in
12483 the table first.
12485 If there is no region, the current field is split at the cursor position and
12486 the text fragment to the right of the cursor is prepended to the field one
12487 line down.
12489 If there is no region, but you specify a prefix ARG, the current field gets
12490 blank, and the content is appended to the field above."
12491 (interactive "P")
12492 (org-table-check-inside-data-field)
12493 (if (org-region-active-p)
12494 ;; There is a region: fill as a paragraph
12495 (let ((beg (region-beginning))
12496 nlines)
12497 (org-table-cut-region (region-beginning) (region-end))
12498 (if (> (length (car org-table-clip)) 1)
12499 (error "Region must be limited to single column"))
12500 (setq nlines (if arg
12501 (if (< arg 1)
12502 (+ (length org-table-clip) arg)
12503 arg)
12504 (length org-table-clip)))
12505 (setq org-table-clip
12506 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
12507 nil nlines)))
12508 (goto-char beg)
12509 (org-table-paste-rectangle))
12510 ;; No region, split the current field at point
12511 (if arg
12512 ;; combine with field above
12513 (let ((s (org-table-blank-field))
12514 (col (org-table-current-column)))
12515 (beginning-of-line 0)
12516 (while (org-at-table-hline-p) (beginning-of-line 0))
12517 (org-table-goto-column col)
12518 (skip-chars-forward "^|")
12519 (skip-chars-backward " ")
12520 (insert " " (org-trim s))
12521 (org-table-align))
12522 ;; split field
12523 (when (looking-at "\\([^|]+\\)+|")
12524 (let ((s (match-string 1)))
12525 (replace-match " |")
12526 (goto-char (match-beginning 0))
12527 (org-table-next-row)
12528 (insert (org-trim s) " ")
12529 (org-table-align))))))
12531 (defvar org-field-marker nil)
12533 (defun org-table-edit-field (arg)
12534 "Edit table field in a different window.
12535 This is mainly useful for fields that contain hidden parts.
12536 When called with a \\[universal-argument] prefix, just make the full field visible so that
12537 it can be edited in place."
12538 (interactive "P")
12539 (if arg
12540 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
12541 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
12542 (remove-text-properties b e '(org-cwidth t invisible t
12543 display t intangible t))
12544 (if (and (boundp 'font-lock-mode) font-lock-mode)
12545 (font-lock-fontify-block)))
12546 (let ((pos (move-marker (make-marker) (point)))
12547 (field (org-table-get-field))
12548 (cw (current-window-configuration))
12550 (switch-to-buffer-other-window "*Org tmp*")
12551 (erase-buffer)
12552 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
12553 (org-mode)
12554 (goto-char (setq p (point-max)))
12555 (insert (org-trim field))
12556 (remove-text-properties p (point-max)
12557 '(invisible t org-cwidth t display t
12558 intangible t))
12559 (goto-char p)
12560 (org-set-local 'org-finish-function
12561 'org-table-finish-edit-field)
12562 (org-set-local 'org-window-configuration cw)
12563 (org-set-local 'org-field-marker pos)
12564 (message "Edit and finish with C-c C-c"))))
12566 (defun org-table-finish-edit-field ()
12567 "Finish editing a table data field.
12568 Remove all newline characters, insert the result into the table, realign
12569 the table and kill the editing buffer."
12570 (let ((pos org-field-marker)
12571 (cw org-window-configuration)
12572 (cb (current-buffer))
12573 text)
12574 (goto-char (point-min))
12575 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
12576 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
12577 (replace-match " "))
12578 (setq text (org-trim (buffer-string)))
12579 (set-window-configuration cw)
12580 (kill-buffer cb)
12581 (select-window (get-buffer-window (marker-buffer pos)))
12582 (goto-char pos)
12583 (move-marker pos nil)
12584 (org-table-check-inside-data-field)
12585 (org-table-get-field nil text)
12586 (org-table-align)
12587 (message "New field value inserted")))
12589 (defun org-trim (s)
12590 "Remove whitespace at beginning and end of string."
12591 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
12592 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
12595 (defun org-wrap (string &optional width lines)
12596 "Wrap string to either a number of lines, or a width in characters.
12597 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12598 that costs. If there is a word longer than WIDTH, the text is actually
12599 wrapped to the length of that word.
12600 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12601 many lines, whatever width that takes.
12602 The return value is a list of lines, without newlines at the end."
12603 (let* ((words (org-split-string string "[ \t\n]+"))
12604 (maxword (apply 'max (mapcar 'org-string-width words)))
12605 w ll)
12606 (cond (width
12607 (org-do-wrap words (max maxword width)))
12608 (lines
12609 (setq w maxword)
12610 (setq ll (org-do-wrap words maxword))
12611 (if (<= (length ll) lines)
12613 (setq ll words)
12614 (while (> (length ll) lines)
12615 (setq w (1+ w))
12616 (setq ll (org-do-wrap words w)))
12617 ll))
12618 (t (error "Cannot wrap this")))))
12621 (defun org-do-wrap (words width)
12622 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12623 (let (lines line)
12624 (while words
12625 (setq line (pop words))
12626 (while (and words (< (+ (length line) (length (car words))) width))
12627 (setq line (concat line " " (pop words))))
12628 (setq lines (push line lines)))
12629 (nreverse lines)))
12631 (defun org-split-string (string &optional separators)
12632 "Splits STRING into substrings at SEPARATORS.
12633 No empty strings are returned if there are matches at the beginning
12634 and end of string."
12635 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12636 (start 0)
12637 notfirst
12638 (list nil))
12639 (while (and (string-match rexp string
12640 (if (and notfirst
12641 (= start (match-beginning 0))
12642 (< start (length string)))
12643 (1+ start) start))
12644 (< (match-beginning 0) (length string)))
12645 (setq notfirst t)
12646 (or (eq (match-beginning 0) 0)
12647 (and (eq (match-beginning 0) (match-end 0))
12648 (eq (match-beginning 0) start))
12649 (setq list
12650 (cons (substring string start (match-beginning 0))
12651 list)))
12652 (setq start (match-end 0)))
12653 (or (eq start (length string))
12654 (setq list
12655 (cons (substring string start)
12656 list)))
12657 (nreverse list)))
12659 (defun org-table-map-tables (function)
12660 "Apply FUNCTION to the start of all tables in the buffer."
12661 (save-excursion
12662 (save-restriction
12663 (widen)
12664 (goto-char (point-min))
12665 (while (re-search-forward org-table-any-line-regexp nil t)
12666 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
12667 (beginning-of-line 1)
12668 (if (looking-at org-table-line-regexp)
12669 (save-excursion (funcall function)))
12670 (re-search-forward org-table-any-border-regexp nil 1))))
12671 (message "Mapping tables: done"))
12673 (defun org-table-sum (&optional beg end nlast)
12674 "Sum numbers in region of current table column.
12675 The result will be displayed in the echo area, and will be available
12676 as kill to be inserted with \\[yank].
12678 If there is an active region, it is interpreted as a rectangle and all
12679 numbers in that rectangle will be summed. If there is no active
12680 region and point is located in a table column, sum all numbers in that
12681 column.
12683 If at least one number looks like a time HH:MM or HH:MM:SS, all other
12684 numbers are assumed to be times as well (in decimal hours) and the
12685 numbers are added as such.
12687 If NLAST is a number, only the NLAST fields will actually be summed."
12688 (interactive)
12689 (save-excursion
12690 (let (col (timecnt 0) diff h m s org-table-clip)
12691 (cond
12692 ((and beg end)) ; beg and end given explicitly
12693 ((org-region-active-p)
12694 (setq beg (region-beginning) end (region-end)))
12696 (setq col (org-table-current-column))
12697 (goto-char (org-table-begin))
12698 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
12699 (error "No table data"))
12700 (org-table-goto-column col)
12701 ;not needed? (skip-chars-backward "^|")
12702 (setq beg (point))
12703 (goto-char (org-table-end))
12704 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
12705 (error "No table data"))
12706 (org-table-goto-column col)
12707 ;not needed? (skip-chars-forward "^|")
12708 (setq end (point))))
12709 (let* ((items (apply 'append (org-table-copy-region beg end)))
12710 (items1 (cond ((not nlast) items)
12711 ((>= nlast (length items)) items)
12712 (t (setq items (reverse items))
12713 (setcdr (nthcdr (1- nlast) items) nil)
12714 (nreverse items))))
12715 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
12716 items1)))
12717 (res (apply '+ numbers))
12718 (sres (if (= timecnt 0)
12719 (format "%g" res)
12720 (setq diff (* 3600 res)
12721 h (floor (/ diff 3600)) diff (mod diff 3600)
12722 m (floor (/ diff 60)) diff (mod diff 60)
12723 s diff)
12724 (format "%d:%02d:%02d" h m s))))
12725 (kill-new sres)
12726 (if (interactive-p)
12727 (message "%s"
12728 (substitute-command-keys
12729 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
12730 (length numbers) sres))))
12731 sres))))
12733 (defun org-table-get-number-for-summing (s)
12734 (let (n)
12735 (if (string-match "^ *|? *" s)
12736 (setq s (replace-match "" nil nil s)))
12737 (if (string-match " *|? *$" s)
12738 (setq s (replace-match "" nil nil s)))
12739 (setq n (string-to-number s))
12740 (cond
12741 ((and (string-match "0" s)
12742 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
12743 ((string-match "\\`[ \t]+\\'" s) nil)
12744 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
12745 (let ((h (string-to-number (or (match-string 1 s) "0")))
12746 (m (string-to-number (or (match-string 2 s) "0")))
12747 (s (string-to-number (or (match-string 4 s) "0"))))
12748 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
12749 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
12750 ((equal n 0) nil)
12751 (t n))))
12753 (defun org-table-get-vertical-vector (desc &optional tbeg col)
12754 "Get a calc vector from a column, accorting to descriptor DESC.
12755 Optional arguments TBEG and COL can give the beginning of the table and
12756 the current column, to avoid unnecessary parsing."
12757 (save-excursion
12758 (or tbeg (setq tbeg (org-table-begin)))
12759 (or col (setq col (org-table-current-column)))
12760 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
12761 (cond
12762 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
12763 (setq n1 (- (match-end 1) (match-beginning 1)))
12764 (if (match-beginning 3)
12765 (setq n2 (- (match-end 2) (match-beginning 3))))
12766 (setq n (if n2 (max n1 n2) n1))
12767 (setq n1 (if n2 (min n1 n2)))
12768 (setq nn n)
12769 (while (and (> nn 0)
12770 (re-search-backward org-table-hline-regexp tbeg t))
12771 (push (org-current-line) hline-list)
12772 (setq nn (1- nn)))
12773 (setq hline-list (nreverse hline-list))
12774 (goto-line (nth (1- n) hline-list))
12775 (when (re-search-forward org-table-dataline-regexp)
12776 (org-table-goto-column col)
12777 (setq beg (point)))
12778 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
12779 (when (re-search-backward org-table-dataline-regexp)
12780 (org-table-goto-column col)
12781 (setq end (point)))
12782 (setq l (apply 'append (org-table-copy-region beg end)))
12783 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
12784 (if (equal x "") "0" x))
12785 l ",") "]"))
12786 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
12787 (setq n1 (string-to-number (match-string 1 desc))
12788 n2 (string-to-number (match-string 2 desc)))
12789 (beginning-of-line 1)
12790 (save-excursion
12791 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
12792 (org-table-goto-column col)
12793 (setq beg (point))))
12794 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
12795 (org-table-goto-column col)
12796 (setq end (point)))
12797 (setq l (apply 'append (org-table-copy-region beg end)))
12798 (concat "[" (mapconcat
12799 (lambda (x) (setq x (org-trim x))
12800 (if (equal x "") "0" x))
12801 l ",") "]"))
12802 ((string-match "\\([0-9]+\\)" desc)
12803 (beginning-of-line 1)
12804 (when (re-search-backward org-table-dataline-regexp tbeg t
12805 (string-to-number (match-string 0 desc)))
12806 (org-table-goto-column col)
12807 (org-trim (org-table-get-field))))))))
12809 (defvar org-table-formula-history nil)
12811 (defvar org-table-column-names nil
12812 "Alist with column names, derived from the `!' line.")
12813 (defvar org-table-column-name-regexp nil
12814 "Regular expression matching the current column names.")
12815 (defvar org-table-local-parameters nil
12816 "Alist with parameter names, derived from the `$' line.")
12817 (defvar org-table-named-field-locations nil
12818 "Alist with locations of named fields.")
12820 (defun org-table-get-formula (&optional equation named)
12821 "Read a formula from the minibuffer, offer stored formula as default."
12822 (let* ((name (car (rassoc (list (org-current-line)
12823 (org-table-current-column))
12824 org-table-named-field-locations)))
12825 (scol (if named
12826 (if name name
12827 (error "Not in a named field"))
12828 (int-to-string (org-table-current-column))))
12829 (dummy (and name (not named)
12830 (not (y-or-n-p "Replace named-field formula with column equation? " ))
12831 (error "Abort")))
12832 (org-table-may-need-update nil)
12833 (stored-list (org-table-get-stored-formulas))
12834 (stored (cdr (assoc scol stored-list)))
12835 (eq (cond
12836 ((and stored equation (string-match "^ *=? *$" equation))
12837 stored)
12838 ((stringp equation)
12839 equation)
12840 (t (read-string
12841 (format "%s formula $%s=" (if named "Field" "Column") scol)
12842 (or stored "") 'org-table-formula-history
12843 ;stored
12844 ))))
12845 mustsave)
12846 (when (not (string-match "\\S-" eq))
12847 ;; remove formula
12848 (setq stored-list (delq (assoc scol stored-list) stored-list))
12849 (org-table-store-formulas stored-list)
12850 (error "Formula removed"))
12851 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
12852 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
12853 (if (and name (not named))
12854 ;; We set the column equation, delete the named one.
12855 (setq stored-list (delq (assoc name stored-list) stored-list)
12856 mustsave t))
12857 (if stored
12858 (setcdr (assoc scol stored-list) eq)
12859 (setq stored-list (cons (cons scol eq) stored-list)))
12860 (if (or mustsave (not (equal stored eq)))
12861 (org-table-store-formulas stored-list))
12862 eq))
12864 (defun org-table-store-formulas (alist)
12865 "Store the list of formulas below the current table."
12866 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
12867 (save-excursion
12868 (goto-char (org-table-end))
12869 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
12870 (delete-region (point) (match-end 0)))
12871 (insert "#+TBLFM: "
12872 (mapconcat (lambda (x)
12873 (concat "$" (car x) "=" (cdr x)))
12874 alist "::")
12875 "\n")))
12877 (defun org-table-get-stored-formulas ()
12878 "Return an alist with the stored formulas directly after current table."
12879 (interactive)
12880 (let (scol eq eq-alist strings string seen)
12881 (save-excursion
12882 (goto-char (org-table-end))
12883 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
12884 (setq strings (org-split-string (match-string 2) " *:: *"))
12885 (while (setq string (pop strings))
12886 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
12887 (setq scol (match-string 1 string)
12888 eq (match-string 2 string)
12889 eq-alist (cons (cons scol eq) eq-alist))
12890 (if (member scol seen)
12891 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
12892 (push scol seen))))))
12893 (nreverse eq-alist)))
12895 (defun org-table-modify-formulas (action &rest columns)
12896 "Modify the formulas stored below the current table.
12897 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
12898 expected, for the other actions only a single column number is needed."
12899 (let ((list (org-table-get-stored-formulas))
12900 (nmax (length (org-split-string
12901 (buffer-substring (point-at-bol) (point-at-eol))
12902 "|")))
12903 col col1 col2 scol si sc1 sc2)
12904 (cond
12905 ((null list)) ; No action needed if there are no stored formulas
12906 ((eq action 'remove)
12907 (setq col (car columns)
12908 scol (int-to-string col))
12909 (org-table-replace-in-formulas list scol "INVALID")
12910 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
12911 (loop for i from (1+ col) upto nmax by 1 do
12912 (setq si (int-to-string i))
12913 (org-table-replace-in-formulas list si (int-to-string (1- i)))
12914 (if (assoc si list) (setcar (assoc si list)
12915 (int-to-string (1- i))))))
12916 ((eq action 'insert)
12917 (setq col (car columns))
12918 (loop for i from nmax downto col by 1 do
12919 (setq si (int-to-string i))
12920 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
12921 (if (assoc si list) (setcar (assoc si list)
12922 (int-to-string (1+ i))))))
12923 ((eq action 'swap)
12924 (setq col1 (car columns) col2 (nth 1 columns)
12925 sc1 (int-to-string col1) sc2 (int-to-string col2))
12926 ;; Hopefully, ZqZtZ will never be a name in a table
12927 (org-table-replace-in-formulas list sc1 "ZqZtZ")
12928 (org-table-replace-in-formulas list sc2 sc1)
12929 (org-table-replace-in-formulas list "ZqZtZ" sc2)
12930 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
12931 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
12932 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
12933 (t (error "Invalid action in `org-table-modify-formulas'")))
12934 (if list (org-table-store-formulas list))))
12936 (defun org-table-replace-in-formulas (list s1 s2)
12937 (let (elt re s)
12938 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
12939 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
12940 re (concat (regexp-quote s1) "\\>"))
12941 (while (setq elt (pop list))
12942 (setq s (cdr elt))
12943 (while (string-match re s)
12944 (setq s (replace-match s2 t t s)))
12945 (setcdr elt s))))
12947 (defun org-table-get-specials ()
12948 "Get the column names and local parameters for this table."
12949 (save-excursion
12950 (let ((beg (org-table-begin)) (end (org-table-end))
12951 names name fields fields1 field cnt c v line col)
12952 (setq org-table-column-names nil
12953 org-table-local-parameters nil
12954 org-table-named-field-locations nil)
12955 (goto-char beg)
12956 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12957 (setq names (org-split-string (match-string 1) " *| *")
12958 cnt 1)
12959 (while (setq name (pop names))
12960 (setq cnt (1+ cnt))
12961 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12962 (push (cons name (int-to-string cnt)) org-table-column-names))))
12963 (setq org-table-column-names (nreverse org-table-column-names))
12964 (setq org-table-column-name-regexp
12965 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12966 (goto-char beg)
12967 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12968 (setq fields (org-split-string (match-string 1) " *| *"))
12969 (while (setq field (pop fields))
12970 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12971 (push (cons (match-string 1 field) (match-string 2 field))
12972 org-table-local-parameters))))
12973 (goto-char beg)
12974 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12975 (setq c (match-string 1)
12976 fields (org-split-string (match-string 2) " *| *"))
12977 (save-excursion
12978 (beginning-of-line (if (equal c "_") 2 0))
12979 (setq line (org-current-line) col 1)
12980 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12981 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12982 (while (and fields1 (setq field (pop fields)))
12983 (setq v (pop fields1) col (1+ col))
12984 (when (and (stringp field) (stringp v)
12985 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12986 (push (cons field v) org-table-local-parameters)
12987 (push (list field line col) org-table-named-field-locations)))))))
12989 (defun org-this-word ()
12990 ;; Get the current word
12991 (save-excursion
12992 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12993 (end (progn (skip-chars-forward "^ \t\n") (point))))
12994 (buffer-substring-no-properties beg end))))
12996 (defun org-table-maybe-eval-formula ()
12997 "Check if the current field starts with \"=\" or \":=\".
12998 If yes, store the formula and apply it."
12999 ;; We already know we are in a table. Get field will only return a formula
13000 ;; when appropriate. It might return a separator line, but no problem.
13001 (when org-table-formula-evaluate-inline
13002 (let* ((field (org-trim (or (org-table-get-field) "")))
13003 named eq)
13004 (when (string-match "^:?=\\(.*\\)" field)
13005 (setq named (equal (string-to-char field) ?:)
13006 eq (match-string 1 field))
13007 (if (fboundp 'calc-eval)
13008 (org-table-eval-formula (if named '(4) nil) eq))))))
13010 (defvar org-recalc-commands nil
13011 "List of commands triggering the recalculation of a line.
13012 Will be filled automatically during use.")
13014 (defvar org-recalc-marks
13015 '((" " . "Unmarked: no special line, no automatic recalculation")
13016 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
13017 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
13018 ("!" . "Column name definition line. Reference in formula as $name.")
13019 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
13020 ("_" . "Names for values in row below this one.")
13021 ("^" . "Names for values in row above this one.")))
13023 (defun org-table-rotate-recalc-marks (&optional newchar)
13024 "Rotate the recalculation mark in the first column.
13025 If in any row, the first field is not consistent with a mark,
13026 insert a new column for the markers.
13027 When there is an active region, change all the lines in the region,
13028 after prompting for the marking character.
13029 After each change, a message will be displayed indicating the meaning
13030 of the new mark."
13031 (interactive)
13032 (unless (org-at-table-p) (error "Not at a table"))
13033 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
13034 (beg (org-table-begin))
13035 (end (org-table-end))
13036 (l (org-current-line))
13037 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
13038 (l2 (if (org-region-active-p) (org-current-line (region-end))))
13039 (have-col
13040 (save-excursion
13041 (goto-char beg)
13042 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
13043 (col (org-table-current-column))
13044 (forcenew (car (assoc newchar org-recalc-marks)))
13045 epos new)
13046 (when l1
13047 (message "Change region to what mark? Type # * ! $ or SPC: ")
13048 (setq newchar (char-to-string (read-char-exclusive))
13049 forcenew (car (assoc newchar org-recalc-marks))))
13050 (if (and newchar (not forcenew))
13051 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
13052 newchar))
13053 (if l1 (goto-line l1))
13054 (save-excursion
13055 (beginning-of-line 1)
13056 (unless (looking-at org-table-dataline-regexp)
13057 (error "Not at a table data line")))
13058 (unless have-col
13059 (org-table-goto-column 1)
13060 (org-table-insert-column)
13061 (org-table-goto-column (1+ col)))
13062 (setq epos (point-at-eol))
13063 (save-excursion
13064 (beginning-of-line 1)
13065 (org-table-get-field
13066 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
13067 (concat " "
13068 (setq new (or forcenew
13069 (cadr (member (match-string 1) marks))))
13070 " ")
13071 " # ")))
13072 (if (and l1 l2)
13073 (progn
13074 (goto-line l1)
13075 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
13076 (and (looking-at org-table-dataline-regexp)
13077 (org-table-get-field 1 (concat " " new " "))))
13078 (goto-line l1)))
13079 (if (not (= epos (point-at-eol))) (org-table-align))
13080 (goto-line l)
13081 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
13083 (defun org-table-maybe-recalculate-line ()
13084 "Recompute the current line if marked for it, and if we haven't just done it."
13085 (interactive)
13086 (and org-table-allow-automatic-line-recalculation
13087 (not (and (memq last-command org-recalc-commands)
13088 (equal org-last-recalc-line (org-current-line))))
13089 (save-excursion (beginning-of-line 1)
13090 (looking-at org-table-auto-recalculate-regexp))
13091 (fboundp 'calc-eval)
13092 (org-table-recalculate) t))
13094 (defvar org-table-formula-debug nil
13095 "Non-nil means, debug table formulas.
13096 When nil, simply write \"#ERROR\" in corrupted fields.")
13098 (defvar modes)
13099 (defsubst org-set-calc-mode (var &optional value)
13100 (if (stringp var)
13101 (setq var (assoc var '(("D" calc-angle-mode deg)
13102 ("R" calc-angle-mode rad)
13103 ("F" calc-prefer-frac t)
13104 ("S" calc-symbolic-mode t)))
13105 value (nth 2 var) var (nth 1 var)))
13106 (if (memq var modes)
13107 (setcar (cdr (memq var modes)) value)
13108 (cons var (cons value modes)))
13109 modes)
13111 (defun org-table-eval-formula (&optional arg equation
13112 suppress-align suppress-const
13113 suppress-store)
13114 "Replace the table field value at the cursor by the result of a calculation.
13116 This function makes use of Dave Gillespie's Calc package, in my view the
13117 most exciting program ever written for GNU Emacs. So you need to have Calc
13118 installed in order to use this function.
13120 In a table, this command replaces the value in the current field with the
13121 result of a formula. It also installs the formula as the \"current\" column
13122 formula, by storing it in a special line below the table. When called
13123 with a `C-u' prefix, the current field must ba a named field, and the
13124 formula is installed as valid in only this specific field.
13126 When called, the command first prompts for a formula, which is read in
13127 the minibuffer. Previously entered formulas are available through the
13128 history list, and the last used formula is offered as a default.
13129 These stored formulas are adapted correctly when moving, inserting, or
13130 deleting columns with the corresponding commands.
13132 The formula can be any algebraic expression understood by the Calc package.
13133 For details, see the Org-mode manual.
13135 This function can also be called from Lisp programs and offers
13136 additional arguments: EQUATION can be the formula to apply. If this
13137 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
13138 used to speed-up recursive calls by by-passing unnecessary aligns.
13139 SUPPRESS-CONST suppresses the interpretation of constants in the
13140 formula, assuming that this has been done already outside the function.
13141 SUPPRESS-STORE means the formula should not be stored, either because
13142 it is already stored, or because it is a modified equation that should
13143 not overwrite the stored one."
13144 (interactive "P")
13145 (require 'calc)
13146 (org-table-check-inside-data-field)
13147 (org-table-get-specials)
13148 (let* (fields
13149 (ndown (if (integerp arg) arg 1))
13150 (org-table-automatic-realign nil)
13151 (case-fold-search nil)
13152 (down (> ndown 1))
13153 (formula (if (and equation suppress-store)
13154 equation
13155 (org-table-get-formula equation (equal arg '(4)))))
13156 (n0 (org-table-current-column))
13157 (modes (copy-sequence org-calc-default-modes))
13158 n form fmt x ev orig c lispp)
13159 ;; Parse the format string. Since we have a lot of modes, this is
13160 ;; a lot of work. However, I think calc still uses most of the time.
13161 (if (string-match ";" formula)
13162 (let ((tmp (org-split-string formula ";")))
13163 (setq formula (car tmp)
13164 fmt (concat (cdr (assoc "%" org-table-local-parameters))
13165 (nth 1 tmp)))
13166 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
13167 (setq c (string-to-char (match-string 1 fmt))
13168 n (string-to-number (match-string 2 fmt)))
13169 (if (= c ?p)
13170 (setq modes (org-set-calc-mode 'calc-internal-prec n))
13171 (setq modes (org-set-calc-mode
13172 'calc-float-format
13173 (list (cdr (assoc c '((?n . float) (?f . fix)
13174 (?s . sci) (?e . eng))))
13175 n))))
13176 (setq fmt (replace-match "" t t fmt)))
13177 (while (string-match "[DRFS]" fmt)
13178 (setq modes (org-set-calc-mode (match-string 0 fmt)))
13179 (setq fmt (replace-match "" t t fmt)))
13180 (unless (string-match "\\S-" fmt)
13181 (setq fmt nil))))
13182 (if (and (not suppress-const) org-table-formula-use-constants)
13183 (setq formula (org-table-formula-substitute-names formula)))
13184 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
13185 (while (> ndown 0)
13186 (setq fields (org-split-string
13187 (buffer-substring
13188 (point-at-bol) (point-at-eol)) " *| *"))
13189 (if org-table-formula-numbers-only
13190 (setq fields (mapcar
13191 (lambda (x) (number-to-string (string-to-number x)))
13192 fields)))
13193 (setq ndown (1- ndown))
13194 (setq form (copy-sequence formula)
13195 lispp (equal (substring form 0 2) "'("))
13196 ;; Insert the references to fields in same row
13197 (while (string-match "\\$\\([0-9]+\\)?" form)
13198 (setq n (if (match-beginning 1)
13199 (string-to-number (match-string 1 form))
13201 x (nth (1- n) fields))
13202 (unless x (error "Invalid field specifier \"%s\""
13203 (match-string 0 form)))
13204 (if (equal x "") (setq x "0"))
13205 (setq form (replace-match
13206 (if lispp x (concat "(" x ")"))
13207 t t form)))
13208 ;; Insert ranges in current column
13209 (while (string-match "\\&[-I0-9]+" form)
13210 (setq form (replace-match
13211 (save-match-data
13212 (org-table-get-vertical-vector (match-string 0 form)
13213 nil n0))
13214 t t form)))
13215 (if lispp
13216 (setq ev (eval (eval (read form)))
13217 ev (if (numberp ev) (number-to-string ev) ev))
13218 (setq ev (calc-eval (cons form modes)
13219 (if org-table-formula-numbers-only 'num))))
13221 (when org-table-formula-debug
13222 (with-output-to-temp-buffer "*Help*"
13223 (princ (format "Substitution history of formula
13224 Orig: %s
13225 $xyz-> %s
13226 $1-> %s\n" orig formula form))
13227 (if (listp ev)
13228 (princ (format " %s^\nError: %s"
13229 (make-string (car ev) ?\-) (nth 1 ev)))
13230 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
13231 ev (or fmt "NONE")
13232 (if fmt (format fmt (string-to-number ev)) ev)))))
13233 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
13234 (unless (and (interactive-p) (not ndown))
13235 (unless (let (inhibit-redisplay)
13236 (y-or-n-p "Debugging Formula. Continue to next? "))
13237 (org-table-align)
13238 (error "Abort"))
13239 (delete-window (get-buffer-window "*Help*"))
13240 (message "")))
13241 (if (listp ev) (setq fmt nil ev "#ERROR"))
13242 (org-table-justify-field-maybe
13243 (if fmt (format fmt (string-to-number ev)) ev))
13244 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
13245 (call-interactively 'org-return)
13246 (setq ndown 0)))
13247 (and down (org-table-maybe-recalculate-line))
13248 (or suppress-align (and org-table-may-need-update
13249 (org-table-align)))))
13251 (defun org-table-recalculate (&optional all noalign)
13252 "Recalculate the current table line by applying all stored formulas.
13253 With prefix arg ALL, do this for all lines in the table."
13254 (interactive "P")
13255 (or (memq this-command org-recalc-commands)
13256 (setq org-recalc-commands (cons this-command org-recalc-commands)))
13257 (unless (org-at-table-p) (error "Not at a table"))
13258 (org-table-get-specials)
13259 (let* ((eqlist (sort (org-table-get-stored-formulas)
13260 (lambda (a b) (string< (car a) (car b)))))
13261 (inhibit-redisplay t)
13262 (line-re org-table-dataline-regexp)
13263 (thisline (org-current-line))
13264 (thiscol (org-table-current-column))
13265 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
13266 ;; Insert constants in all formulas
13267 (setq eqlist
13268 (mapcar (lambda (x)
13269 (setcdr x (org-table-formula-substitute-names (cdr x)))
13271 eqlist))
13272 ;; Split the equation list
13273 (while (setq eq (pop eqlist))
13274 (if (<= (string-to-char (car eq)) ?9)
13275 (push eq eqlnum)
13276 (push eq eqlname)))
13277 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
13278 (if all
13279 (progn
13280 (setq end (move-marker (make-marker) (1+ (org-table-end))))
13281 (goto-char (setq beg (org-table-begin)))
13282 (if (re-search-forward org-table-calculate-mark-regexp end t)
13283 ;; This is a table with marked lines, only compute selected lines
13284 (setq line-re org-table-recalculate-regexp)
13285 ;; Move forward to the first non-header line
13286 (if (and (re-search-forward org-table-dataline-regexp end t)
13287 (re-search-forward org-table-hline-regexp end t)
13288 (re-search-forward org-table-dataline-regexp end t))
13289 (setq beg (match-beginning 0))
13290 nil))) ;; just leave beg where it is
13291 (setq beg (point-at-bol)
13292 end (move-marker (make-marker) (1+ (point-at-eol)))))
13293 (goto-char beg)
13294 (and all (message "Re-applying formulas to full table..."))
13295 (while (re-search-forward line-re end t)
13296 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
13297 ;; Unprotected line, recalculate
13298 (and all (message "Re-applying formulas to full table...(line %d)"
13299 (setq cnt (1+ cnt))))
13300 (setq org-last-recalc-line (org-current-line))
13301 (setq eql eqlnum)
13302 (while (setq entry (pop eql))
13303 (goto-line org-last-recalc-line)
13304 (org-table-goto-column (string-to-number (car entry)) nil 'force)
13305 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
13306 (goto-line thisline)
13307 (org-table-goto-column thiscol)
13308 (or noalign (and org-table-may-need-update (org-table-align))
13309 (and all (message "Re-applying formulas to %d lines...done" cnt)))
13310 ;; Now do the names fields
13311 (while (setq eq (pop eqlname))
13312 (setq name (car eq)
13313 a (assoc name org-table-named-field-locations))
13314 (when a
13315 (message "Re-applying formula to named field: %s" name)
13316 (goto-line (nth 1 a))
13317 (org-table-goto-column (nth 2 a))
13318 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
13319 ;; back to initial position
13320 (goto-line thisline)
13321 (org-table-goto-column thiscol)
13322 (or noalign (and org-table-may-need-update (org-table-align))
13323 (and all (message "Re-applying formulas...done")))))
13325 (defun org-table-formula-substitute-names (f)
13326 "Replace $const with values in string F."
13327 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
13328 ;; First, check for column names
13329 (while (setq start (string-match org-table-column-name-regexp f start))
13330 (setq start (1+ start))
13331 (setq a (assoc (match-string 1 f) org-table-column-names))
13332 (setq f (replace-match (concat "$" (cdr a)) t t f)))
13333 ;; Expand ranges to vectors
13334 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
13335 (setq n1 (string-to-number (match-string 1 f))
13336 n2 (string-to-number (match-string 2 f))
13337 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
13338 s (concat "[($" (number-to-string (1- nn1)) ")"))
13339 (loop for i from nn1 upto nn2 do
13340 (setq s (concat s ",($" (int-to-string i) ")")))
13341 (setq s (concat s "]"))
13342 (if (< n2 n1) (setq s (concat "rev(" s ")")))
13343 (setq f (replace-match s t t f)))
13344 ;; Parameters and constants
13345 (setq start 0)
13346 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
13347 (setq start (1+ start))
13348 (if (setq a (save-match-data
13349 (org-table-get-constant (match-string 1 f))))
13350 (setq f (replace-match (concat "(" a ")") t t f))))
13351 (if org-table-formula-debug
13352 (put-text-property 0 (length f) :orig-formula f1 f))
13355 (defun org-table-get-constant (const)
13356 "Find the value for a parameter or constant in a formula.
13357 Parameters get priority."
13358 (or (cdr (assoc const org-table-local-parameters))
13359 (cdr (assoc const org-table-formula-constants))
13360 (and (fboundp 'constants-get) (constants-get const))
13361 "#UNDEFINED_NAME"))
13363 (defvar org-edit-formulas-map (make-sparse-keymap))
13364 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
13365 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
13366 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
13368 (defvar org-pos)
13370 (defun org-table-edit-formulas ()
13371 "Edit the formulas of the current table in a separate buffer."
13372 (interactive)
13373 (unless (org-at-table-p)
13374 (error "Not at a table"))
13375 (org-table-get-specials)
13376 (let ((eql (org-table-get-stored-formulas))
13377 (pos (move-marker (make-marker) (point)))
13378 (wc (current-window-configuration))
13379 entry loc s)
13380 (switch-to-buffer-other-window "*Edit Formulas*")
13381 (erase-buffer)
13382 (fundamental-mode)
13383 (org-set-local 'org-pos pos)
13384 (org-set-local 'org-window-configuration wc)
13385 (use-local-map org-edit-formulas-map)
13386 (setq s "# Edit formulas and finish with `C-c C-c'.
13387 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
13388 # Use `C-c ?' to get information about $name at point.
13389 # To cancel editing, press `C-c C-q'.\n")
13390 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13391 (insert s)
13392 (while (setq entry (pop eql))
13393 (when (setq loc (assoc (car entry) org-table-named-field-locations))
13394 (setq s (format "# Named formula, referring to column %d in line %d\n"
13395 (nth 2 loc) (nth 1 loc)))
13396 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13397 (insert s))
13398 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
13399 (remove-text-properties 0 (length s) '(face nil) s)
13400 (insert s))
13401 (goto-char (point-min))
13402 (message "Edit formulas and finish with `C-c C-c'.")))
13404 (defun org-show-variable ()
13405 "Show the location/value of the $ expression at point."
13406 (interactive)
13407 (let (var (pos org-pos) (win (selected-window)) e)
13408 (save-excursion
13409 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
13410 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
13411 (setq var (match-string 1))
13412 (error "No variable at point")))
13413 (cond
13414 ((setq e (assoc var org-table-named-field-locations))
13415 (switch-to-buffer-other-window (marker-buffer pos))
13416 (goto-line (nth 1 e))
13417 (org-table-goto-column (nth 2 e))
13418 (select-window win)
13419 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
13420 ((setq e (assoc var org-table-column-names))
13421 (switch-to-buffer-other-window (marker-buffer pos))
13422 (goto-char pos)
13423 (goto-char (org-table-begin))
13424 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
13425 (org-table-end) t)
13426 (progn
13427 (goto-char (match-beginning 1))
13428 (message "Named column (column %s)" (cdr e)))
13429 (error "Column name not found"))
13430 (select-window win))
13431 ((string-match "^[0-9]$" var)
13432 ;; column number
13433 (switch-to-buffer-other-window (marker-buffer pos))
13434 (goto-char pos)
13435 (goto-char (org-table-begin))
13436 (recenter 1)
13437 (if (re-search-forward org-table-dataline-regexp
13438 (org-table-end) t)
13439 (progn
13440 (goto-char (match-beginning 0))
13441 (org-table-goto-column (string-to-number var))
13442 (message "Column %s" var))
13443 (error "Column name not found"))
13444 (select-window win))
13445 ((setq e (assoc var org-table-local-parameters))
13446 (switch-to-buffer-other-window (marker-buffer pos))
13447 (goto-char pos)
13448 (goto-char (org-table-begin))
13449 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
13450 (progn
13451 (goto-char (match-beginning 1))
13452 (message "Local parameter."))
13453 (error "Parameter not found"))
13454 (select-window win))
13456 (cond
13457 ((setq e (assoc var org-table-formula-constants))
13458 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
13459 ((setq e (and (fboundp 'constants-get) (constants-get var)))
13460 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
13461 (t (error "Undefined name $%s" var)))))))
13463 (defun org-finish-edit-formulas (&optional arg)
13464 "Parse the buffer for formula definitions and install them.
13465 With prefix ARG, apply the new formulas to the table."
13466 (interactive "P")
13467 (let ((pos org-pos) eql)
13468 (goto-char (point-min))
13469 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
13470 (push (cons (match-string 1) (match-string 2)) eql))
13471 (set-window-configuration org-window-configuration)
13472 (select-window (get-buffer-window (marker-buffer pos)))
13473 (goto-char pos)
13474 (unless (org-at-table-p)
13475 (error "Lost table position - cannot install formulae"))
13476 (org-table-store-formulas eql)
13477 (move-marker pos nil)
13478 (kill-buffer "*Edit Formulas*")
13479 (if arg
13480 (org-table-recalculate 'all)
13481 (message "New formulas installed - press C-u C-c C-c to apply."))))
13483 (defun org-abort-edit-formulas ()
13484 "Abort editing formulas, without installing the changes."
13485 (interactive)
13486 (let ((pos org-pos))
13487 (set-window-configuration org-window-configuration)
13488 (select-window (get-buffer-window (marker-buffer pos)))
13489 (goto-char pos)
13490 (message "Formula editing aborted without installing changes")))
13492 ;;; The orgtbl minor mode
13494 ;; Define a minor mode which can be used in other modes in order to
13495 ;; integrate the org-mode table editor.
13497 ;; This is really a hack, because the org-mode table editor uses several
13498 ;; keys which normally belong to the major mode, for example the TAB and
13499 ;; RET keys. Here is how it works: The minor mode defines all the keys
13500 ;; necessary to operate the table editor, but wraps the commands into a
13501 ;; function which tests if the cursor is currently inside a table. If that
13502 ;; is the case, the table editor command is executed. However, when any of
13503 ;; those keys is used outside a table, the function uses `key-binding' to
13504 ;; look up if the key has an associated command in another currently active
13505 ;; keymap (minor modes, major mode, global), and executes that command.
13506 ;; There might be problems if any of the keys used by the table editor is
13507 ;; otherwise used as a prefix key.
13509 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
13510 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
13511 ;; addresses this by checking explicitly for both bindings.
13513 ;; The optimized version (see variable `orgtbl-optimized') takes over
13514 ;; all keys which are bound to `self-insert-command' in the *global map*.
13515 ;; Some modes bind other commands to simple characters, for example
13516 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
13517 ;; active, this binding is ignored inside tables and replaced with a
13518 ;; modified self-insert.
13520 (defvar orgtbl-mode nil
13521 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
13522 table editor in arbitrary modes.")
13523 (make-variable-buffer-local 'orgtbl-mode)
13525 (defvar orgtbl-mode-map (make-keymap)
13526 "Keymap for `orgtbl-mode'.")
13528 ;;;###autoload
13529 (defun turn-on-orgtbl ()
13530 "Unconditionally turn on `orgtbl-mode'."
13531 (orgtbl-mode 1))
13533 ;;;###autoload
13534 (defun orgtbl-mode (&optional arg)
13535 "The `org-mode' table editor as a minor mode for use in other modes."
13536 (interactive)
13537 (if (org-mode-p)
13538 ;; Exit without error, in case some hook functions calls this
13539 ;; by accident in org-mode.
13540 (message "Orgtbl-mode is not useful in org-mode, command ignored")
13541 (setq orgtbl-mode
13542 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
13543 (if orgtbl-mode
13544 (progn
13545 (and (orgtbl-setup) (defun orgtbl-setup () nil))
13546 ;; Make sure we are first in minor-mode-map-alist
13547 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
13548 (and c (setq minor-mode-map-alist
13549 (cons c (delq c minor-mode-map-alist)))))
13550 (org-set-local (quote org-table-may-need-update) t)
13551 (org-add-hook 'before-change-functions 'org-before-change-function
13552 nil 'local)
13553 (org-set-local 'org-old-auto-fill-inhibit-regexp
13554 auto-fill-inhibit-regexp)
13555 (org-set-local 'auto-fill-inhibit-regexp
13556 (if auto-fill-inhibit-regexp
13557 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
13558 "[ \t]*|"))
13559 (org-add-to-invisibility-spec '(org-cwidth))
13560 (easy-menu-add orgtbl-mode-menu)
13561 (run-hooks 'orgtbl-mode-hook))
13562 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
13563 (org-cleanup-narrow-column-properties)
13564 (org-remove-from-invisibility-spec '(org-cwidth))
13565 (remove-hook 'before-change-functions 'org-before-change-function t)
13566 (easy-menu-remove orgtbl-mode-menu)
13567 (force-mode-line-update 'all))))
13569 (defun org-cleanup-narrow-column-properties ()
13570 "Remove all properties related to narrow-column invisibility."
13571 (let ((s 1))
13572 (while (setq s (text-property-any s (point-max)
13573 'display org-narrow-column-arrow))
13574 (remove-text-properties s (1+ s) '(display t)))
13575 (setq s 1)
13576 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
13577 (remove-text-properties s (1+ s) '(org-cwidth t)))
13578 (setq s 1)
13579 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
13580 (remove-text-properties s (1+ s) '(invisible t)))))
13582 ;; Install it as a minor mode.
13583 (put 'orgtbl-mode :included t)
13584 (put 'orgtbl-mode :menu-tag "Org Table Mode")
13585 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
13587 (defun orgtbl-make-binding (fun n &rest keys)
13588 "Create a function for binding in the table minor mode.
13589 FUN is the command to call inside a table. N is used to create a unique
13590 command name. KEYS are keys that should be checked in for a command
13591 to execute outside of tables."
13592 (eval
13593 (list 'defun
13594 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
13595 '(arg)
13596 (concat "In tables, run `" (symbol-name fun) "'.\n"
13597 "Outside of tables, run the binding of `"
13598 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
13599 "'.")
13600 '(interactive "p")
13601 (list 'if
13602 '(org-at-table-p)
13603 (list 'call-interactively (list 'quote fun))
13604 (list 'let '(orgtbl-mode)
13605 (list 'call-interactively
13606 (append '(or)
13607 (mapcar (lambda (k)
13608 (list 'key-binding k))
13609 keys)
13610 '('orgtbl-error))))))))
13612 (defun orgtbl-error ()
13613 "Error when there is no default binding for a table key."
13614 (interactive)
13615 (error "This key is has no function outside tables"))
13617 (defun orgtbl-setup ()
13618 "Setup orgtbl keymaps."
13619 (let ((nfunc 0)
13620 (bindings
13621 (list
13622 '([(meta shift left)] org-table-delete-column)
13623 '([(meta left)] org-table-move-column-left)
13624 '([(meta right)] org-table-move-column-right)
13625 '([(meta shift right)] org-table-insert-column)
13626 '([(meta shift up)] org-table-kill-row)
13627 '([(meta shift down)] org-table-insert-row)
13628 '([(meta up)] org-table-move-row-up)
13629 '([(meta down)] org-table-move-row-down)
13630 '("\C-c\C-w" org-table-cut-region)
13631 '("\C-c\M-w" org-table-copy-region)
13632 '("\C-c\C-y" org-table-paste-rectangle)
13633 '("\C-c-" org-table-insert-hline)
13634 ; '([(shift tab)] org-table-previous-field)
13635 '("\C-m" org-table-next-row)
13636 (list (org-key 'S-return) 'org-table-copy-down)
13637 '([(meta return)] org-table-wrap-region)
13638 '("\C-c\C-q" org-table-wrap-region)
13639 '("\C-c?" org-table-current-column)
13640 '("\C-c " org-table-blank-field)
13641 '("\C-c+" org-table-sum)
13642 '("\C-c=" org-table-eval-formula)
13643 '("\C-c'" org-table-edit-formulas)
13644 '("\C-c`" org-table-edit-field)
13645 '("\C-c*" org-table-recalculate)
13646 '("\C-c|" org-table-create-or-convert-from-region)
13647 '("\C-c^" org-table-sort-lines)
13648 '([(control ?#)] org-table-rotate-recalc-marks)))
13649 elt key fun cmd)
13650 (while (setq elt (pop bindings))
13651 (setq nfunc (1+ nfunc))
13652 (setq key (car elt)
13653 fun (nth 1 elt)
13654 cmd (orgtbl-make-binding fun nfunc key))
13655 (define-key orgtbl-mode-map key cmd))
13656 ;; Special treatment needed for TAB and RET
13657 (define-key orgtbl-mode-map [(return)]
13658 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
13659 (define-key orgtbl-mode-map "\C-m"
13660 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
13661 (define-key orgtbl-mode-map [(tab)]
13662 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
13663 (define-key orgtbl-mode-map "\C-i"
13664 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
13665 (define-key orgtbl-mode-map "\C-i"
13666 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
13667 (define-key orgtbl-mode-map "\C-c\C-c"
13668 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
13669 (when orgtbl-optimized
13670 ;; If the user wants maximum table support, we need to hijack
13671 ;; some standard editing functions
13672 (org-remap orgtbl-mode-map
13673 'self-insert-command 'orgtbl-self-insert-command
13674 'delete-char 'org-delete-char
13675 'delete-backward-char 'org-delete-backward-char)
13676 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
13677 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
13678 '("OrgTbl"
13679 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
13680 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
13681 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
13682 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
13683 "--"
13684 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
13685 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
13686 ["Copy Field from Above"
13687 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
13688 "--"
13689 ("Column"
13690 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
13691 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
13692 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
13693 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
13694 "--"
13695 ["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])
13696 ("Row"
13697 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
13698 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
13699 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
13700 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
13701 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
13702 "--"
13703 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
13704 ("Rectangle"
13705 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
13706 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
13707 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
13708 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
13709 "--"
13710 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
13711 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13712 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
13713 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
13714 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
13715 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
13716 ["Sum Column/Rectangle" org-table-sum
13717 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
13718 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
13719 ["Debug Formulas"
13720 (setq org-table-formula-debug (not org-table-formula-debug))
13721 :style toggle :selected org-table-formula-debug]
13725 (defun orgtbl-tab (arg)
13726 "Justification and field motion for `orgtbl-mode'."
13727 (interactive "P")
13728 (if arg (org-table-edit-field t)
13729 (org-table-justify-field-maybe)
13730 (org-table-next-field)))
13732 (defun orgtbl-ret ()
13733 "Justification and field motion for `orgtbl-mode'."
13734 (interactive)
13735 (org-table-justify-field-maybe)
13736 (org-table-next-row))
13738 (defun orgtbl-self-insert-command (N)
13739 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13740 If the cursor is in a table looking at whitespace, the whitespace is
13741 overwritten, and the table is not marked as requiring realignment."
13742 (interactive "p")
13743 (if (and (org-at-table-p)
13745 (and org-table-auto-blank-field
13746 (member last-command
13747 '(orgtbl-hijacker-command-100
13748 orgtbl-hijacker-command-101
13749 orgtbl-hijacker-command-102
13750 orgtbl-hijacker-command-103
13751 orgtbl-hijacker-command-104
13752 orgtbl-hijacker-command-105))
13753 (org-table-blank-field))
13755 (eq N 1)
13756 (looking-at "[^|\n]* +|"))
13757 (let (org-table-may-need-update)
13758 (goto-char (1- (match-end 0)))
13759 (delete-backward-char 1)
13760 (goto-char (match-beginning 0))
13761 (self-insert-command N))
13762 (setq org-table-may-need-update t)
13763 (let (orgtbl-mode)
13764 (call-interactively (key-binding (vector last-input-event))))))
13766 (defun org-force-self-insert (N)
13767 "Needed to enforce self-insert under remapping."
13768 (interactive "p")
13769 (self-insert-command N))
13771 ;;; Exporting
13773 (defconst org-level-max 20)
13775 (defvar org-export-html-preamble nil
13776 "Preamble, to be inserted just after <body>. Set by publishing functions.")
13777 (defvar org-export-html-postamble nil
13778 "Preamble, to be inserted just before </body>. Set by publishing functions.")
13779 (defvar org-export-html-auto-preamble t
13780 "Should default preamble be inserted? Set by publishing functions.")
13781 (defvar org-export-html-auto-postamble t
13782 "Should default postamble be inserted? Set by publishing functions.")
13784 (defconst org-export-plist-vars
13785 '((:language . org-export-default-language)
13786 (:headline-levels . org-export-headline-levels)
13787 (:section-numbers . org-export-with-section-numbers)
13788 (:table-of-contents . org-export-with-toc)
13789 (:archived-trees . org-export-with-archived-trees)
13790 (:emphasize . org-export-with-emphasize)
13791 (:sub-superscript . org-export-with-sub-superscripts)
13792 (:TeX-macros . org-export-with-TeX-macros)
13793 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
13794 (:fixed-width . org-export-with-fixed-width)
13795 (:timestamps . org-export-with-timestamps)
13796 (:tables . org-export-with-tables)
13797 (:table-auto-headline . org-export-highlight-first-table-line)
13798 (:style . org-export-html-style)
13799 (:convert-org-links . org-export-html-link-org-files-as-html)
13800 (:inline-images . org-export-html-inline-images)
13801 (:expand-quoted-html . org-export-html-expand)
13802 (:timestamp . org-export-html-with-timestamp)
13803 (:publishing-directory . org-export-publishing-directory)
13804 (:preamble . org-export-html-preamble)
13805 (:postamble . org-export-html-postamble)
13806 (:auto-preamble . org-export-html-auto-preamble)
13807 (:auto-postamble . org-export-html-auto-postamble)
13808 (:author . user-full-name)
13809 (:email . user-mail-address)))
13811 (defun org-default-export-plist ()
13812 "Return the property list with default settings for the export variables."
13813 (let ((l org-export-plist-vars) rtn e)
13814 (while (setq e (pop l))
13815 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
13816 rtn))
13818 (defun org-infile-export-plist ()
13819 "Return the property list with file-local settings for export."
13820 (save-excursion
13821 (goto-char 0)
13822 (let ((re (org-make-options-regexp
13823 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
13824 p key val text options)
13825 (while (re-search-forward re nil t)
13826 (setq key (org-match-string-no-properties 1)
13827 val (org-match-string-no-properties 2))
13828 (cond
13829 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
13830 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
13831 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
13832 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
13833 ((string-equal key "TEXT")
13834 (setq text (if text (concat text "\n" val) val)))
13835 ((string-equal key "OPTIONS") (setq options val))))
13836 (setq p (plist-put p :text text))
13837 (when options
13838 (let ((op '(("H" . :headline-levels)
13839 ("num" . :section-numbers)
13840 ("toc" . :table-of-contents)
13841 ("\\n" . :preserve-breaks)
13842 ("@" . :expand-quoted-html)
13843 (":" . :fixed-width)
13844 ("|" . :tables)
13845 ("^" . :sub-superscript)
13846 ("*" . :emphasize)
13847 ("TeX" . :TeX-macros)
13848 ("LaTeX" . :LaTeX-fragments)))
13850 (while (setq o (pop op))
13851 (if (string-match (concat (regexp-quote (car o))
13852 ":\\([^ \t\n\r;,.]*\\)")
13853 options)
13854 (setq p (plist-put p (cdr o)
13855 (car (read-from-string
13856 (match-string 1 options)))))))))
13857 p)))
13859 (defun org-combine-plists (&rest plists)
13860 "Create a single property list from all plists in PLISTS.
13861 The process starts by copying the last list, and then setting properties
13862 from the other lists. Settings in the first list are the most significant
13863 ones and overrule settings in the other lists."
13864 (let ((rtn (copy-sequence (pop plists)))
13865 p v ls)
13866 (while plists
13867 (setq ls (pop plists))
13868 (while ls
13869 (setq p (pop ls) v (pop ls))
13870 (setq rtn (plist-put rtn p v))))
13871 rtn))
13873 (defun org-export-directory (type plist)
13874 (let* ((val (plist-get plist :publishing-directory))
13875 (dir (if (listp val)
13876 (or (cdr (assoc type val)) ".")
13877 val)))
13878 dir))
13880 (defun org-export-find-first-heading-line (list)
13881 "Remove all lines from LIST which are before the first headline."
13882 (let ((orig-list list)
13883 (re (concat "^" outline-regexp)))
13884 (while (and list
13885 (not (string-match re (car list))))
13886 (pop list))
13887 (or list orig-list)))
13889 (defun org-skip-comments (lines)
13890 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
13891 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
13892 (re2 "^\\(\\*+\\)[ \t\n\r]")
13893 rtn line level)
13894 (while (setq line (pop lines))
13895 (cond
13896 ((and (string-match re1 line)
13897 (setq level (- (match-end 1) (match-beginning 1))))
13898 ;; Beginning of a COMMENT subtree. Skip it.
13899 (while (and (setq line (pop lines))
13900 (or (not (string-match re2 line))
13901 (> (- (match-end 1) (match-beginning 1)) level))))
13902 (setq lines (cons line lines)))
13903 ((string-match "^#" line)
13904 ;; an ordinary comment line
13906 ((and org-export-table-remove-special-lines
13907 (string-match "^[ \t]*|" line)
13908 (or (string-match "^[ \t]*| *[!_^] *|" line)
13909 (and (string-match "| *<[0-9]+> *|" line)
13910 (not (string-match "| *[^ <|]" line)))))
13911 ;; a special table line that should be removed
13913 (t (setq rtn (cons line rtn)))))
13914 (nreverse rtn)))
13916 (defun org-export (&optional arg)
13917 (interactive)
13918 (let ((help "[t] insert the export option template
13919 \[v] limit export to visible part of outline tree
13921 \[a] export as ASCII
13922 \[h] export as HTML
13923 \[b] export as HTML and browse immediately
13924 \[x] export as XOXO
13926 \[i] export current file as iCalendar file
13927 \[I] export all agenda files as iCalendar files
13928 \[c] export agenda files into combined iCalendar file
13930 \[F] publish current file
13931 \[P] publish current project
13932 \[X] publish... (project will be prompted for)
13933 \[A] publish all projects")
13934 (cmds
13935 '((?t . org-insert-export-options-template)
13936 (?v . org-export-visible)
13937 (?a . org-export-as-ascii)
13938 (?h . org-export-as-html)
13939 (?b . org-export-as-html-and-open)
13940 (?x . org-export-as-xoxo)
13941 (?i . org-export-icalendar-this-file)
13942 (?I . org-export-icalendar-all-agenda-files)
13943 (?c . org-export-icalendar-combine-agenda-files)
13944 (?F . org-publish-current-file)
13945 (?P . org-publish-current-project)
13946 (?X . org-publish)
13947 (?A . org-publish-all)))
13948 r1 r2 ass)
13949 (save-window-excursion
13950 (delete-other-windows)
13951 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
13952 (princ help))
13953 (message "Select command: ")
13954 (setq r1 (read-char-exclusive)))
13955 (setq r2 (if (< r1 27) (+ r1 96) r1))
13956 (if (setq ass (assq r2 cmds))
13957 (call-interactively (cdr ass))
13958 (error "No command associated with key %c" r1))))
13960 ;; ASCII
13962 (defconst org-html-entities
13963 '(("nbsp")
13964 ("iexcl")
13965 ("cent")
13966 ("pound")
13967 ("curren")
13968 ("yen")
13969 ("brvbar")
13970 ("sect")
13971 ("uml")
13972 ("copy")
13973 ("ordf")
13974 ("laquo")
13975 ("not")
13976 ("shy")
13977 ("reg")
13978 ("macr")
13979 ("deg")
13980 ("plusmn")
13981 ("sup2")
13982 ("sup3")
13983 ("acute")
13984 ("micro")
13985 ("para")
13986 ("middot")
13987 ("odot"."o")
13988 ("star"."*")
13989 ("cedil")
13990 ("sup1")
13991 ("ordm")
13992 ("raquo")
13993 ("frac14")
13994 ("frac12")
13995 ("frac34")
13996 ("iquest")
13997 ("Agrave")
13998 ("Aacute")
13999 ("Acirc")
14000 ("Atilde")
14001 ("Auml")
14002 ("Aring") ("AA"."&Aring;")
14003 ("AElig")
14004 ("Ccedil")
14005 ("Egrave")
14006 ("Eacute")
14007 ("Ecirc")
14008 ("Euml")
14009 ("Igrave")
14010 ("Iacute")
14011 ("Icirc")
14012 ("Iuml")
14013 ("ETH")
14014 ("Ntilde")
14015 ("Ograve")
14016 ("Oacute")
14017 ("Ocirc")
14018 ("Otilde")
14019 ("Ouml")
14020 ("times")
14021 ("Oslash")
14022 ("Ugrave")
14023 ("Uacute")
14024 ("Ucirc")
14025 ("Uuml")
14026 ("Yacute")
14027 ("THORN")
14028 ("szlig")
14029 ("agrave")
14030 ("aacute")
14031 ("acirc")
14032 ("atilde")
14033 ("auml")
14034 ("aring")
14035 ("aelig")
14036 ("ccedil")
14037 ("egrave")
14038 ("eacute")
14039 ("ecirc")
14040 ("euml")
14041 ("igrave")
14042 ("iacute")
14043 ("icirc")
14044 ("iuml")
14045 ("eth")
14046 ("ntilde")
14047 ("ograve")
14048 ("oacute")
14049 ("ocirc")
14050 ("otilde")
14051 ("ouml")
14052 ("divide")
14053 ("oslash")
14054 ("ugrave")
14055 ("uacute")
14056 ("ucirc")
14057 ("uuml")
14058 ("yacute")
14059 ("thorn")
14060 ("yuml")
14061 ("fnof")
14062 ("Alpha")
14063 ("Beta")
14064 ("Gamma")
14065 ("Delta")
14066 ("Epsilon")
14067 ("Zeta")
14068 ("Eta")
14069 ("Theta")
14070 ("Iota")
14071 ("Kappa")
14072 ("Lambda")
14073 ("Mu")
14074 ("Nu")
14075 ("Xi")
14076 ("Omicron")
14077 ("Pi")
14078 ("Rho")
14079 ("Sigma")
14080 ("Tau")
14081 ("Upsilon")
14082 ("Phi")
14083 ("Chi")
14084 ("Psi")
14085 ("Omega")
14086 ("alpha")
14087 ("beta")
14088 ("gamma")
14089 ("delta")
14090 ("epsilon")
14091 ("varepsilon"."&epsilon;")
14092 ("zeta")
14093 ("eta")
14094 ("theta")
14095 ("iota")
14096 ("kappa")
14097 ("lambda")
14098 ("mu")
14099 ("nu")
14100 ("xi")
14101 ("omicron")
14102 ("pi")
14103 ("rho")
14104 ("sigmaf") ("varsigma"."&sigmaf;")
14105 ("sigma")
14106 ("tau")
14107 ("upsilon")
14108 ("phi")
14109 ("chi")
14110 ("psi")
14111 ("omega")
14112 ("thetasym") ("vartheta"."&thetasym;")
14113 ("upsih")
14114 ("piv")
14115 ("bull") ("bullet"."&bull;")
14116 ("hellip") ("dots"."&hellip;")
14117 ("prime")
14118 ("Prime")
14119 ("oline")
14120 ("frasl")
14121 ("weierp")
14122 ("image")
14123 ("real")
14124 ("trade")
14125 ("alefsym")
14126 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
14127 ("uarr") ("uparrow"."&uarr;")
14128 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
14129 ("darr")("downarrow"."&darr;")
14130 ("harr") ("leftrightarrow"."&harr;")
14131 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
14132 ("lArr") ("Leftarrow"."&lArr;")
14133 ("uArr") ("Uparrow"."&uArr;")
14134 ("rArr") ("Rightarrow"."&rArr;")
14135 ("dArr") ("Downarrow"."&dArr;")
14136 ("hArr") ("Leftrightarrow"."&hArr;")
14137 ("forall")
14138 ("part") ("partial"."&part;")
14139 ("exist") ("exists"."&exist;")
14140 ("empty") ("emptyset"."&empty;")
14141 ("nabla")
14142 ("isin") ("in"."&isin;")
14143 ("notin")
14144 ("ni")
14145 ("prod")
14146 ("sum")
14147 ("minus")
14148 ("lowast") ("ast"."&lowast;")
14149 ("radic")
14150 ("prop") ("proptp"."&prop;")
14151 ("infin") ("infty"."&infin;")
14152 ("ang") ("angle"."&ang;")
14153 ("and") ("vee"."&and;")
14154 ("or") ("wedge"."&or;")
14155 ("cap")
14156 ("cup")
14157 ("int")
14158 ("there4")
14159 ("sim")
14160 ("cong") ("simeq"."&cong;")
14161 ("asymp")("approx"."&asymp;")
14162 ("ne") ("neq"."&ne;")
14163 ("equiv")
14164 ("le")
14165 ("ge")
14166 ("sub") ("subset"."&sub;")
14167 ("sup") ("supset"."&sup;")
14168 ("nsub")
14169 ("sube")
14170 ("supe")
14171 ("oplus")
14172 ("otimes")
14173 ("perp")
14174 ("sdot") ("cdot"."&sdot;")
14175 ("lceil")
14176 ("rceil")
14177 ("lfloor")
14178 ("rfloor")
14179 ("lang")
14180 ("rang")
14181 ("loz") ("Diamond"."&loz;")
14182 ("spades") ("spadesuit"."&spades;")
14183 ("clubs") ("clubsuit"."&clubs;")
14184 ("hearts") ("diamondsuit"."&hearts;")
14185 ("diams") ("diamondsuit"."&diams;")
14186 ("quot")
14187 ("amp")
14188 ("lt")
14189 ("gt")
14190 ("OElig")
14191 ("oelig")
14192 ("Scaron")
14193 ("scaron")
14194 ("Yuml")
14195 ("circ")
14196 ("tilde")
14197 ("ensp")
14198 ("emsp")
14199 ("thinsp")
14200 ("zwnj")
14201 ("zwj")
14202 ("lrm")
14203 ("rlm")
14204 ("ndash")
14205 ("mdash")
14206 ("lsquo")
14207 ("rsquo")
14208 ("sbquo")
14209 ("ldquo")
14210 ("rdquo")
14211 ("bdquo")
14212 ("dagger")
14213 ("Dagger")
14214 ("permil")
14215 ("lsaquo")
14216 ("rsaquo")
14217 ("euro")
14219 ("arccos"."arccos")
14220 ("arcsin"."arcsin")
14221 ("arctan"."arctan")
14222 ("arg"."arg")
14223 ("cos"."cos")
14224 ("cosh"."cosh")
14225 ("cot"."cot")
14226 ("coth"."coth")
14227 ("csc"."csc")
14228 ("deg"."deg")
14229 ("det"."det")
14230 ("dim"."dim")
14231 ("exp"."exp")
14232 ("gcd"."gcd")
14233 ("hom"."hom")
14234 ("inf"."inf")
14235 ("ker"."ker")
14236 ("lg"."lg")
14237 ("lim"."lim")
14238 ("liminf"."liminf")
14239 ("limsup"."limsup")
14240 ("ln"."ln")
14241 ("log"."log")
14242 ("max"."max")
14243 ("min"."min")
14244 ("Pr"."Pr")
14245 ("sec"."sec")
14246 ("sin"."sin")
14247 ("sinh"."sinh")
14248 ("sup"."sup")
14249 ("tan"."tan")
14250 ("tanh"."tanh")
14252 "Entities for TeX->HTML translation.
14253 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
14254 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
14255 In that case, \"\\ent\" will be translated to \"&other;\".
14256 The list contains HTML entities for Latin-1, Greek and other symbols.
14257 It is supplemented by a number of commonly used TeX macros with appropriate
14258 translations. There is currently no way for users to extend this.")
14260 (defun org-cleaned-string-for-export (string &rest parameters)
14261 "Cleanup a buffer substring so that links can be created safely."
14262 (interactive)
14263 (let* ((re-radio (and org-target-link-regexp
14264 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
14265 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
14266 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
14267 (re-archive (concat ":" org-archive-tag ":"))
14268 rtn)
14269 (save-excursion
14270 (set-buffer (get-buffer-create " org-mode-tmp"))
14271 (erase-buffer)
14272 (insert string)
14273 (let ((org-inhibit-startup t)) (org-mode))
14275 ;; Get rid of archived trees
14276 (when (not (eq org-export-with-archived-trees t))
14277 (goto-char (point-min))
14278 (while (re-search-forward re-archive nil t)
14279 (if (not (org-on-heading-p))
14280 (org-end-of-subtree t)
14281 (beginning-of-line 1)
14282 (delete-region
14283 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
14284 (org-end-of-subtree t)))))
14286 ;; Find targets in comments and move them out of comments,
14287 ;; but mark them as targets that should be invisible
14288 (goto-char (point-min))
14289 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
14290 (replace-match "\\1(INVISIBLE)"))
14292 ;; Remove comments
14293 (goto-char (point-min))
14294 (while (re-search-forward "^#.*\n?" nil t)
14295 (replace-match ""))
14297 ;; Find matches for radio targets and turn them into internal links
14298 (goto-char (point-min))
14299 (when re-radio
14300 (while (re-search-forward re-radio nil t)
14301 (replace-match "\\1[[\\2]]")))
14303 ;; Find all links that contain a newline and put them into a single line
14304 (goto-char (point-min))
14305 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
14306 (replace-match "\\1 \\3")
14307 (goto-char (match-beginning 0)))
14309 ;; Convert LaTeX fragments to images
14310 (when (memq :LaTeX-fragments parameters)
14311 (org-format-latex
14312 (concat "ltxpng/" (file-name-sans-extension
14313 (file-name-nondirectory
14314 org-current-export-file)))
14315 org-current-export-dir nil "Creating LaTeX image %s"))
14316 (message "Exporting...")
14318 ;; Normalize links: Convert angle and plain links into bracket links
14319 ;; Expand link abbreviations
14320 (goto-char (point-min))
14321 (while (re-search-forward re-plain-link nil t)
14322 (replace-match
14323 (concat
14324 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
14325 t t))
14326 (goto-char (point-min))
14327 (while (re-search-forward re-angle-link nil t)
14328 (replace-match
14329 (concat
14330 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
14331 t t))
14332 (goto-char (point-min))
14333 (while (re-search-forward org-bracket-link-regexp nil t)
14334 (replace-match
14335 (concat "[[" (save-match-data
14336 (org-link-expand-abbrev (match-string 1)))
14338 (if (match-end 3)
14339 (match-string 2)
14340 (concat "[" (match-string 1) "]"))
14341 "]")
14342 t t))
14344 ;; Find multiline emphasis and put them into single line
14345 (when (memq :emph-multiline parameters)
14346 (goto-char (point-min))
14347 (while (re-search-forward org-emph-re nil t)
14348 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
14349 (goto-char (1- (match-end 0)))))
14351 (setq rtn (buffer-string)))
14352 (kill-buffer " org-mode-tmp")
14353 rtn))
14355 (defun org-solidify-link-text (s &optional alist)
14356 "Take link text and make a safe target out of it."
14357 (save-match-data
14358 (let* ((rtn
14359 (mapconcat
14360 'identity
14361 (org-split-string s "[ \t\r\n]+") "--"))
14362 (a (assoc rtn alist)))
14363 (or (cdr a) rtn))))
14365 (defun org-convert-to-odd-levels ()
14366 "Convert an org-mode file with all levels allowed to one with odd levels.
14367 This will leave level 1 alone, convert level 2 to level 3, level 3 to
14368 level 5 etc."
14369 (interactive)
14370 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
14371 (let ((org-odd-levels-only nil) n)
14372 (save-excursion
14373 (goto-char (point-min))
14374 (while (re-search-forward "^\\*\\*+" nil t)
14375 (setq n (1- (length (match-string 0))))
14376 (while (>= (setq n (1- n)) 0)
14377 (org-demote))
14378 (end-of-line 1))))))
14381 (defun org-convert-to-oddeven-levels ()
14382 "Convert an org-mode file with only odd levels to one with odd and even levels.
14383 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
14384 section with an even level, conversion would destroy the structure of the file. An error
14385 is signaled in this case."
14386 (interactive)
14387 (goto-char (point-min))
14388 ;; First check if there are no even levels
14389 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
14390 (org-show-context t)
14391 (error "Not all levels are odd in this file. Conversion not possible."))
14392 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
14393 (let ((org-odd-levels-only nil) n)
14394 (save-excursion
14395 (goto-char (point-min))
14396 (while (re-search-forward "^\\*\\*+" nil t)
14397 (setq n (/ (length (match-string 0)) 2))
14398 (while (>= (setq n (1- n)) 0)
14399 (org-promote))
14400 (end-of-line 1))))))
14402 (defun org-tr-level (n)
14403 "Make N odd if required."
14404 (if org-odd-levels-only (1+ (/ n 2)) n))
14406 (defvar org-last-level nil) ; dynamically scoped variable
14407 (defvar org-ascii-current-indentation nil) ; For communication
14409 (defun org-export-as-ascii (arg)
14410 "Export the outline as a pretty ASCII file.
14411 If there is an active region, export only the region.
14412 The prefix ARG specifies how many levels of the outline should become
14413 underlined headlines. The default is 3."
14414 (interactive "P")
14415 (setq-default org-todo-line-regexp org-todo-line-regexp)
14416 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14417 (org-infile-export-plist)))
14418 (region
14419 (buffer-substring
14420 (if (org-region-active-p) (region-beginning) (point-min))
14421 (if (org-region-active-p) (region-end) (point-max))))
14422 (lines (org-export-find-first-heading-line
14423 (org-skip-comments
14424 (org-split-string
14425 (org-cleaned-string-for-export region)
14426 "[\r\n]"))))
14427 (org-ascii-current-indentation '(0 . 0))
14428 (org-startup-with-deadline-check nil)
14429 (level 0) line txt
14430 (umax nil)
14431 (case-fold-search nil)
14432 (filename (concat (file-name-as-directory
14433 (org-export-directory :ascii opt-plist))
14434 (file-name-sans-extension
14435 (file-name-nondirectory buffer-file-name))
14436 ".txt"))
14437 (buffer (find-file-noselect filename))
14438 (levels-open (make-vector org-level-max nil))
14439 (odd org-odd-levels-only)
14440 (date (format-time-string "%Y/%m/%d" (current-time)))
14441 (time (format-time-string "%X" (org-current-time)))
14442 (author (plist-get opt-plist :author))
14443 (title (or (plist-get opt-plist :title)
14444 (file-name-sans-extension
14445 (file-name-nondirectory buffer-file-name))))
14446 (email (plist-get opt-plist :email))
14447 (language (plist-get opt-plist :language))
14448 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14449 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14450 (text nil)
14451 (todo nil)
14452 (lang-words nil))
14454 (setq org-last-level 1)
14455 (org-init-section-numbers)
14457 (find-file-noselect filename)
14459 (setq lang-words (or (assoc language org-export-language-setup)
14460 (assoc "en" org-export-language-setup)))
14461 (if org-export-ascii-show-new-buffer
14462 (switch-to-buffer-other-window buffer)
14463 (set-buffer buffer))
14464 (erase-buffer)
14465 (fundamental-mode)
14466 ;; create local variables for all options, to make sure all called
14467 ;; functions get the correct information
14468 (mapcar (lambda (x)
14469 (set (make-local-variable (cdr x))
14470 (plist-get opt-plist (car x))))
14471 org-export-plist-vars)
14472 (org-set-local 'org-odd-levels-only odd)
14473 (setq umax (if arg (prefix-numeric-value arg)
14474 org-export-headline-levels))
14476 ;; File header
14477 (if title (org-insert-centered title ?=))
14478 (insert "\n")
14479 (if (or author email)
14480 (insert (concat (nth 1 lang-words) ": " (or author "")
14481 (if email (concat " <" email ">") "")
14482 "\n")))
14483 (if (and date time)
14484 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
14485 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
14487 (insert "\n\n")
14489 (if org-export-with-toc
14490 (progn
14491 (insert (nth 3 lang-words) "\n"
14492 (make-string (length (nth 3 lang-words)) ?=) "\n")
14493 (mapcar '(lambda (line)
14494 (if (string-match org-todo-line-regexp
14495 line)
14496 ;; This is a headline
14497 (progn
14498 (setq level (- (match-end 1) (match-beginning 1))
14499 level (org-tr-level level)
14500 txt (match-string 3 line)
14501 todo
14502 (or (and org-export-mark-todo-in-toc
14503 (match-beginning 2)
14504 (not (equal (match-string 2 line)
14505 org-done-string)))
14506 ; TODO, not DONE
14507 (and org-export-mark-todo-in-toc
14508 (= level umax)
14509 (org-search-todo-below
14510 line lines level))))
14511 (setq txt (org-html-expand-for-ascii txt))
14513 (if (and (memq org-export-with-tags '(not-in-toc nil))
14514 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14515 (setq txt (replace-match "" t t txt)))
14516 (if (string-match quote-re0 txt)
14517 (setq txt (replace-match "" t t txt)))
14519 (if org-export-with-section-numbers
14520 (setq txt (concat (org-section-number level)
14521 " " txt)))
14522 (if (<= level umax)
14523 (progn
14524 (insert
14525 (make-string (* (1- level) 4) ?\ )
14526 (format (if todo "%s (*)\n" "%s\n") txt))
14527 (setq org-last-level level))
14528 ))))
14529 lines)))
14531 (org-init-section-numbers)
14532 (while (setq line (pop lines))
14533 ;; Remove the quoted HTML tags.
14534 (setq line (org-html-expand-for-ascii line))
14535 ;; Remove targets
14536 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
14537 (setq line (replace-match "" t t line)))
14538 ;; Replace internal links
14539 (while (string-match org-bracket-link-regexp line)
14540 (setq line (replace-match
14541 (if (match-end 3) "[\\3]" "[\\1]")
14542 t nil line)))
14543 (cond
14544 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14545 ;; a Headline
14546 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14547 txt (match-string 2 line))
14548 (org-ascii-level-start level txt umax lines))
14550 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
14551 (normal-mode)
14552 (save-buffer)
14553 ;; remove display and invisible chars
14554 (let (beg end)
14555 (goto-char (point-min))
14556 (while (setq beg (next-single-property-change (point) 'display))
14557 (setq end (next-single-property-change beg 'display))
14558 (delete-region beg end)
14559 (goto-char beg)
14560 (insert "=>"))
14561 (goto-char (point-min))
14562 (while (setq beg (next-single-property-change (point) 'org-cwidth))
14563 (setq end (next-single-property-change beg 'org-cwidth))
14564 (delete-region beg end)
14565 (goto-char beg)))
14566 (goto-char (point-min))))
14568 (defun org-search-todo-below (line lines level)
14569 "Search the subtree below LINE for any TODO entries."
14570 (let ((rest (cdr (memq line lines)))
14571 (re org-todo-line-regexp)
14572 line lv todo)
14573 (catch 'exit
14574 (while (setq line (pop rest))
14575 (if (string-match re line)
14576 (progn
14577 (setq lv (- (match-end 1) (match-beginning 1))
14578 todo (and (match-beginning 2)
14579 (not (equal (match-string 2 line)
14580 org-done-string))))
14581 ; TODO, not DONE
14582 (if (<= lv level) (throw 'exit nil))
14583 (if todo (throw 'exit t))))))))
14585 (defun org-html-expand-for-ascii (line)
14586 "Handle quoted HTML for ASCII export."
14587 (if org-export-html-expand
14588 (while (string-match "@<[^<>\n]*>" line)
14589 ;; We just remove the tags for now.
14590 (setq line (replace-match "" nil nil line))))
14591 line)
14593 (defun org-insert-centered (s &optional underline)
14594 "Insert the string S centered and underline it with character UNDERLINE."
14595 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
14596 (insert (make-string ind ?\ ) s "\n")
14597 (if underline
14598 (insert (make-string ind ?\ )
14599 (make-string (string-width s) underline)
14600 "\n"))))
14602 (defun org-ascii-level-start (level title umax &optional lines)
14603 "Insert a new level in ASCII export."
14604 (let (char (n (- level umax 1)) (ind 0))
14605 (if (> level umax)
14606 (progn
14607 (insert (make-string (* 2 n) ?\ )
14608 (char-to-string (nth (% n (length org-export-ascii-bullets))
14609 org-export-ascii-bullets))
14610 " " title "\n")
14611 ;; find the indentation of the next non-empty line
14612 (catch 'stop
14613 (while lines
14614 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
14615 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
14616 (throw 'stop (setq ind (org-get-indentation (car lines)))))
14617 (pop lines)))
14618 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
14619 (if (or (not (equal (char-before) ?\n))
14620 (not (equal (char-before (1- (point))) ?\n)))
14621 (insert "\n"))
14622 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
14623 (unless org-export-with-tags
14624 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14625 (setq title (replace-match "" t t title))))
14626 (if org-export-with-section-numbers
14627 (setq title (concat (org-section-number level) " " title)))
14628 (insert title "\n" (make-string (string-width title) char) "\n")
14629 (setq org-ascii-current-indentation '(0 . 0)))))
14631 (defun org-export-visible (type arg)
14632 "Create a copy of the visible part of the current buffer, and export it.
14633 The copy is created in a temporary buffer and removed after use.
14634 TYPE is the final key (as a string) that also select the export command in
14635 the `C-c C-e' export dispatcher.
14636 As a special case, if the you type SPC at the prompt, the temporary
14637 org-mode file will not be removed but presented to you so that you can
14638 continue to use it. The prefix arg ARG is passed through to the exporting
14639 command."
14640 (interactive
14641 (list (progn
14642 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
14643 (read-char-exclusive))
14644 current-prefix-arg))
14645 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
14646 (error "Invalid export key"))
14647 (let* ((binding (cdr (assoc type
14648 '((?a . org-export-as-ascii)
14649 (?\C-a . org-export-as-ascii)
14650 (?b . org-export-as-html-and-open)
14651 (?\C-b . org-export-as-html-and-open)
14652 (?h . org-export-as-html)
14653 (?x . org-export-as-xoxo)))))
14654 (keepp (equal type ?\ ))
14655 (file buffer-file-name)
14656 (buffer (get-buffer-create "*Org Export Visible*"))
14657 s e)
14658 (with-current-buffer buffer (erase-buffer))
14659 (save-excursion
14660 (setq s (goto-char (point-min)))
14661 (while (not (= (point) (point-max)))
14662 (goto-char (org-find-invisible))
14663 (append-to-buffer buffer s (point))
14664 (setq s (goto-char (org-find-visible))))
14665 (goto-char (point-min))
14666 (unless keepp
14667 ;; Copy all comment lines to the end, to make sure #+ settings are
14668 ;; still available for the second export step. Kind of a hack, but
14669 ;; does do the trick.
14670 (if (looking-at "#[^\r\n]*")
14671 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
14672 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
14673 (append-to-buffer buffer (1+ (match-beginning 0))
14674 (min (point-max) (1+ (match-end 0))))))
14675 (set-buffer buffer)
14676 (let ((buffer-file-name file)
14677 (org-inhibit-startup t))
14678 (org-mode)
14679 (show-all)
14680 (unless keepp (funcall binding arg))))
14681 (if (not keepp)
14682 (kill-buffer buffer)
14683 (switch-to-buffer-other-window buffer)
14684 (goto-char (point-min)))))
14686 (defun org-find-visible ()
14687 (let ((s (point)))
14688 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14689 (get-char-property s 'invisible)))
14691 (defun org-find-invisible ()
14692 (let ((s (point)))
14693 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
14694 (not (get-char-property s 'invisible))))
14697 ;; HTML
14699 (defun org-get-current-options ()
14700 "Return a string with current options as keyword options.
14701 Does include HTML export options as well as TODO and CATEGORY stuff."
14702 (format
14703 "#+TITLE: %s
14704 #+AUTHOR: %s
14705 #+EMAIL: %s
14706 #+LANGUAGE: %s
14707 #+TEXT: Some descriptive text to be emitted. Several lines OK.
14708 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
14709 #+CATEGORY: %s
14710 #+SEQ_TODO: %s
14711 #+TYP_TODO: %s
14712 #+STARTUP: %s %s %s %s %s %s
14713 #+TAGS: %s
14714 #+ARCHIVE: %s
14715 #+LINK: %s
14717 (buffer-name) (user-full-name) user-mail-address org-export-default-language
14718 org-export-headline-levels
14719 org-export-with-section-numbers
14720 org-export-with-toc
14721 org-export-preserve-breaks
14722 org-export-html-expand
14723 org-export-with-fixed-width
14724 org-export-with-tables
14725 org-export-with-sub-superscripts
14726 org-export-with-emphasize
14727 org-export-with-TeX-macros
14728 org-export-with-LaTeX-fragments
14729 (file-name-nondirectory buffer-file-name)
14730 (if (equal org-todo-interpretation 'sequence)
14731 (mapconcat 'identity org-todo-keywords " ")
14732 "TODO FEEDBACK VERIFY DONE")
14733 (if (equal org-todo-interpretation 'type)
14734 (mapconcat 'identity org-todo-keywords " ")
14735 "Me Jason Marie DONE")
14736 (cdr (assoc org-startup-folded
14737 '((nil . "showall") (t . "overview") (content . "content"))))
14738 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
14739 (if org-odd-levels-only "odd" "oddeven")
14740 (if org-hide-leading-stars "hidestars" "showstars")
14741 (if org-startup-align-all-tables "align" "noalign")
14742 (if org-log-done "logging" "nologging")
14743 (or (mapconcat (lambda (x)
14744 (cond
14745 ((equal '(:startgroup) x) "{")
14746 ((equal '(:endgroup) x) "}")
14747 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
14748 (t (car x))))
14749 (or org-tag-alist (org-get-buffer-tags)) " ") "")
14750 org-archive-location
14751 "org file:~/org/%s.org"
14754 (defun org-insert-export-options-template ()
14755 "Insert into the buffer a template with information for exporting."
14756 (interactive)
14757 (if (not (bolp)) (newline))
14758 (let ((s (org-get-current-options)))
14759 (and (string-match "#\\+CATEGORY" s)
14760 (setq s (substring s 0 (match-beginning 0))))
14761 (insert s)))
14763 (defun org-toggle-fixed-width-section (arg)
14764 "Toggle the fixed-width export.
14765 If there is no active region, the QUOTE keyword at the current headline is
14766 inserted or removed. When present, it causes the text between this headline
14767 and the next to be exported as fixed-width text, and unmodified.
14768 If there is an active region, this command adds or removes a colon as the
14769 first character of this line. If the first character of a line is a colon,
14770 this line is also exported in fixed-width font."
14771 (interactive "P")
14772 (let* ((cc 0)
14773 (regionp (org-region-active-p))
14774 (beg (if regionp (region-beginning) (point)))
14775 (end (if regionp (region-end)))
14776 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14777 (re "[ \t]*\\(:\\)")
14778 off)
14779 (if regionp
14780 (save-excursion
14781 (goto-char beg)
14782 (setq cc (current-column))
14783 (beginning-of-line 1)
14784 (setq off (looking-at re))
14785 (while (> nlines 0)
14786 (setq nlines (1- nlines))
14787 (beginning-of-line 1)
14788 (cond
14789 (arg
14790 (move-to-column cc t)
14791 (insert ":\n")
14792 (forward-line -1))
14793 ((and off (looking-at re))
14794 (replace-match "" t t nil 1))
14795 ((not off) (move-to-column cc t) (insert ":")))
14796 (forward-line 1)))
14797 (save-excursion
14798 (org-back-to-heading)
14799 (if (looking-at (concat outline-regexp
14800 "\\( +\\<" org-quote-string "\\>\\)"))
14801 (replace-match "" t t nil 1)
14802 (if (looking-at outline-regexp)
14803 (progn
14804 (goto-char (match-end 0))
14805 (insert " " org-quote-string))))))))
14807 (defun org-export-as-html-and-open (arg)
14808 "Export the outline as HTML and immediately open it with a browser.
14809 If there is an active region, export only the region.
14810 The prefix ARG specifies how many levels of the outline should become
14811 headlines. The default is 3. Lower levels will become bulleted lists."
14812 (interactive "P")
14813 (org-export-as-html arg 'hidden)
14814 (org-open-file buffer-file-name))
14816 (defun org-export-as-html-batch ()
14817 "Call `org-export-as-html', may be used in batch processing as
14818 emacs --batch
14819 --load=$HOME/lib/emacs/org.el
14820 --eval \"(setq org-export-headline-levels 2)\"
14821 --visit=MyFile --funcall org-export-as-html-batch"
14822 (org-export-as-html org-export-headline-levels 'hidden))
14824 (defun org-export-as-html (arg &optional hidden ext-plist)
14825 "Export the outline as a pretty HTML file.
14826 If there is an active region, export only the region.
14827 The prefix ARG specifies how many levels of the outline should become
14828 headlines. The default is 3. Lower levels will become bulleted lists.
14829 When HIDDEN is non-nil, don't display the HTML buffer.
14830 EXT-PLIST is a property list with external parameters overriding
14831 org-mode's default settings, but still inferior to file-local settings."
14832 (interactive "P")
14833 (message "Exporting...")
14834 (setq-default org-todo-line-regexp org-todo-line-regexp)
14835 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
14836 (setq-default org-done-string org-done-string)
14837 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14838 ext-plist
14839 (org-infile-export-plist)))
14841 (style (plist-get opt-plist :style))
14842 (link-validate (plist-get opt-plist :link-validation-function))
14843 valid
14844 (odd org-odd-levels-only)
14845 (region-p (org-region-active-p))
14846 (region
14847 (buffer-substring
14848 (if region-p (region-beginning) (point-min))
14849 (if region-p (region-end) (point-max))))
14850 ;; The following two are dynamically scoped into other
14851 ;; routines below.
14852 (org-current-export-dir (org-export-directory :html opt-plist))
14853 (org-current-export-file buffer-file-name)
14854 (all_lines
14855 (org-skip-comments (org-split-string
14856 (org-cleaned-string-for-export
14857 region :emph-multiline
14858 (if (plist-get opt-plist :LaTeX-fragments)
14859 :LaTeX-fragments))
14860 "[\r\n]")))
14861 (lines (org-export-find-first-heading-line all_lines))
14862 (level 0) (line "") (origline "") txt todo
14863 (umax nil)
14864 (filename (concat (file-name-as-directory
14865 (org-export-directory :html opt-plist))
14866 (file-name-sans-extension
14867 (file-name-nondirectory buffer-file-name))
14868 ".html"))
14869 (current-dir (file-name-directory buffer-file-name))
14870 (buffer (find-file-noselect filename))
14871 (levels-open (make-vector org-level-max nil))
14872 (date (format-time-string "%Y/%m/%d" (current-time)))
14873 (time (format-time-string "%X" (org-current-time)))
14874 (author (plist-get opt-plist :author))
14875 (title (or (plist-get opt-plist :title)
14876 (file-name-sans-extension
14877 (file-name-nondirectory buffer-file-name))))
14878 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14879 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14880 (inquote nil)
14881 (infixed nil)
14882 (in-local-list nil)
14883 (local-list-num nil)
14884 (local-list-indent nil)
14885 (llt org-plain-list-ordered-item-terminator)
14886 (email (plist-get opt-plist :email))
14887 (language (plist-get opt-plist :language))
14888 (text (plist-get opt-plist :text))
14889 (lang-words nil)
14890 (target-alist nil) tg
14891 (head-count 0) cnt
14892 (start 0)
14893 (coding-system (and (boundp 'buffer-file-coding-system)
14894 buffer-file-coding-system))
14895 (coding-system-for-write coding-system)
14896 (save-buffer-coding-system coding-system)
14897 (charset (and coding-system
14898 (fboundp 'coding-system-get)
14899 (coding-system-get coding-system 'mime-charset)))
14900 table-open type
14901 table-buffer table-orig-buffer
14902 ind start-is-num starter
14903 rpl path desc descp desc1 desc2 link
14905 (message "Exporting...")
14907 (setq org-last-level 1)
14908 (org-init-section-numbers)
14910 ;; Get the language-dependent settings
14911 (setq lang-words (or (assoc language org-export-language-setup)
14912 (assoc "en" org-export-language-setup)))
14914 ;; Switch to the output buffer
14915 (if (or hidden (not org-export-html-show-new-buffer))
14916 (set-buffer buffer)
14917 (switch-to-buffer-other-window buffer))
14918 (erase-buffer)
14919 (fundamental-mode)
14920 (let ((case-fold-search nil)
14921 (org-odd-levels-only odd))
14922 ;; create local variables for all options, to make sure all called
14923 ;; functions get the correct information
14924 (mapcar (lambda (x)
14925 (set (make-local-variable (cdr x))
14926 (plist-get opt-plist (car x))))
14927 org-export-plist-vars)
14928 (setq umax (if arg (prefix-numeric-value arg)
14929 org-export-headline-levels))
14931 ;; File header
14932 (insert (format
14933 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
14934 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
14935 <html xmlns=\"http://www.w3.org/1999/xhtml\"
14936 lang=\"%s\" xml:lang=\"%s\">
14937 <head>
14938 <title>%s</title>
14939 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
14940 <meta name=\"generator\" content=\"Org-mode\"/>
14941 <meta name=\"generated\" content=\"%s %s\"/>
14942 <meta name=\"author\" content=\"%s\"/>
14944 </head><body>
14946 language language (org-html-expand title) (or charset "iso-8859-1")
14947 date time author style))
14950 (insert (or (plist-get opt-plist :preamble) ""))
14952 (when (plist-get opt-plist :auto-preamble)
14953 (if title (insert (format org-export-html-title-format
14954 (org-html-expand title))))
14955 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
14957 (if org-export-with-toc
14958 (progn
14959 (insert (format "<h%d>%s</h%d>\n"
14960 org-export-html-toplevel-hlevel
14961 (nth 3 lang-words)
14962 org-export-html-toplevel-hlevel))
14963 (insert "<ul>\n<li>")
14964 (setq lines
14965 (mapcar '(lambda (line)
14966 (if (string-match org-todo-line-regexp line)
14967 ;; This is a headline
14968 (progn
14969 (setq level (- (match-end 1) (match-beginning 1))
14970 level (org-tr-level level)
14971 txt (save-match-data
14972 (org-html-expand
14973 (org-export-cleanup-toc-line
14974 (match-string 3 line))))
14975 todo
14976 (or (and org-export-mark-todo-in-toc
14977 (match-beginning 2)
14978 (not (equal (match-string 2 line)
14979 org-done-string)))
14980 ; TODO, not DONE
14981 (and org-export-mark-todo-in-toc
14982 (= level umax)
14983 (org-search-todo-below
14984 line lines level))))
14985 (if (and (memq org-export-with-tags '(not-in-toc nil))
14986 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14987 (setq txt (replace-match "" t t txt)))
14988 (if (string-match quote-re0 txt)
14989 (setq txt (replace-match "" t t txt)))
14990 (if org-export-with-section-numbers
14991 (setq txt (concat (org-section-number level)
14992 " " txt)))
14993 (if (<= level umax)
14994 (progn
14995 (setq head-count (+ head-count 1))
14996 (if (> level org-last-level)
14997 (progn
14998 (setq cnt (- level org-last-level))
14999 (while (>= (setq cnt (1- cnt)) 0)
15000 (insert "\n<ul>\n<li>"))
15001 (insert "\n")))
15002 (if (< level org-last-level)
15003 (progn
15004 (setq cnt (- org-last-level level))
15005 (while (>= (setq cnt (1- cnt)) 0)
15006 (insert "</li>\n</ul>"))
15007 (insert "\n")))
15008 ;; Check for targets
15009 (while (string-match org-target-regexp line)
15010 (setq tg (match-string 1 line)
15011 line (replace-match
15012 (concat "@<span class=\"target\">" tg "@</span> ")
15013 t t line))
15014 (push (cons (org-solidify-link-text tg)
15015 (format "sec-%d" head-count))
15016 target-alist))
15017 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
15018 (setq txt (replace-match "" t t txt)))
15019 (insert
15020 (format
15021 (if todo
15022 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
15023 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
15024 head-count txt))
15026 (setq org-last-level level))
15028 line)
15029 lines))
15030 (while (> org-last-level 0)
15031 (setq org-last-level (1- org-last-level))
15032 (insert "</li>\n</ul>\n"))
15034 (setq head-count 0)
15035 (org-init-section-numbers)
15037 (while (setq line (pop lines) origline line)
15038 (catch 'nextline
15040 ;; end of quote section?
15041 (when (and inquote (string-match "^\\*+" line))
15042 (insert "</pre>\n")
15043 (setq inquote nil))
15044 ;; inside a quote section?
15045 (when inquote
15046 (insert (org-html-protect line) "\n")
15047 (throw 'nextline nil))
15049 ;; verbatim lines
15050 (when (and org-export-with-fixed-width
15051 (string-match "^[ \t]*:\\(.*\\)" line))
15052 (when (not infixed)
15053 (setq infixed t)
15054 (insert "<pre>\n"))
15055 (insert (org-html-protect (match-string 1 line)) "\n")
15056 (when (and lines
15057 (not (string-match "^[ \t]*\\(:.*\\)"
15058 (car lines))))
15059 (setq infixed nil)
15060 (insert "</pre>\n"))
15061 (throw 'nextline nil))
15064 ;; make targets to anchors
15065 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
15066 (cond
15067 ((match-end 2)
15068 (setq line (replace-match
15069 (concat "@<a name=\""
15070 (org-solidify-link-text (match-string 1 line))
15071 "\">\\nbsp@</a>")
15072 t t line)))
15073 ((and org-export-with-toc (equal (string-to-char line) ?*))
15074 (setq line (replace-match
15075 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
15076 ; (concat "@<i>" (match-string 1 line) "@</i> ")
15077 t t line)))
15079 (setq line (replace-match
15080 (concat "@<a name=\""
15081 (org-solidify-link-text (match-string 1 line))
15082 "\" class=\"target\">" (match-string 1 line) "@</a> ")
15083 t t line)))))
15085 (setq line (org-html-handle-time-stamps line))
15087 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
15088 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
15089 ;; Also handle sub_superscripts and checkboxes
15090 (setq line (org-html-expand line))
15092 ;; Format the links
15093 (setq start 0)
15094 (while (string-match org-bracket-link-analytic-regexp line start)
15095 (setq start (match-beginning 0))
15096 (setq type (if (match-end 2) (match-string 2 line) "internal"))
15097 (setq path (match-string 3 line))
15098 (setq desc1 (if (match-end 5) (match-string 5 line))
15099 desc2 (if (match-end 2) (concat type ":" path) path)
15100 descp (and desc1 (not (equal desc1 desc2)))
15101 desc (or desc1 desc2))
15102 ;; FIXME: do we need to unescape here somewhere?
15103 (cond
15104 ((equal type "internal")
15105 (setq rpl
15106 (concat
15107 "<a href=\"#"
15108 (org-solidify-link-text path target-alist)
15109 "\">" desc "</a>")))
15110 ((member type '("http" "https" "ftp" "mailto" "news"))
15111 ;; standard URL
15112 (setq link (concat type ":" path))
15113 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
15114 ((string= type "file")
15115 ;; FILE link
15116 (let* ((filename path)
15117 (abs-p (file-name-absolute-p filename))
15118 thefile file-is-image-p search)
15119 (save-match-data
15120 (if (string-match "::\\(.*\\)" filename)
15121 (setq search (match-string 1 filename)
15122 filename (replace-match "" t nil filename)))
15123 (setq valid
15124 (if (functionp link-validate)
15125 (funcall link-validate filename current-dir)
15127 (setq file-is-image-p
15128 (string-match (org-image-file-name-regexp) filename))
15129 (setq thefile (if abs-p (expand-file-name filename) filename))
15130 (when (and org-export-html-link-org-files-as-html
15131 (string-match "\\.org$" thefile))
15132 (setq thefile (concat (substring thefile 0
15133 (match-beginning 0))
15134 ".html"))
15135 (if (and search
15136 ;; make sure this is can be used as target search
15137 (not (string-match "^[0-9]*$" search))
15138 (not (string-match "^\\*" search))
15139 (not (string-match "^/.*/$" search)))
15140 (setq thefile (concat thefile "#"
15141 (org-solidify-link-text
15142 (org-link-unescape search)))))
15143 (when (string-match "^file:" desc)
15144 (setq desc (replace-match "" t t desc))
15145 (if (string-match "\\.org$" desc)
15146 (setq desc (replace-match "" t t desc))))))
15147 (setq rpl (if (and file-is-image-p
15148 (or (eq t org-export-html-inline-images)
15149 (and org-export-html-inline-images
15150 (not descp))))
15151 (concat "<img src=\"" thefile "\"/>")
15152 (concat "<a href=\"" thefile "\">" desc "</a>")))
15153 (if (not valid) (setq rpl desc))))
15154 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
15155 (setq rpl (concat "<i>&lt;" type ":"
15156 (save-match-data (org-link-unescape path))
15157 "&gt;</i>"))))
15158 (setq line (replace-match rpl t t line)
15159 start (+ start (length rpl))))
15160 ;; TODO items
15161 (if (and (string-match org-todo-line-regexp line)
15162 (match-beginning 2))
15163 (if (equal (match-string 2 line) org-done-string)
15164 (setq line (replace-match
15165 "<span class=\"done\">\\2</span>"
15166 t nil line 2))
15167 (setq line (replace-match "<span class=\"todo\">\\2</span>"
15168 t nil line 2))))
15170 (cond
15171 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15172 ;; This is a headline
15173 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15174 txt (match-string 2 line))
15175 (if (string-match quote-re0 txt)
15176 (setq txt (replace-match "" t t txt)))
15177 (if (<= level umax) (setq head-count (+ head-count 1)))
15178 (when in-local-list
15179 ;; Close any local lists before inserting a new header line
15180 (while local-list-num
15181 (org-close-li)
15182 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15183 (pop local-list-num))
15184 (setq local-list-indent nil
15185 in-local-list nil))
15186 (org-html-level-start level txt umax
15187 (and org-export-with-toc (<= level umax))
15188 head-count)
15189 ;; QUOTES
15190 (when (string-match quote-re line)
15191 (insert "<pre>")
15192 (setq inquote t)))
15194 ((and org-export-with-tables
15195 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
15196 (if (not table-open)
15197 ;; New table starts
15198 (setq table-open t table-buffer nil table-orig-buffer nil))
15199 ;; Accumulate lines
15200 (setq table-buffer (cons line table-buffer)
15201 table-orig-buffer (cons origline table-orig-buffer))
15202 (when (or (not lines)
15203 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
15204 (car lines))))
15205 (setq table-open nil
15206 table-buffer (nreverse table-buffer)
15207 table-orig-buffer (nreverse table-orig-buffer))
15208 (org-close-par-maybe)
15209 (insert (org-format-table-html table-buffer table-orig-buffer))))
15211 ;; Normal lines
15212 (when (string-match
15213 (cond
15214 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15215 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15216 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15217 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
15218 line)
15219 (setq ind (org-get-string-indentation line)
15220 start-is-num (match-beginning 4)
15221 starter (if (match-beginning 2)
15222 (substring (match-string 2 line) 0 -1))
15223 line (substring line (match-beginning 5)))
15224 (unless (string-match "[^ \t]" line)
15225 ;; empty line. Pretend indentation is large.
15226 (setq ind (1+ (or (car local-list-indent) 1))))
15227 (while (and in-local-list
15228 (or (and (= ind (car local-list-indent))
15229 (not starter))
15230 (< ind (car local-list-indent))))
15231 (org-close-li)
15232 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15233 (pop local-list-num) (pop local-list-indent)
15234 (setq in-local-list local-list-indent))
15235 (cond
15236 ((and starter
15237 (or (not in-local-list)
15238 (> ind (car local-list-indent))))
15239 ;; Start new (level of ) list
15240 (org-close-par-maybe)
15241 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
15242 (push start-is-num local-list-num)
15243 (push ind local-list-indent)
15244 (setq in-local-list t))
15245 (starter
15246 ;; continue current list
15247 (org-close-li)
15248 (insert "<li>\n")))
15249 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
15250 (setq line
15251 (replace-match
15252 (if (equal (match-string 1 line) "X")
15253 "<b>[X]</b>"
15254 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
15255 t t line))))
15257 ;; Empty lines start a new paragraph. If hand-formatted lists
15258 ;; are not fully interpreted, lines starting with "-", "+", "*"
15259 ;; also start a new paragraph.
15260 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
15262 ;; Check if the line break needs to be conserved
15263 (cond
15264 ((string-match "\\\\\\\\[ \t]*$" line)
15265 (setq line (replace-match "<br/>" t t line)))
15266 (org-export-preserve-breaks
15267 (setq line (concat line "<br/>"))))
15269 (insert line "\n")))))
15271 ;; Properly close all local lists and other lists
15272 (when inquote (insert "</pre>\n"))
15273 (when in-local-list
15274 ;; Close any local lists before inserting a new header line
15275 (while local-list-num
15276 (org-close-li)
15277 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
15278 (pop local-list-num))
15279 (setq local-list-indent nil
15280 in-local-list nil))
15281 (org-html-level-start 1 nil umax
15282 (and org-export-with-toc (<= level umax))
15283 head-count)
15285 (when (plist-get opt-plist :auto-postamble)
15286 (when author
15287 (insert "<p class=\"author\"> "
15288 (nth 1 lang-words) ": " author "\n")
15289 (when email
15290 (insert "<a href=\"mailto:" email "\">&lt;"
15291 email "&gt;</a>\n"))
15292 (insert "</p>\n"))
15293 (when (and date time)
15294 (insert "<p class=\"date\"> "
15295 (nth 2 lang-words) ": "
15296 date " " time "</p>\n")))
15298 (if org-export-html-with-timestamp
15299 (insert org-export-html-html-helper-timestamp))
15300 (insert (or (plist-get opt-plist :postamble) ""))
15301 (insert "</body>\n</html>\n")
15302 (normal-mode)
15303 ;; remove empty paragraphs and lists
15304 (goto-char (point-min))
15305 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
15306 (replace-match ""))
15307 (goto-char (point-min))
15308 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
15309 (replace-match ""))
15310 (save-buffer)
15311 (goto-char (point-min))
15312 (message "Exporting... done"))))
15315 (defun org-format-table-html (lines olines)
15316 "Find out which HTML converter to use and return the HTML code."
15317 (if (string-match "^[ \t]*|" (car lines))
15318 ;; A normal org table
15319 (org-format-org-table-html lines)
15320 ;; Table made by table.el - test for spanning
15321 (let* ((hlines (delq nil (mapcar
15322 (lambda (x)
15323 (if (string-match "^[ \t]*\\+-" x) x
15324 nil))
15325 lines)))
15326 (first (car hlines))
15327 (ll (and (string-match "\\S-+" first)
15328 (match-string 0 first)))
15329 (re (concat "^[ \t]*" (regexp-quote ll)))
15330 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
15331 hlines))))
15332 (if (and (not spanning)
15333 (not org-export-prefer-native-exporter-for-tables))
15334 ;; We can use my own converter with HTML conversions
15335 (org-format-table-table-html lines)
15336 ;; Need to use the code generator in table.el, with the original text.
15337 (org-format-table-table-html-using-table-generate-source olines)))))
15339 (defun org-format-org-table-html (lines)
15340 "Format a table into HTML."
15341 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15342 (setq lines (nreverse lines))
15343 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15344 (setq lines (nreverse lines))
15345 (when org-export-table-remove-special-lines
15346 ;; Check if the table has a marking column. If yes remove the
15347 ;; column and the special lines
15348 (let* ((special
15349 (not
15350 (memq nil
15351 (mapcar
15352 (lambda (x)
15353 (or (string-match "^[ \t]*|-" x)
15354 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
15355 lines)))))
15356 (if special
15357 (setq lines
15358 (delq nil
15359 (mapcar
15360 (lambda (x)
15361 (if (string-match "^[ \t]*| *[!_^] *|" x)
15362 nil ; ignore this line
15363 (and (or (string-match "^[ \t]*|-+\\+" x)
15364 (string-match "^[ \t]*|[^|]*|" x))
15365 (replace-match "|" t t x))))
15366 lines))))))
15368 (let ((head (and org-export-highlight-first-table-line
15369 (delq nil (mapcar
15370 (lambda (x) (string-match "^[ \t]*|-" x))
15371 (cdr lines)))))
15372 line fields html)
15373 (setq html (concat org-export-html-table-tag "\n"))
15374 (while (setq line (pop lines))
15375 (catch 'next-line
15376 (if (string-match "^[ \t]*|-" line)
15377 (progn
15378 (setq head nil) ;; head ends here, first time around
15379 ;; ignore this line
15380 (throw 'next-line t)))
15381 ;; Break the line into fields
15382 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15383 (setq html (concat
15384 html
15385 "<tr>"
15386 (mapconcat (lambda (x)
15387 (if head
15388 (concat "<th>" x "</th>")
15389 (concat "<td>" x "</td>")))
15390 fields "")
15391 "</tr>\n"))))
15392 (setq html (concat html "</table>\n"))
15393 html))
15395 (defun org-fake-empty-table-line (line)
15396 "Replace everything except \"|\" with spaces."
15397 (let ((i (length line))
15398 (newstr (copy-sequence line)))
15399 (while (> i 0)
15400 (setq i (1- i))
15401 (if (not (eq (aref newstr i) ?|))
15402 (aset newstr i ?\ )))
15403 newstr))
15405 (defun org-format-table-table-html (lines)
15406 "Format a table generated by table.el into HTML.
15407 This conversion does *not* use `table-generate-source' from table.el.
15408 This has the advantage that Org-mode's HTML conversions can be used.
15409 But it has the disadvantage, that no cell- or row-spanning is allowed."
15410 (let (line field-buffer
15411 (head org-export-highlight-first-table-line)
15412 fields html empty)
15413 (setq html (concat org-export-html-table-tag "\n"))
15414 (while (setq line (pop lines))
15415 (setq empty "&nbsp;")
15416 (catch 'next-line
15417 (if (string-match "^[ \t]*\\+-" line)
15418 (progn
15419 (if field-buffer
15420 (progn
15421 (setq html (concat
15422 html
15423 "<tr>"
15424 (mapconcat
15425 (lambda (x)
15426 (if (equal x "") (setq x empty))
15427 (if head
15428 (concat "<th>" x "</th>\n")
15429 (concat "<td>" x "</td>\n")))
15430 field-buffer "\n")
15431 "</tr>\n"))
15432 (setq head nil)
15433 (setq field-buffer nil)))
15434 ;; Ignore this line
15435 (throw 'next-line t)))
15436 ;; Break the line into fields and store the fields
15437 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15438 (if field-buffer
15439 (setq field-buffer (mapcar
15440 (lambda (x)
15441 (concat x "<br/>" (pop fields)))
15442 field-buffer))
15443 (setq field-buffer fields))))
15444 (setq html (concat html "</table>\n"))
15445 html))
15447 (defun org-format-table-table-html-using-table-generate-source (lines)
15448 "Format a table into html, using `table-generate-source' from table.el.
15449 This has the advantage that cell- or row-spanning is allowed.
15450 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
15451 (require 'table)
15452 (with-current-buffer (get-buffer-create " org-tmp1 ")
15453 (erase-buffer)
15454 (insert (mapconcat 'identity lines "\n"))
15455 (goto-char (point-min))
15456 (if (not (re-search-forward "|[^+]" nil t))
15457 (error "Error processing table"))
15458 (table-recognize-table)
15459 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
15460 (table-generate-source 'html " org-tmp2 ")
15461 (set-buffer " org-tmp2 ")
15462 (buffer-substring (point-min) (point-max))))
15464 (defun org-html-handle-time-stamps (s)
15465 "Format time stamps in string S, or remove them."
15466 (catch 'exit
15467 (let (r b)
15468 (while (string-match org-maybe-keyword-time-regexp s)
15469 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
15470 ;; never export CLOCK
15471 (throw 'exit ""))
15472 (or b (setq b (substring s 0 (match-beginning 0))))
15473 (if (not org-export-with-timestamps)
15474 (setq r (concat r (substring s 0 (match-beginning 0)))
15475 s (substring s (match-end 0)))
15476 (setq r (concat
15477 r (substring s 0 (match-beginning 0))
15478 (if (match-end 1)
15479 (format "@<span class=\"timestamp-kwd\">%s @</span>"
15480 (match-string 1 s)))
15481 (format " @<span class=\"timestamp\">%s@</span>"
15482 (substring (match-string 3 s) 1 -1)))
15483 s (substring s (match-end 0)))))
15484 ;; Line break if line started and ended with time stamp stuff
15485 (if (not r)
15487 (setq r (concat r s))
15488 (unless (string-match "\\S-" (concat b s))
15489 (setq r (concat r "@<br/>")))
15490 r))))
15492 (defun org-html-protect (s)
15493 ;; convert & to &amp;, < to &lt; and > to &gt;
15494 (let ((start 0))
15495 (while (string-match "&" s start)
15496 (setq s (replace-match "&amp;" t t s)
15497 start (1+ (match-beginning 0))))
15498 (while (string-match "<" s)
15499 (setq s (replace-match "&lt;" t t s)))
15500 (while (string-match ">" s)
15501 (setq s (replace-match "&gt;" t t s))))
15504 (defun org-export-cleanup-toc-line (s)
15505 "Remove tags and time staps from lines going into the toc."
15506 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
15507 (setq s (replace-match "" t t s)))
15508 (when org-export-remove-timestamps-from-toc
15509 (while (string-match org-maybe-keyword-time-regexp s)
15510 (setq s (replace-match "" t t s))))
15513 (defun org-html-expand (string)
15514 "Prepare STRING for HTML export. Applies all active conversions.
15515 If there are links in the string, don't modify these."
15516 (let* (m s l res)
15517 (while (setq m (string-match org-bracket-link-regexp string))
15518 (setq s (substring string 0 m)
15519 l (match-string 0 string)
15520 string (substring string (match-end 0)))
15521 (push (org-html-do-expand s) res)
15522 (push l res))
15523 (push (org-html-do-expand string) res)
15524 (apply 'concat (nreverse res))))
15526 (defun org-html-do-expand (s)
15527 "Apply all active conversions to translate special ASCII to HTML."
15528 (setq s (org-html-protect s))
15529 (if org-export-html-expand
15530 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
15531 (setq s (replace-match "<\\1>" t nil s))))
15532 (if org-export-with-emphasize
15533 (setq s (org-export-html-convert-emphasize s)))
15534 (if org-export-with-sub-superscripts
15535 (setq s (org-export-html-convert-sub-super s)))
15536 (if org-export-with-TeX-macros
15537 (let ((start 0) wd ass)
15538 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
15539 (setq wd (match-string 1 s))
15540 (if (setq ass (assoc wd org-html-entities))
15541 (setq s (replace-match (or (cdr ass)
15542 (concat "&" (car ass) ";"))
15543 t t s))
15544 (setq start (+ start (length wd)))))))
15547 (defun org-create-multibrace-regexp (left right n)
15548 "Create a regular expression which will match a balanced sexp.
15549 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
15550 as single character strings.
15551 The regexp returned will match the entire expression including the
15552 delimiters. It will also define a single group which contains the
15553 match except for the outermost delimiters. The maximum depth of
15554 stacked delimiters is N. Escaping delimiters is not possible."
15555 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
15556 (or "\\|")
15557 (re nothing)
15558 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
15559 (while (> n 1)
15560 (setq n (1- n)
15561 re (concat re or next)
15562 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
15563 (concat left "\\(" re "\\)" right)))
15565 (defvar org-match-substring-regexp
15566 (concat
15567 "\\([^\\]\\)\\([_^]\\)\\("
15568 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
15569 "\\|"
15570 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
15571 "\\|"
15572 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
15573 "The regular expression matching a sub- or superscript.")
15575 (defun org-export-html-convert-sub-super (string)
15576 "Convert sub- and superscripts in STRING to HTML."
15577 (let (key c)
15578 (while (string-match org-match-substring-regexp string)
15579 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
15580 (setq c (or (match-string 8 string)
15581 (match-string 6 string)
15582 (match-string 5 string)))
15583 (setq string (replace-match
15584 (concat (match-string 1 string)
15585 "<" key ">" c "</" key ">")
15586 t t string)))
15587 (while (string-match "\\\\\\([_^]\\)" string)
15588 (setq string (replace-match (match-string 1 string) t t string))))
15589 string)
15591 (defun org-export-html-convert-emphasize (string)
15592 "Apply emphasis."
15593 (while (string-match org-emph-re string)
15594 (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)))
15595 string)
15597 (defvar org-par-open nil)
15598 (defun org-open-par ()
15599 "Insert <p>, but first close previous paragraph if any."
15600 (org-close-par-maybe)
15601 (insert "\n<p>")
15602 (setq org-par-open t))
15603 (defun org-close-par-maybe ()
15604 "Close paragraph if there is one open."
15605 (when org-par-open
15606 (insert "</p>")
15607 (setq org-par-open nil)))
15608 (defun org-close-li ()
15609 "Close <li> if necessary."
15610 (org-close-par-maybe)
15611 (insert "</li>\n"))
15612 ; (when (save-excursion
15613 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
15614 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
15615 ; (insert "</li>"))))
15617 (defun org-html-level-start (level title umax with-toc head-count)
15618 "Insert a new level in HTML export.
15619 When TITLE is nil, just close all open levels."
15620 (org-close-par-maybe)
15621 (let ((l (1+ (max level umax))))
15622 (while (<= l org-level-max)
15623 (if (aref levels-open (1- l))
15624 (progn
15625 (org-html-level-close l)
15626 (aset levels-open (1- l) nil)))
15627 (setq l (1+ l)))
15628 (when title
15629 ;; If title is nil, this means this function is called to close
15630 ;; all levels, so the rest is done only if title is given
15631 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
15632 (setq title (replace-match
15633 (if org-export-with-tags
15634 (save-match-data
15635 (concat
15636 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
15637 (mapconcat 'identity (org-split-string
15638 (match-string 1 title) ":")
15639 "&nbsp;")
15640 "</span>"))
15642 t t title)))
15643 (if (> level umax)
15644 (progn
15645 (if (aref levels-open (1- level))
15646 (progn
15647 (org-close-li)
15648 (insert "<li>" title "<br/>\n"))
15649 (aset levels-open (1- level) t)
15650 (org-close-par-maybe)
15651 (insert "<ul>\n<li>" title "<br/>\n")))
15652 (if org-export-with-section-numbers
15653 (setq title (concat (org-section-number level) " " title)))
15654 (setq level (+ level org-export-html-toplevel-hlevel -1))
15655 (if with-toc
15656 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
15657 level head-count title level))
15658 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
15659 (org-open-par)))))
15661 (defun org-html-level-close (&rest args)
15662 "Terminate one level in HTML export."
15663 (org-close-li)
15664 (insert "</ul>"))
15666 ;; Variable holding the vector with section numbers
15667 (defvar org-section-numbers (make-vector org-level-max 0))
15669 (defun org-init-section-numbers ()
15670 "Initialize the vector for the section numbers."
15671 (let* ((level -1)
15672 (numbers (nreverse (org-split-string "" "\\.")))
15673 (depth (1- (length org-section-numbers)))
15674 (i depth) number-string)
15675 (while (>= i 0)
15676 (if (> i level)
15677 (aset org-section-numbers i 0)
15678 (setq number-string (or (car numbers) "0"))
15679 (if (string-match "\\`[A-Z]\\'" number-string)
15680 (aset org-section-numbers i
15681 (- (string-to-char number-string) ?A -1))
15682 (aset org-section-numbers i (string-to-number number-string)))
15683 (pop numbers))
15684 (setq i (1- i)))))
15686 (defun org-section-number (&optional level)
15687 "Return a string with the current section number.
15688 When LEVEL is non-nil, increase section numbers on that level."
15689 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
15690 (when level
15691 (when (> level -1)
15692 (aset org-section-numbers
15693 level (1+ (aref org-section-numbers level))))
15694 (setq idx (1+ level))
15695 (while (<= idx depth)
15696 (if (not (= idx 1))
15697 (aset org-section-numbers idx 0))
15698 (setq idx (1+ idx))))
15699 (setq idx 0)
15700 (while (<= idx depth)
15701 (setq n (aref org-section-numbers idx))
15702 (setq string (concat string (if (not (string= string "")) "." "")
15703 (int-to-string n)))
15704 (setq idx (1+ idx)))
15705 (save-match-data
15706 (if (string-match "\\`\\([@0]\\.\\)+" string)
15707 (setq string (replace-match "" t nil string)))
15708 (if (string-match "\\(\\.0\\)+\\'" string)
15709 (setq string (replace-match "" t nil string))))
15710 string))
15713 ;;;###autoload
15714 (defun org-export-icalendar-this-file ()
15715 "Export current file as an iCalendar file.
15716 The iCalendar file will be located in the same directory as the Org-mode
15717 file, but with extension `.ics'."
15718 (interactive)
15719 (org-export-icalendar nil buffer-file-name))
15721 (defun org-export-as-xoxo-insert-into (buffer &rest output)
15722 (with-current-buffer buffer
15723 (apply 'insert output)))
15724 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
15726 (defun org-export-as-xoxo (&optional buffer)
15727 "Export the org buffer as XOXO.
15728 The XOXO buffer is named *xoxo-<source buffer name>*"
15729 (interactive (list (current-buffer)))
15730 ;; A quickie abstraction
15732 ;; Output everything as XOXO
15733 (with-current-buffer (get-buffer buffer)
15734 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
15735 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15736 (org-infile-export-plist)))
15737 (filename (concat (file-name-as-directory
15738 (org-export-directory :xoxo opt-plist))
15739 (file-name-sans-extension
15740 (file-name-nondirectory buffer-file-name))
15741 ".html"))
15742 (out (find-file-noselect filename))
15743 (last-level 1)
15744 (hanging-li nil))
15745 ;; Check the output buffer is empty.
15746 (with-current-buffer out (erase-buffer))
15747 ;; Kick off the output
15748 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
15749 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
15750 (let* ((hd (match-string-no-properties 1))
15751 (level (length hd))
15752 (text (concat
15753 (match-string-no-properties 2)
15754 (save-excursion
15755 (goto-char (match-end 0))
15756 (let ((str ""))
15757 (catch 'loop
15758 (while 't
15759 (forward-line)
15760 (if (looking-at "^[ \t]\\(.*\\)")
15761 (setq str (concat str (match-string-no-properties 1)))
15762 (throw 'loop str)))))))))
15764 ;; Handle level rendering
15765 (cond
15766 ((> level last-level)
15767 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
15769 ((< level last-level)
15770 (dotimes (- (- last-level level) 1)
15771 (if hanging-li
15772 (org-export-as-xoxo-insert-into out "</li>\n"))
15773 (org-export-as-xoxo-insert-into out "</ol>\n"))
15774 (when hanging-li
15775 (org-export-as-xoxo-insert-into out "</li>\n")
15776 (setq hanging-li nil)))
15778 ((equal level last-level)
15779 (if hanging-li
15780 (org-export-as-xoxo-insert-into out "</li>\n")))
15783 (setq last-level level)
15785 ;; And output the new li
15786 (setq hanging-li 't)
15787 (if (equal ?+ (elt text 0))
15788 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
15789 (org-export-as-xoxo-insert-into out "<li>" text))))
15791 ;; Finally finish off the ol
15792 (dotimes (- last-level 1)
15793 (if hanging-li
15794 (org-export-as-xoxo-insert-into out "</li>\n"))
15795 (org-export-as-xoxo-insert-into out "</ol>\n"))
15797 ;; Finish the buffer off and clean it up.
15798 (switch-to-buffer-other-window out)
15799 (indent-region (point-min) (point-max) nil)
15800 (save-buffer)
15801 (goto-char (point-min))
15804 ;;;###autoload
15805 (defun org-export-icalendar-all-agenda-files ()
15806 "Export all files in `org-agenda-files' to iCalendar .ics files.
15807 Each iCalendar file will be located in the same directory as the Org-mode
15808 file, but with extension `.ics'."
15809 (interactive)
15810 (apply 'org-export-icalendar nil (org-agenda-files t)))
15812 ;;;###autoload
15813 (defun org-export-icalendar-combine-agenda-files ()
15814 "Export all files in `org-agenda-files' to a single combined iCalendar file.
15815 The file is stored under the name `org-combined-agenda-icalendar-file'."
15816 (interactive)
15817 (apply 'org-export-icalendar t (org-agenda-files t)))
15819 (defun org-export-icalendar (combine &rest files)
15820 "Create iCalendar files for all elements of FILES.
15821 If COMBINE is non-nil, combine all calendar entries into a single large
15822 file and store it under the name `org-combined-agenda-icalendar-file'."
15823 (save-excursion
15824 (let* ((dir (org-export-directory
15825 :ical (list :publishing-directory
15826 org-export-publishing-directory)))
15827 file ical-file ical-buffer category started org-agenda-new-buffers)
15829 (when combine
15830 (setq ical-file
15831 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
15832 org-combined-agenda-icalendar-file
15833 (expand-file-name org-combined-agenda-icalendar-file dir))
15834 ical-buffer (org-get-agenda-file-buffer ical-file))
15835 (set-buffer ical-buffer) (erase-buffer))
15836 (while (setq file (pop files))
15837 (catch 'nextfile
15838 (org-check-agenda-file file)
15839 (set-buffer (org-get-agenda-file-buffer file))
15840 (unless combine
15841 (setq ical-file (concat (file-name-as-directory dir)
15842 (file-name-sans-extension
15843 (file-name-nondirectory buffer-file-name))
15844 ".ics"))
15845 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
15846 (with-current-buffer ical-buffer (erase-buffer)))
15847 (setq category (or org-category
15848 (file-name-sans-extension
15849 (file-name-nondirectory buffer-file-name))))
15850 (if (symbolp category) (setq category (symbol-name category)))
15851 (let ((standard-output ical-buffer))
15852 (if combine
15853 (and (not started) (setq started t)
15854 (org-start-icalendar-file org-icalendar-combined-name))
15855 (org-start-icalendar-file category))
15856 (org-print-icalendar-entries combine category)
15857 (when (or (and combine (not files)) (not combine))
15858 (org-finish-icalendar-file)
15859 (set-buffer ical-buffer)
15860 (save-buffer)
15861 (run-hooks 'org-after-save-iCalendar-file-hook)))))
15862 (org-release-buffers org-agenda-new-buffers))))
15864 (defvar org-after-save-iCalendar-file-hook nil
15865 "Hook run after an iCalendar file has been saved.
15866 The iCalendar buffer is still current when this hook is run.
15867 A good way to use this is to tell a desktop calenndar application to re-read
15868 the iCalendar file.")
15870 (defun org-print-icalendar-entries (&optional combine category)
15871 "Print iCalendar entries for the current Org-mode file to `standard-output'.
15872 When COMBINE is non nil, add the category to each line."
15873 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
15874 (dts (org-ical-ts-to-string
15875 (format-time-string (cdr org-time-stamp-formats) (current-time))
15876 "DTSTART"))
15877 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
15878 (save-excursion
15879 (goto-char (point-min))
15880 (while (re-search-forward org-ts-regexp nil t)
15881 (setq pos (match-beginning 0)
15882 ts (match-string 0)
15883 inc t
15884 hd (org-get-heading))
15885 (if (looking-at re2)
15886 (progn
15887 (goto-char (match-end 0))
15888 (setq ts2 (match-string 1) inc nil))
15889 (setq ts2 ts
15890 tmp (buffer-substring (max (point-min)
15891 (- pos org-ds-keyword-length))
15892 pos)
15893 deadlinep (string-match org-deadline-regexp tmp)
15894 scheduledp (string-match org-scheduled-regexp tmp)
15895 ;; donep (org-entry-is-done-p)
15897 (if (or (string-match org-tr-regexp hd)
15898 (string-match org-ts-regexp hd))
15899 (setq hd (replace-match "" t t hd)))
15900 (if combine
15901 (setq hd (concat hd " (category " category ")")))
15902 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
15903 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
15904 (princ (format "BEGIN:VEVENT
15907 SUMMARY:%s
15908 END:VEVENT\n"
15909 (org-ical-ts-to-string ts "DTSTART")
15910 (org-ical-ts-to-string ts2 "DTEND" inc)
15911 hd)))
15912 (when org-icalendar-include-todo
15913 (goto-char (point-min))
15914 (while (re-search-forward org-todo-line-regexp nil t)
15915 (setq state (match-string 1))
15916 (unless (equal state org-done-string)
15917 (setq hd (match-string 3))
15918 (if (string-match org-priority-regexp hd)
15919 (setq pri (string-to-char (match-string 2 hd))
15920 hd (concat (substring hd 0 (match-beginning 1))
15921 (substring hd (- (match-end 1)))))
15922 (setq pri org-default-priority))
15923 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
15924 (- org-lowest-priority ?A))))))
15926 (princ (format "BEGIN:VTODO
15928 SUMMARY:%s
15929 SEQUENCE:1
15930 PRIORITY:%d
15931 END:VTODO\n"
15932 dts hd pri))))))))
15934 (defun org-start-icalendar-file (name)
15935 "Start an iCalendar file by inserting the header."
15936 (let ((user user-full-name)
15937 (name (or name "unknown"))
15938 (timezone (cadr (current-time-zone))))
15939 (princ
15940 (format "BEGIN:VCALENDAR
15941 VERSION:2.0
15942 X-WR-CALNAME:%s
15943 PRODID:-//%s//Emacs with Org-mode//EN
15944 X-WR-TIMEZONE:%s
15945 CALSCALE:GREGORIAN\n" name user timezone))))
15947 (defun org-finish-icalendar-file ()
15948 "Finish an iCalendar file by inserting the END statement."
15949 (princ "END:VCALENDAR\n"))
15951 (defun org-ical-ts-to-string (s keyword &optional inc)
15952 "Take a time string S and convert it to iCalendar format.
15953 KEYWORD is added in front, to make a complete line like DTSTART....
15954 When INC is non-nil, increase the hour by two (if time string contains
15955 a time), or the day by one (if it does not contain a time)."
15956 (let ((t1 (org-parse-time-string s 'nodefault))
15957 t2 fmt have-time time)
15958 (if (and (car t1) (nth 1 t1) (nth 2 t1))
15959 (setq t2 t1 have-time t)
15960 (setq t2 (org-parse-time-string s)))
15961 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
15962 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
15963 (when inc
15964 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
15965 (setq time (encode-time s mi h d m y)))
15966 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
15967 (concat keyword (format-time-string fmt time))))
15969 ;;; LaTeX stuff
15971 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15972 "Keymap for the minor `org-cdlatex-mode'.")
15974 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15975 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15976 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15977 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15978 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15980 (defvar org-cdlatex-texmathp-advice-is-done nil
15981 "Flag remembering if we have applied the advice to texmathp already.")
15983 (define-minor-mode org-cdlatex-mode
15984 "Toggle the minor `org-cdlatex-mode'.
15985 This mode supports entering LaTeX environment and math in LaTeX fragments
15986 in Org-mode.
15987 \\{org-cdlatex-mode-map}"
15988 nil " OCDL" nil
15989 (when org-cdlatex-mode (require 'cdlatex))
15990 (unless org-cdlatex-texmathp-advice-is-done
15991 (setq org-cdlatex-texmathp-advice-is-done t)
15992 (defadvice texmathp (around org-math-always-on activate)
15993 "Always return t in org-mode buffers.
15994 This is because we want to insert math symbols without dollars even outside
15995 the LaTeX math segments. If Orgmode thinks that point is actually inside
15996 en embedded LaTeX fragement, let texmathp do its job.
15997 \\[org-cdlatex-mode-map]"
15998 (interactive)
15999 (let (p)
16000 (cond
16001 ((not (org-mode-p)) ad-do-it)
16002 ((eq this-command 'cdlatex-math-symbol)
16003 (setq ad-return-value t
16004 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16006 (let ((p (org-inside-LaTeX-fragment-p)))
16007 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16008 (setq ad-return-value t
16009 texmathp-why '("Org-mode embedded math" . 0))
16010 (if p ad-do-it)))))))))
16012 (defun turn-on-org-cdlatex ()
16013 "Unconditionally turn on `org-cdlatex-mode'."
16014 (org-cdlatex-mode 1))
16016 (defun org-inside-LaTeX-fragment-p ()
16017 "Test if point is inside a LaTeX fragment.
16018 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16019 sequence appearing also before point.
16020 Even though the matchers for math are configurable, this function assumes
16021 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16022 delimiters are skipped when they have been removed by customization.
16023 The return value is nil, or a cons cell with the delimiter and
16024 and the position of this delimiter.
16026 This function does a reasonably good job, but can locally be fooled by
16027 for example currency specifications. For example it will assume being in
16028 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16029 fragments that are properly closed, but during editing, we have to live
16030 with the uncertainty caused by missing closing delimiters. This function
16031 looks only before point, not after."
16032 (catch 'exit
16033 (let ((pos (point))
16034 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16035 (lim (progn
16036 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16037 (point)))
16038 dd-on str (start 0) m re)
16039 (goto-char pos)
16040 (when dodollar
16041 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16042 re (nth 1 (assoc "$" org-latex-regexps)))
16043 (while (string-match re str start)
16044 (cond
16045 ((= (match-end 0) (length str))
16046 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16047 ((= (match-end 0) (- (length str) 5))
16048 (throw 'exit nil))
16049 (t (setq start (match-end 0))))))
16050 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16051 (goto-char pos)
16052 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16053 (and (match-beginning 2) (throw 'exit nil))
16054 ;; count $$
16055 (while (re-search-backward "\\$\\$" lim t)
16056 (setq dd-on (not dd-on)))
16057 (goto-char pos)
16058 (if dd-on (cons "$$" m))))))
16061 (defun org-try-cdlatex-tab ()
16062 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16063 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16064 - inside a LaTeX fragment, or
16065 - after the first word in a line, where an abbreviation expansion could
16066 insert a LaTeX environment."
16067 (when org-cdlatex-mode
16068 (cond
16069 ((save-excursion
16070 (skip-chars-backward "a-zA-Z0-9*")
16071 (skip-chars-backward " \t")
16072 (bolp))
16073 (cdlatex-tab) t)
16074 ((org-inside-LaTeX-fragment-p)
16075 (cdlatex-tab) t)
16076 (t nil))))
16078 (defun org-cdlatex-underscore-caret (&optional arg)
16079 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16080 Revert to the normal definition outside of these fragments."
16081 (interactive "P")
16082 (if (org-inside-LaTeX-fragment-p)
16083 (call-interactively 'cdlatex-sub-superscript)
16084 (let (org-cdlatex-mode)
16085 (call-interactively (key-binding (vector last-input-event))))))
16087 (defun org-cdlatex-math-modify (&optional arg)
16088 "Execute `cdlatex-math-modify' in LaTeX fragments.
16089 Revert to the normal definition outside of these fragments."
16090 (interactive "P")
16091 (if (org-inside-LaTeX-fragment-p)
16092 (call-interactively 'cdlatex-math-modify)
16093 (let (org-cdlatex-mode)
16094 (call-interactively (key-binding (vector last-input-event))))))
16096 (defvar org-latex-fragment-image-overlays nil
16097 "List of overlays carrying the images of latex fragments.")
16098 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16100 (defun org-remove-latex-fragment-image-overlays ()
16101 "Remove all overlays with LaTeX fragment images in current buffer."
16102 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16103 (setq org-latex-fragment-image-overlays nil))
16105 (defun org-preview-latex-fragment (&optional subtree)
16106 "Preview the LaTeX fragment at point, or all locally or globally.
16107 If the cursor is in a LaTeX fragment, create the image and overlay
16108 it over the source code. If there is no fragment at point, display
16109 all fragments in the current text, from one headline to the next. With
16110 prefix SUBTREE, display all fragments in the current subtree. With a
16111 double prefix `C-u C-u', or when the cursor is before the first headline,
16112 display all fragments in the buffer.
16113 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16114 (interactive "P")
16115 (org-remove-latex-fragment-image-overlays)
16116 (save-excursion
16117 (save-restriction
16118 (let (beg end at msg)
16119 (cond
16120 ((or (equal subtree '(16))
16121 (not (save-excursion
16122 (re-search-backward (concat "^" outline-regexp) nil t))))
16123 (setq beg (point-min) end (point-max)
16124 msg "Creating images for buffer...%s"))
16125 ((equal subtree '(4))
16126 (org-back-to-heading)
16127 (setq beg (point) end (org-end-of-subtree t)
16128 msg "Creating images for subtree...%s"))
16130 (if (setq at (org-inside-LaTeX-fragment-p))
16131 (goto-char (max (point-min) (- (cdr at) 2)))
16132 (org-back-to-heading))
16133 (setq beg (point) end (progn (outline-next-heading) (point))
16134 msg (if at "Creating image...%s"
16135 "Creating images for entry...%s"))))
16136 (message msg "")
16137 (narrow-to-region beg end)
16138 (org-format-latex
16139 (concat "ltxpng/" (file-name-sans-extension
16140 (file-name-nondirectory
16141 buffer-file-name)))
16142 default-directory 'overlays msg at)
16143 (message msg "done. Use `C-c C-c' to remove images.")))))
16145 (defvar org-latex-regexps
16146 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16147 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16148 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16149 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16150 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16151 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16152 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16153 "Regular expressions for matching embedded LaTeX.")
16155 (defun org-format-latex (prefix &optional dir overlays msg at)
16156 "Replace LaTeX fragments with links to an image, and produce images."
16157 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16158 (let* ((prefixnodir (file-name-nondirectory prefix))
16159 (absprefix (expand-file-name prefix dir))
16160 (todir (file-name-directory absprefix))
16161 (opt org-format-latex-options)
16162 (matchers (plist-get opt :matchers))
16163 (re-list org-latex-regexps)
16164 (cnt 0) txt link beg end re e oldfiles
16165 m n block linkfile movefile ov)
16166 ;; Make sure the directory exists
16167 (or (file-directory-p todir) (make-directory todir))
16168 ;; Check if there are old images files with this prefix, and remove them
16169 (setq oldfiles (directory-files
16170 todir 'full
16171 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
16172 (while oldfiles (delete-file (pop oldfiles)))
16173 ;; Check the different regular expressions
16174 (while (setq e (pop re-list))
16175 (setq m (car e) re (nth 1 e) n (nth 2 e)
16176 block (if (nth 3 e) "\n\n" ""))
16177 (when (member m matchers)
16178 (goto-char (point-min))
16179 (while (re-search-forward re nil t)
16180 (when (or (not at) (equal (cdr at) (match-beginning n)))
16181 (setq txt (match-string n)
16182 beg (match-beginning n) end (match-end n)
16183 cnt (1+ cnt)
16184 linkfile (format "%s_%04d.png" prefix cnt)
16185 movefile (format "%s_%04d.png" absprefix cnt)
16186 link (concat block "[[file:" linkfile "]]" block))
16187 (if msg (message msg cnt))
16188 (goto-char beg)
16189 (org-create-formula-image
16190 txt movefile opt)
16191 (if overlays
16192 (progn
16193 (setq ov (org-make-overlay beg end))
16194 (if (featurep 'xemacs)
16195 (progn
16196 (org-overlay-put ov 'invisible t)
16197 (org-overlay-put
16198 ov 'end-glyph
16199 (make-glyph (vector 'png :file movefile))))
16200 (org-overlay-put
16201 ov 'display
16202 (list 'image :type 'png :file movefile :ascent 'center)))
16203 (push ov org-latex-fragment-image-overlays)
16204 (goto-char end))
16205 (delete-region beg end)
16206 (insert link))))))))
16208 ;; This function borrows from Ganesh Swami's latex2png.el
16209 (defun org-create-formula-image (string tofile options)
16210 (let* ((tmpdir (if (featurep 'xemacs)
16211 (temp-directory)
16212 temporary-file-directory))
16213 (texfilebase (make-temp-name
16214 (expand-file-name "orgtex" tmpdir)))
16216 ;(texfilebase (make-temp-file "orgtex"))
16217 ; (dummy (delete-file texfilebase))
16218 (texfile (concat texfilebase ".tex"))
16219 (dvifile (concat texfilebase ".dvi"))
16220 (pngfile (concat texfilebase ".png"))
16221 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16222 (fg (or (plist-get options :foreground) "Black"))
16223 (bg (or (plist-get options :background) "Transparent")))
16224 (with-temp-file texfile
16225 (insert "\\documentclass{article}
16226 \\usepackage{fullpage}
16227 \\usepackage{amssymb}
16228 \\usepackage[usenames]{color}
16229 \\usepackage{amsmath}
16230 \\usepackage{latexsym}
16231 \\usepackage[mathscr]{eucal}
16232 \\pagestyle{empty}
16233 \\begin{document}\n" string "\n\\end{document}\n"))
16234 (let ((dir default-directory))
16235 (condition-case nil
16236 (progn
16237 (cd tmpdir)
16238 (call-process "latex" nil nil nil texfile))
16239 (error nil))
16240 (cd dir))
16241 (if (not (file-exists-p dvifile))
16242 (progn (message "Failed to create dvi file from %s" texfile) nil)
16243 (call-process "dvipng" nil nil nil
16244 "-E" "-fg" fg "-bg" bg
16245 "-x" scale "-y" scale "-T" "tight"
16246 "-o" pngfile
16247 dvifile)
16248 (if (not (file-exists-p pngfile))
16249 (progn (message "Failed to create png file from %s" texfile) nil)
16250 ;; Use the requested file name and clean up
16251 (copy-file pngfile tofile 'replace)
16252 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16253 (delete-file (concat texfilebase e)))
16254 pngfile))))
16256 ;;; Key bindings
16258 ;; - Bindings in Org-mode map are currently
16259 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
16260 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
16261 ;; e (?) useful from outline-mode
16262 ;; i k @ expendable from outline-mode
16263 ;; 0123456789 % & ()_{} " ` free
16265 ;; Make `C-c C-x' a prefix key
16266 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
16268 ;; TAB key with modifiers
16269 (define-key org-mode-map "\C-i" 'org-cycle)
16270 (define-key org-mode-map [(tab)] 'org-cycle)
16271 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
16272 (define-key org-mode-map [(meta tab)] 'org-complete)
16273 ;; The following line is necessary under Suse GNU/Linux
16274 (unless (featurep 'xemacs)
16275 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
16276 (define-key org-mode-map [(shift tab)] 'org-shifttab)
16278 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
16279 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16280 (define-key org-mode-map [(meta return)] 'org-meta-return)
16282 ;; Cursor keys with modifiers
16283 (define-key org-mode-map [(meta left)] 'org-metaleft)
16284 (define-key org-mode-map [(meta right)] 'org-metaright)
16285 (define-key org-mode-map [(meta up)] 'org-metaup)
16286 (define-key org-mode-map [(meta down)] 'org-metadown)
16288 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16289 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
16290 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
16291 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
16293 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
16294 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
16295 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
16296 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
16298 ;; Extra keys for tty access. We only set them when really needed
16299 ;; because otherwise the menus don't show the simple keys
16301 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16302 (not window-system))
16303 (define-key org-mode-map "\M-\C-i" 'org-complete)
16304 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16305 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16306 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
16307 (define-key org-mode-map [?\e (return)] 'org-meta-return)
16308 (define-key org-mode-map [?\e (left)] 'org-metaleft)
16309 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
16310 (define-key org-mode-map [?\e (right)] 'org-metaright)
16311 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
16312 (define-key org-mode-map [?\e (up)] 'org-metaup)
16313 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
16314 (define-key org-mode-map [?\e (down)] 'org-metadown)
16315 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
16316 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16317 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16318 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16319 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16320 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
16321 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
16322 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
16323 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
16325 ;; All the other keys
16327 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16328 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
16329 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
16330 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
16331 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
16332 (define-key org-mode-map "\C-c\C-j" 'org-goto)
16333 (define-key org-mode-map "\C-c\C-t" 'org-todo)
16334 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
16335 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
16336 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
16337 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
16338 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
16339 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
16340 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
16341 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
16342 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
16343 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
16344 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
16345 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
16346 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
16347 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
16348 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16349 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16350 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16351 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16352 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
16353 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
16354 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16355 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
16356 (define-key org-mode-map "\C-c]" 'org-remove-file)
16357 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
16358 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
16359 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16360 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
16361 (define-key org-mode-map "\C-m" 'org-return)
16362 (define-key org-mode-map "\C-c?" 'org-table-current-column)
16363 (define-key org-mode-map "\C-c " 'org-table-blank-field)
16364 (define-key org-mode-map "\C-c+" 'org-table-sum)
16365 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
16366 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
16367 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
16368 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16369 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
16370 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16371 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
16372 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
16373 (define-key org-mode-map "\C-c\C-e" 'org-export)
16374 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16376 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
16377 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16378 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16379 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16381 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16382 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16383 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16384 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16385 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16386 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16387 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16388 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16389 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16391 (when (featurep 'xemacs)
16392 (define-key org-mode-map 'button3 'popup-mode-menu))
16394 (defsubst org-table-p () (org-at-table-p))
16396 (defun org-self-insert-command (N)
16397 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16398 If the cursor is in a table looking at whitespace, the whitespace is
16399 overwritten, and the table is not marked as requiring realignment."
16400 (interactive "p")
16401 (if (and (org-table-p)
16402 (progn
16403 ;; check if we blank the field, and if that triggers align
16404 (and org-table-auto-blank-field
16405 (member last-command
16406 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
16407 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16408 ;; got extra space, this field does not determine column width
16409 (let (org-table-may-need-update) (org-table-blank-field))
16410 ;; no extra space, this field may determine column width
16411 (org-table-blank-field)))
16413 (eq N 1)
16414 (looking-at "[^|\n]* |"))
16415 (let (org-table-may-need-update)
16416 (goto-char (1- (match-end 0)))
16417 (delete-backward-char 1)
16418 (goto-char (match-beginning 0))
16419 (self-insert-command N))
16420 (setq org-table-may-need-update t)
16421 (self-insert-command N)))
16423 (defun org-delete-backward-char (N)
16424 "Like `delete-backward-char', insert whitespace at field end in tables.
16425 When deleting backwards, in tables this function will insert whitespace in
16426 front of the next \"|\" separator, to keep the table aligned. The table will
16427 still be marked for re-alignment if the field did fill the entire column,
16428 because, in this case the deletion might narrow the column."
16429 (interactive "p")
16430 (if (and (org-table-p)
16431 (eq N 1)
16432 (string-match "|" (buffer-substring (point-at-bol) (point)))
16433 (looking-at ".*?|"))
16434 (let ((pos (point))
16435 (noalign (looking-at "[^|\n\r]* |"))
16436 (c org-table-may-need-update))
16437 (backward-delete-char N)
16438 (skip-chars-forward "^|")
16439 (insert " ")
16440 (goto-char (1- pos))
16441 ;; noalign: if there were two spaces at the end, this field
16442 ;; does not determine the width of the column.
16443 (if noalign (setq org-table-may-need-update c)))
16444 (backward-delete-char N)))
16446 (defun org-delete-char (N)
16447 "Like `delete-char', but insert whitespace at field end in tables.
16448 When deleting characters, in tables this function will insert whitespace in
16449 front of the next \"|\" separator, to keep the table aligned. The table will
16450 still be marked for re-alignment if the field did fill the entire column,
16451 because, in this case the deletion might narrow the column."
16452 (interactive "p")
16453 (if (and (org-table-p)
16454 (not (bolp))
16455 (not (= (char-after) ?|))
16456 (eq N 1))
16457 (if (looking-at ".*?|")
16458 (let ((pos (point))
16459 (noalign (looking-at "[^|\n\r]* |"))
16460 (c org-table-may-need-update))
16461 (replace-match (concat
16462 (substring (match-string 0) 1 -1)
16463 " |"))
16464 (goto-char pos)
16465 ;; noalign: if there were two spaces at the end, this field
16466 ;; does not determine the width of the column.
16467 (if noalign (setq org-table-may-need-update c)))
16468 (delete-char N))
16469 (delete-char N)))
16471 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16472 (put 'org-self-insert-command 'delete-selection t)
16473 (put 'orgtbl-self-insert-command 'delete-selection t)
16474 (put 'org-delete-char 'delete-selection 'supersede)
16475 (put 'org-delete-backward-char 'delete-selection 'supersede)
16477 ;; How to do this: Measure non-white length of current string
16478 ;; If equal to column width, we should realign.
16480 (defun org-remap (map &rest commands)
16481 "In MAP, remap the functions given in COMMANDS.
16482 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16483 (let (new old)
16484 (while commands
16485 (setq old (pop commands) new (pop commands))
16486 (if (fboundp 'command-remapping)
16487 (define-key map (vector 'remap old) new)
16488 (substitute-key-definition old new map global-map)))))
16490 (when (eq org-enable-table-editor 'optimized)
16491 ;; If the user wants maximum table support, we need to hijack
16492 ;; some standard editing functions
16493 (org-remap org-mode-map
16494 'self-insert-command 'org-self-insert-command
16495 'delete-char 'org-delete-char
16496 'delete-backward-char 'org-delete-backward-char)
16497 (define-key org-mode-map "|" 'org-force-self-insert))
16499 (defun org-shiftcursor-error ()
16500 "Throw an error because Shift-Cursor command was applied in wrong context."
16501 (error "This command is active in special context like tables, headlines or timestamps"))
16503 (defun org-shifttab (&optional arg)
16504 "Global visibility cycling or move to previous table field.
16505 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16506 on context.
16507 See the individual commands for more information."
16508 (interactive "P")
16509 (cond
16510 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16511 (t (call-interactively 'org-global-cycle))))
16513 (defun org-shiftmetaleft ()
16514 "Promote subtree or delete table column.
16515 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
16516 See the individual commands for more information."
16517 (interactive)
16518 (cond
16519 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16520 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16521 ((org-at-item-p) (call-interactively 'org-outdent-item))
16522 (t (org-shiftcursor-error))))
16524 (defun org-shiftmetaright ()
16525 "Demote subtree or insert table column.
16526 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
16527 See the individual commands for more information."
16528 (interactive)
16529 (cond
16530 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16531 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16532 ((org-at-item-p) (call-interactively 'org-indent-item))
16533 (t (org-shiftcursor-error))))
16535 (defun org-shiftmetaup (&optional arg)
16536 "Move subtree up or kill table row.
16537 Calls `org-move-subtree-up' or `org-table-kill-row' or
16538 `org-move-item-up' depending on context. See the individual commands
16539 for more information."
16540 (interactive "P")
16541 (cond
16542 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16543 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16544 ((org-at-item-p) (call-interactively 'org-move-item-up))
16545 (t (org-shiftcursor-error))))
16546 (defun org-shiftmetadown (&optional arg)
16547 "Move subtree down or insert table row.
16548 Calls `org-move-subtree-down' or `org-table-insert-row' or
16549 `org-move-item-down', depending on context. See the individual
16550 commands for more information."
16551 (interactive "P")
16552 (cond
16553 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16554 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16555 ((org-at-item-p) (call-interactively 'org-move-item-down))
16556 (t (org-shiftcursor-error))))
16558 (defun org-metaleft (&optional arg)
16559 "Promote heading or move table column to left.
16560 Calls `org-do-promote' or `org-table-move-column', depending on context.
16561 With no specific context, calls the Emacs default `backward-word'.
16562 See the individual commands for more information."
16563 (interactive "P")
16564 (cond
16565 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16566 ((or (org-on-heading-p) (org-region-active-p))
16567 (call-interactively 'org-do-promote))
16568 ((org-at-item-p) (call-interactively 'org-outdent-item))
16569 (t (call-interactively 'backward-word))))
16571 (defun org-metaright (&optional arg)
16572 "Demote subtree or move table column to right.
16573 Calls `org-do-demote' or `org-table-move-column', depending on context.
16574 With no specific context, calls the Emacs default `forward-word'.
16575 See the individual commands for more information."
16576 (interactive "P")
16577 (cond
16578 ((org-at-table-p) (call-interactively 'org-table-move-column))
16579 ((or (org-on-heading-p) (org-region-active-p))
16580 (call-interactively 'org-do-demote))
16581 ((org-at-item-p) (call-interactively 'org-indent-item))
16582 (t (call-interactively 'forward-word))))
16584 (defun org-metaup (&optional arg)
16585 "Move subtree up or move table row up.
16586 Calls `org-move-subtree-up' or `org-table-move-row' or
16587 `org-move-item-up', depending on context. See the individual commands
16588 for more information."
16589 (interactive "P")
16590 (cond
16591 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16592 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16593 ((org-at-item-p) (call-interactively 'org-move-item-up))
16594 (t (org-shiftcursor-error))))
16596 (defun org-metadown (&optional arg)
16597 "Move subtree down or move table row down.
16598 Calls `org-move-subtree-down' or `org-table-move-row' or
16599 `org-move-item-down', depending on context. See the individual
16600 commands for more information."
16601 (interactive "P")
16602 (cond
16603 ((org-at-table-p) (call-interactively 'org-table-move-row))
16604 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16605 ((org-at-item-p) (call-interactively 'org-move-item-down))
16606 (t (org-shiftcursor-error))))
16608 (defun org-shiftup (&optional arg)
16609 "Increase item in timestamp or increase priority of current headline.
16610 Calls `org-timestamp-up' or `org-priority-up', depending on context.
16611 See the individual commands for more information."
16612 (interactive "P")
16613 (cond
16614 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
16615 ((org-on-heading-p) (call-interactively 'org-priority-up))
16616 ((org-at-item-p) (call-interactively 'org-previous-item))
16617 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
16619 (defun org-shiftdown (&optional arg)
16620 "Decrease item in timestamp or decrease priority of current headline.
16621 Calls `org-timestamp-down' or `org-priority-down', depending on context.
16622 See the individual commands for more information."
16623 (interactive "P")
16624 (cond
16625 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
16626 ((org-on-heading-p) (call-interactively 'org-priority-down))
16627 (t (call-interactively 'org-next-item))))
16629 (defun org-shiftright ()
16630 "Next TODO keyword or timestamp one day later, depending on context."
16631 (interactive)
16632 (cond
16633 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16634 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
16635 (t (org-shiftcursor-error))))
16637 (defun org-shiftleft ()
16638 "Previous TODO keyword or timestamp one day earlier, depending on context."
16639 (interactive)
16640 (cond
16641 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16642 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
16643 (t (org-shiftcursor-error))))
16645 (defun org-copy-special ()
16646 "Copy region in table or copy current subtree.
16647 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16648 See the individual commands for more information."
16649 (interactive)
16650 (call-interactively
16651 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16653 (defun org-cut-special ()
16654 "Cut region in table or cut current subtree.
16655 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16656 See the individual commands for more information."
16657 (interactive)
16658 (call-interactively
16659 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16661 (defun org-paste-special (arg)
16662 "Paste rectangular region into table, or past subtree relative to level.
16663 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16664 See the individual commands for more information."
16665 (interactive "P")
16666 (if (org-at-table-p)
16667 (org-table-paste-rectangle)
16668 (org-paste-subtree arg)))
16670 (defun org-ctrl-c-ctrl-c (&optional arg)
16671 "Set tags in headline, or update according to changed information at point.
16673 This command does many different things, depending on context:
16675 - If the cursor is in a headline, prompt for tags and insert them
16676 into the current line, aligned to `org-tags-column'. When called
16677 with prefix arg, realign all tags in the current buffer.
16679 - If the cursor is in one of the special #+KEYWORD lines, this
16680 triggers scanning the buffer for these lines and updating the
16681 information.
16683 - If the cursor is inside a table, realign the table. This command
16684 works even if the automatic table editor has been turned off.
16686 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16687 the entire table.
16689 - If the cursor is inside a table created by the table.el package,
16690 activate that table.
16692 - If the current buffer is a remember buffer, close note and file it.
16693 with a prefix argument, file it without further interaction to the default
16694 location.
16696 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16697 links in this buffer.
16699 - If the cursor is on a numbered item in a plain list, renumber the
16700 ordered list."
16701 (interactive "P")
16702 (let ((org-enable-table-editor t))
16703 (cond
16704 ((or org-clock-overlays
16705 org-occur-highlights
16706 org-latex-fragment-image-overlays)
16707 (org-remove-clock-overlays)
16708 (org-remove-occur-highlights)
16709 (org-remove-latex-fragment-image-overlays)
16710 (message "Temporary highlights/overlays removed from current buffer"))
16711 ((and (local-variable-p 'org-finish-function (current-buffer))
16712 (fboundp org-finish-function))
16713 (funcall org-finish-function))
16714 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16715 ((org-on-heading-p) (call-interactively 'org-set-tags))
16716 ((org-at-table.el-p)
16717 (require 'table)
16718 (beginning-of-line 1)
16719 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
16720 (call-interactively 'table-recognize-table))
16721 ((org-at-table-p)
16722 (org-table-maybe-eval-formula)
16723 (if arg
16724 (call-interactively 'org-table-recalculate)
16725 (org-table-maybe-recalculate-line))
16726 (call-interactively 'org-table-align))
16727 ((org-at-item-checkbox-p)
16728 (call-interactively 'org-toggle-checkbox))
16729 ((org-at-item-p)
16730 (call-interactively 'org-renumber-ordered-list))
16731 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
16732 (cond
16733 ((equal (match-string 1) "TBLFM")
16734 ;; Recalculate the table before this line
16735 (save-excursion
16736 (beginning-of-line 1)
16737 (skip-chars-backward " \r\n\t")
16738 (if (org-at-table-p)
16739 (org-call-with-arg 'org-table-recalculate t))))
16741 (call-interactively 'org-mode-restart))))
16742 (t (error "C-c C-c can do nothing useful at this location.")))))
16744 (defun org-mode-restart ()
16745 "Restart Org-mode, to scan again for special lines.
16746 Also updates the keyword regular expressions."
16747 (interactive)
16748 (let ((org-inhibit-startup t)) (org-mode))
16749 (message "Org-mode restarted to refresh keyword and special line setup"))
16751 (defun org-return ()
16752 "Goto next table row or insert a newline.
16753 Calls `org-table-next-row' or `newline', depending on context.
16754 See the individual commands for more information."
16755 (interactive)
16756 (cond
16757 ((org-at-table-p)
16758 (org-table-justify-field-maybe)
16759 (call-interactively 'org-table-next-row))
16760 (t (newline))))
16762 (defun org-meta-return (&optional arg)
16763 "Insert a new heading or wrap a region in a table.
16764 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16765 See the individual commands for more information."
16766 (interactive "P")
16767 (cond
16768 ((org-at-table-p)
16769 (call-interactively 'org-table-wrap-region))
16770 (t (call-interactively 'org-insert-heading))))
16772 ;;; Menu entries
16774 ;; Define the Org-mode menus
16775 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16776 '("Tbl"
16777 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
16778 ["Next Field" org-cycle (org-at-table-p)]
16779 ["Previous Field" org-shifttab (org-at-table-p)]
16780 ["Next Row" org-return (org-at-table-p)]
16781 "--"
16782 ["Blank Field" org-table-blank-field (org-at-table-p)]
16783 ["Edit Field" org-table-edit-field (org-at-table-p)]
16784 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16785 "--"
16786 ("Column"
16787 ["Move Column Left" org-metaleft (org-at-table-p)]
16788 ["Move Column Right" org-metaright (org-at-table-p)]
16789 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16790 ["Insert Column" org-shiftmetaright (org-at-table-p)]
16791 "--"
16792 ["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])
16793 ("Row"
16794 ["Move Row Up" org-metaup (org-at-table-p)]
16795 ["Move Row Down" org-metadown (org-at-table-p)]
16796 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16797 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16798 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16799 "--"
16800 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
16801 ("Rectangle"
16802 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16803 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16804 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16805 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16806 "--"
16807 ("Calculate"
16808 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16809 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16810 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
16811 "--"
16812 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16813 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16814 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16815 "--"
16816 ["Sum Column/Rectangle" org-table-sum
16817 (or (org-at-table-p) (org-region-active-p))]
16818 ["Which Column?" org-table-current-column (org-at-table-p)])
16819 ["Debug Formulas"
16820 (setq org-table-formula-debug (not org-table-formula-debug))
16821 :style toggle :selected org-table-formula-debug]
16822 "--"
16823 ["Create" org-table-create (and (not (org-at-table-p))
16824 org-enable-table-editor)]
16825 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16826 ["Import from File" org-table-import (not (org-at-table-p))]
16827 ["Export to File" org-table-export (org-at-table-p)]
16828 "--"
16829 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16831 (easy-menu-define org-org-menu org-mode-map "Org menu"
16832 '("Org"
16833 ("Show/Hide"
16834 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
16835 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
16836 ["Sparse Tree" org-occur t]
16837 ["Reveal Context" org-reveal t]
16838 ["Show All" show-all t])
16839 "--"
16840 ["New Heading" org-insert-heading t]
16841 ("Navigate Headings"
16842 ["Up" outline-up-heading t]
16843 ["Next" outline-next-visible-heading t]
16844 ["Previous" outline-previous-visible-heading t]
16845 ["Next Same Level" outline-forward-same-level t]
16846 ["Previous Same Level" outline-backward-same-level t]
16847 "--"
16848 ["Jump" org-goto t])
16849 ("Edit Structure"
16850 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16851 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16852 "--"
16853 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16854 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16855 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16856 "--"
16857 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16858 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16859 ["Demote Heading" org-metaright (not (org-at-table-p))]
16860 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16861 "--"
16862 ["Convert to odd levels" org-convert-to-odd-levels t]
16863 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16864 ("Archive"
16865 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16866 ["Check and Tag Children" (org-toggle-archive-tag (4))
16867 :active t :keys "C-u C-c C-x C-a"]
16868 ["Sparse trees open ARCHIVE trees"
16869 (setq org-sparse-tree-open-archived-trees
16870 (not org-sparse-tree-open-archived-trees))
16871 :style toggle :selected org-sparse-tree-open-archived-trees]
16872 ["Cycling opens ARCHIVE trees"
16873 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
16874 :style toggle :selected org-cycle-open-archived-trees]
16875 ["Agenda includes ARCHIVE trees"
16876 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
16877 :style toggle :selected (not org-agenda-skip-archived-trees)]
16878 "--"
16879 ["Move Subtree to Archive" org-archive-subtree t]
16880 ["Check and Move Children" (org-archive-subtree '(4))
16881 :active t :keys "C-u C-c $"])
16882 "--"
16883 ("TODO Lists"
16884 ["TODO/DONE/-" org-todo t]
16885 ("Select keyword"
16886 ["Next keyword" org-shiftright (org-on-heading-p)]
16887 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16888 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
16889 ["Show TODO Tree" org-show-todo-tree t]
16890 ["Global TODO list" org-todo-list t]
16891 "--"
16892 ["Set Priority" org-priority t]
16893 ["Priority Up" org-shiftup t]
16894 ["Priority Down" org-shiftdown t]
16895 "--"
16896 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
16897 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
16898 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
16899 ; (or (org-on-heading-p) (org-at-item-p))]
16900 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
16901 ; (or (org-on-heading-p) (org-at-item-p))]
16902 ; ["Update Statistics" org-update-checkbox-count t]
16904 ("Dates and Scheduling"
16905 ["Timestamp" org-time-stamp t]
16906 ["Timestamp (inactive)" org-time-stamp-inactive t]
16907 ("Change Date"
16908 ["1 Day Later" org-shiftright t]
16909 ["1 Day Earlier" org-shiftleft t]
16910 ["1 ... Later" org-shiftup t]
16911 ["1 ... Earlier" org-shiftdown t])
16912 ["Compute Time Range" org-evaluate-time-range t]
16913 ["Schedule Item" org-schedule t]
16914 ["Deadline" org-deadline t]
16915 "--"
16916 ["Custom time format" org-toggle-time-stamp-overlays
16917 :style radio :selected org-display-custom-times]
16918 "--"
16919 ["Goto Calendar" org-goto-calendar t]
16920 ["Date from Calendar" org-date-from-calendar t])
16921 ("Logging work"
16922 ["Clock in" org-clock-in t]
16923 ["Clock out" org-clock-out t]
16924 ["Clock cancel" org-clock-cancel t]
16925 ["Display times" org-clock-display t]
16926 ["Create clock table" org-clock-report t]
16927 "--"
16928 ["Record DONE time"
16929 (progn (setq org-log-done (not org-log-done))
16930 (message "Switching to %s will %s record a timestamp"
16931 org-done-string
16932 (if org-log-done "automatically" "not")))
16933 :style toggle :selected org-log-done])
16934 "--"
16935 ["Agenda Command..." org-agenda t]
16936 ("File List for Agenda")
16937 ("Special views current file"
16938 ["TODO Tree" org-show-todo-tree t]
16939 ["Check Deadlines" org-check-deadlines t]
16940 ["Timeline" org-timeline t]
16941 ["Tags Tree" org-tags-sparse-tree t])
16942 "--"
16943 ("Hyperlinks"
16944 ["Store Link (Global)" org-store-link t]
16945 ["Insert Link" org-insert-link t]
16946 ["Follow Link" org-open-at-point t]
16947 "--"
16948 ["Descriptive Links"
16949 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16950 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
16951 ["Literal Links"
16952 (progn
16953 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16954 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
16955 "--"
16956 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
16957 (save-excursion (goto-char (point-min))
16958 (re-search-forward "<[a-z]+:" nil t))])
16959 "--"
16960 ["Export/Publish..." org-export t]
16961 ("LaTeX"
16962 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16963 :selected org-cdlatex-mode]
16964 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16965 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16966 ["Modify math symbol" org-cdlatex-math-modify
16967 (org-inside-LaTeX-fragment-p)]
16968 ["Export LaTeX fragments as images"
16969 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
16970 :style toggle :selected org-export-with-LaTeX-fragments])
16971 "--"
16972 ("Documentation"
16973 ["Show Version" org-version t]
16974 ["Info Documentation" org-info t])
16975 ("Customize"
16976 ["Browse Org Group" org-customize t]
16977 "--"
16978 ["Expand This Menu" org-create-customize-menu
16979 (fboundp 'customize-menu-create)])
16980 "--"
16981 ["Refresh setup" org-mode-restart t]
16984 (defun org-info (&optional node)
16985 "Read documentation for Org-mode in the info system.
16986 With optional NODE, go directly to that node."
16987 (interactive)
16988 (require 'info)
16989 (Info-goto-node (format "(org)%s" (or node ""))))
16991 (defun org-install-agenda-files-menu ()
16992 (let ((bl (buffer-list)))
16993 (save-excursion
16994 (while bl
16995 (set-buffer (pop bl))
16996 (if (org-mode-p) (setq bl nil)))
16997 (when (org-mode-p)
16998 (easy-menu-change
16999 '("Org") "File List for Agenda"
17000 (append
17001 (list
17002 ["Edit File List" (org-edit-agenda-file-list) t]
17003 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17004 ["Remove Current File from List" org-remove-file t]
17005 ["Cycle through agenda files" org-cycle-agenda-files t]
17006 "--")
17007 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17009 ;;; Documentation
17011 (defun org-customize ()
17012 "Call the customize function with org as argument."
17013 (interactive)
17014 (customize-browse 'org))
17016 (defun org-create-customize-menu ()
17017 "Create a full customization menu for Org-mode, insert it into the menu."
17018 (interactive)
17019 (if (fboundp 'customize-menu-create)
17020 (progn
17021 (easy-menu-change
17022 '("Org") "Customize"
17023 `(["Browse Org group" org-customize t]
17024 "--"
17025 ,(customize-menu-create 'org)
17026 ["Set" Custom-set t]
17027 ["Save" Custom-save t]
17028 ["Reset to Current" Custom-reset-current t]
17029 ["Reset to Saved" Custom-reset-saved t]
17030 ["Reset to Standard Settings" Custom-reset-standard t]))
17031 (message "\"Org\"-menu now contains full customization menu"))
17032 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17034 ;;; Miscellaneous stuff
17036 (defun org-context ()
17037 "Return a list of contexts of the current cursor position.
17038 If several contexts apply, all are returned.
17039 Each context entry is a list with a symbol naming the context, and
17040 two positions indicating start and end of the context. Possible
17041 contexts are:
17043 :headline anywhere in a headline
17044 :headline-stars on the leading stars in a headline
17045 :todo-keyword on a TODO keyword (including DONE) in a headline
17046 :tags on the TAGS in a headline
17047 :priority on the priority cookie in a headline
17048 :item on the first line of a plain list item
17049 :item-bullet on the bullet/number of a plain list item
17050 :checkbox on the checkbox in a plain list item
17051 :table in an org-mode table
17052 :table-special on a special filed in a table
17053 :table-table in a table.el table
17054 :link on a hyperline
17055 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17056 :target on a <<target>>
17057 :radio-target on a <<<radio-target>>>
17058 :latex-fragment on a LaTeX fragment
17059 :latex-preview on a LaTeX fragment with overlayed preview image
17061 This function expects the position to be visible because it uses font-lock
17062 faces as a help to recognize the following contexts: :table-special, :link,
17063 and :keyword."
17064 (let* ((f (get-text-property (point) 'face))
17065 (faces (if (listp f) f (list f)))
17066 (p (point)) clist o)
17067 ;; First the large context
17068 (cond
17069 ((org-on-heading-p)
17070 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17071 (when (progn
17072 (beginning-of-line 1)
17073 (looking-at org-todo-line-tags-regexp))
17074 (push (org-point-in-group p 1 :headline-stars) clist)
17075 (push (org-point-in-group p 2 :todo-keyword) clist)
17076 (push (org-point-in-group p 4 :tags) clist))
17077 (goto-char p)
17078 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
17079 (if (looking-at "\\[#[A-Z]\\]")
17080 (push (org-point-in-group p 0 :priority) clist)))
17082 ((org-at-item-p)
17083 (push (org-point-in-group p 2 :item-bullet) clist)
17084 (push (list :item (point-at-bol)
17085 (save-excursion (org-end-of-item) (point)))
17086 clist)
17087 (and (org-at-item-checkbox-p)
17088 (push (org-point-in-group p 0 :checkbox) clist)))
17090 ((org-at-table-p)
17091 (push (list :table (org-table-begin) (org-table-end)) clist)
17092 (if (memq 'org-formula faces)
17093 (push (list :table-special
17094 (previous-single-property-change p 'face)
17095 (next-single-property-change p 'face)) clist)))
17096 ((org-at-table-p 'any)
17097 (push (list :table-table) clist)))
17098 (goto-char p)
17100 ;; Now the small context
17101 (cond
17102 ((org-at-timestamp-p)
17103 (push (org-point-in-group p 0 :timestamp) clist))
17104 ((memq 'org-link faces)
17105 (push (list :link
17106 (previous-single-property-change p 'face)
17107 (next-single-property-change p 'face)) clist))
17108 ((memq 'org-special-keyword faces)
17109 (push (list :keyword
17110 (previous-single-property-change p 'face)
17111 (next-single-property-change p 'face)) clist))
17112 ((org-on-target-p)
17113 (push (org-point-in-group p 0 :target) clist)
17114 (goto-char (1- (match-beginning 0)))
17115 (if (looking-at org-radio-target-regexp)
17116 (push (org-point-in-group p 0 :radio-target) clist))
17117 (goto-char p))
17118 ((setq o (car (delq nil
17119 (mapcar
17120 (lambda (x)
17121 (if (memq x org-latex-fragment-image-overlays) x))
17122 (org-overlays-at (point))))))
17123 (push (list :latex-fragment
17124 (org-overlay-start o) (org-overlay-end o)) clist)
17125 (push (list :latex-preview
17126 (org-overlay-start o) (org-overlay-end o)) clist))
17127 ((org-inside-LaTeX-fragment-p)
17128 ;; FIXME: positions wrong.
17129 (push (list :latex-fragment (point) (point)) clist)))
17131 (setq clist (nreverse (delq nil clist)))
17132 clist))
17134 (defun org-point-in-group (point group &optional context)
17135 "Check if POINT is in match-group GROUP.
17136 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17137 match. If the match group does ot exist or point is not inside it,
17138 return nil."
17139 (and (match-beginning group)
17140 (>= point (match-beginning group))
17141 (<= point (match-end group))
17142 (if context
17143 (list context (match-beginning group) (match-end group))
17144 t)))
17146 (defun org-move-line-down (arg)
17147 "Move the current line down. With prefix argument, move it past ARG lines."
17148 (interactive "p")
17149 (let ((col (current-column))
17150 beg end pos)
17151 (beginning-of-line 1) (setq beg (point))
17152 (beginning-of-line 2) (setq end (point))
17153 (beginning-of-line (+ 1 arg))
17154 (setq pos (move-marker (make-marker) (point)))
17155 (insert (delete-and-extract-region beg end))
17156 (goto-char pos)
17157 (move-to-column col)))
17159 (defun org-move-line-up (arg)
17160 "Move the current line up. With prefix argument, move it past ARG lines."
17161 (interactive "p")
17162 (let ((col (current-column))
17163 beg end pos)
17164 (beginning-of-line 1) (setq beg (point))
17165 (beginning-of-line 2) (setq end (point))
17166 (beginning-of-line (- arg))
17167 (setq pos (move-marker (make-marker) (point)))
17168 (insert (delete-and-extract-region beg end))
17169 (goto-char pos)
17170 (move-to-column col)))
17172 ;; Paragraph filling stuff.
17173 ;; We want this to be just right, so use the full arsenal.
17175 (defun org-set-autofill-regexps ()
17176 (interactive)
17177 ;; In the paragraph separator we include headlines, because filling
17178 ;; text in a line directly attached to a headline would otherwise
17179 ;; fill the headline as well.
17180 (org-set-local 'comment-start-skip "^#+[ \t]*")
17181 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
17182 ;; The paragraph starter includes hand-formatted lists.
17183 (org-set-local 'paragraph-start
17184 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
17185 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17186 ;; But only if the user has not turned off tables or fixed-width regions
17187 (org-set-local
17188 'auto-fill-inhibit-regexp
17189 (concat "\\*\\|#"
17190 "\\|[ \t]*" org-keyword-time-regexp
17191 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17192 (concat
17193 "\\|[ \t]*["
17194 (if org-enable-table-editor "|" "")
17195 (if org-enable-fixed-width-editor ":" "")
17196 "]"))))
17197 ;; We use our own fill-paragraph function, to make sure that tables
17198 ;; and fixed-width regions are not wrapped. That function will pass
17199 ;; through to `fill-paragraph' when appropriate.
17200 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17201 ; Adaptive filling: To get full control, first make sure that
17202 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17203 (org-set-local 'adaptive-fill-regexp "\000")
17204 (org-set-local 'adaptive-fill-function
17205 'org-adaptive-fill-function))
17207 (defun org-fill-paragraph (&optional justify)
17208 "Re-align a table, pass through to fill-paragraph if no table."
17209 (let ((table-p (org-at-table-p))
17210 (table.el-p (org-at-table.el-p)))
17211 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
17212 (table.el-p t) ; skip table.el tables
17213 (table-p (org-table-align) t) ; align org-mode tables
17214 (t nil)))) ; call paragraph-fill
17216 ;; For reference, this is the default value of adaptive-fill-regexp
17217 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17219 (defun org-adaptive-fill-function ()
17220 "Return a fill prefix for org-mode files.
17221 In particular, this makes sure hanging paragraphs for hand-formatted lists
17222 work correctly."
17223 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
17224 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
17226 ;; Functions needed for Emacs/XEmacs region compatibility
17228 (defun org-add-hook (hook function &optional append local)
17229 "Add-hook, compatible with both Emacsen."
17230 (if (and local (featurep 'xemacs))
17231 (add-local-hook hook function append)
17232 (add-hook hook function append local)))
17234 (defun org-region-active-p ()
17235 "Is `transient-mark-mode' on and the region active?
17236 Works on both Emacs and XEmacs."
17237 (if org-ignore-region
17239 (if (featurep 'xemacs)
17240 (and zmacs-regions (region-active-p))
17241 (and transient-mark-mode mark-active))))
17243 (defun org-add-to-invisibility-spec (arg)
17244 "Add elements to `buffer-invisibility-spec'.
17245 See documentation for `buffer-invisibility-spec' for the kind of elements
17246 that can be added."
17247 (cond
17248 ((fboundp 'add-to-invisibility-spec)
17249 (add-to-invisibility-spec arg))
17250 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
17251 (setq buffer-invisibility-spec (list arg)))
17253 (setq buffer-invisibility-spec
17254 (cons arg buffer-invisibility-spec)))))
17256 (defun org-remove-from-invisibility-spec (arg)
17257 "Remove elements from `buffer-invisibility-spec'."
17258 (if (fboundp 'remove-from-invisibility-spec)
17259 (remove-from-invisibility-spec arg)
17260 (if (consp buffer-invisibility-spec)
17261 (setq buffer-invisibility-spec
17262 (delete arg buffer-invisibility-spec)))))
17264 (defun org-in-invisibility-spec-p (arg)
17265 "Is ARG a member of `buffer-invisibility-spec'?"
17266 (if (consp buffer-invisibility-spec)
17267 (member arg buffer-invisibility-spec)
17268 nil))
17270 (defun org-image-file-name-regexp ()
17271 "Return regexp matching the file names of images."
17272 (if (fboundp 'image-file-name-regexp)
17273 (image-file-name-regexp)
17274 (let ((image-file-name-extensions
17275 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17276 "xbm" "xpm" "pbm" "pgm" "ppm")))
17277 (concat "\\."
17278 (regexp-opt (nconc (mapcar 'upcase
17279 image-file-name-extensions)
17280 image-file-name-extensions)
17282 "\\'"))))
17284 ;; Functions extending outline functionality
17286 ;; C-a should go to the beginning of a *visible* line, also in the
17287 ;; new outline.el. I guess this should be patched into Emacs?
17288 (defun org-beginning-of-line ()
17289 "Go to the beginning of the current line. If that is invisible, continue
17290 to a visible line beginning. This makes the function of C-a more intuitive."
17291 (interactive)
17292 (beginning-of-line 1)
17293 (if (bobp)
17295 (backward-char 1)
17296 (if (org-invisible-p)
17297 (while (and (not (bobp)) (org-invisible-p))
17298 (backward-char 1)
17299 (beginning-of-line 1))
17300 (forward-char 1))))
17302 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17304 (defun org-invisible-p ()
17305 "Check if point is at a character currently not visible."
17306 ;; Early versions of noutline don't have `outline-invisible-p'.
17307 (if (fboundp 'outline-invisible-p)
17308 (outline-invisible-p)
17309 (get-char-property (point) 'invisible)))
17311 (defun org-invisible-p2 ()
17312 "Check if point is at a character currently not visible."
17313 (save-excursion
17314 (if (and (eolp) (not (bobp))) (backward-char 1))
17315 ;; Early versions of noutline don't have `outline-invisible-p'.
17316 (if (fboundp 'outline-invisible-p)
17317 (outline-invisible-p)
17318 (get-char-property (point) 'invisible))))
17320 (defalias 'org-back-to-heading 'outline-back-to-heading)
17321 (defalias 'org-on-heading-p 'outline-on-heading-p)
17323 (defun org-on-target-p ()
17324 (let ((pos (point)))
17325 (save-excursion
17326 (skip-chars-forward "<")
17327 (and (re-search-backward "<<" nil t)
17328 (or (looking-at org-radio-target-regexp)
17329 (looking-at org-target-regexp))
17330 (<= (match-beginning 0) pos)
17331 (>= (1+ (match-end 0)) pos)))))
17333 (defun org-up-heading-all (arg)
17334 "Move to the heading line of which the present line is a subheading.
17335 This function considers both visible and invisible heading lines.
17336 With argument, move up ARG levels."
17337 (if (fboundp 'outline-up-heading-all)
17338 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17339 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17341 (defun org-goto-sibling (&optional previous)
17342 "Goto the next sibling, even if it is invisible.
17343 When PREVIOUS is set, go to the previous sibling instead. Returns t
17344 when a sibling was found. When none is found, return nil and don't
17345 move point."
17346 (let ((fun (if previous 're-search-backward 're-search-forward))
17347 (pos (point))
17348 (re (concat "^" outline-regexp))
17349 level l)
17350 (org-back-to-heading t)
17351 (setq level (funcall outline-level))
17352 (catch 'exit
17353 (or previous (forward-char 1))
17354 (while (funcall fun re nil t)
17355 (setq l (funcall outline-level))
17356 (when (< l level) (goto-char pos) (throw 'exit nil))
17357 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17358 (goto-char pos)
17359 nil)))
17361 (defun org-show-hidden-entry ()
17362 "Show an entry where even the heading is hidden."
17363 (save-excursion
17364 (org-show-entry)))
17366 (defun org-flag-heading (flag &optional entry)
17367 "Flag the current heading. FLAG non-nil means make invisible.
17368 When ENTRY is non-nil, show the entire entry."
17369 (save-excursion
17370 (org-back-to-heading t)
17371 ;; Check if we should show the entire entry
17372 (if entry
17373 (progn
17374 (org-show-entry)
17375 (save-excursion
17376 (and (outline-next-heading)
17377 (org-flag-heading nil))))
17378 (outline-flag-region (max 1 (1- (point)))
17379 (save-excursion (outline-end-of-heading) (point))
17380 flag))))
17382 (defun org-end-of-subtree (&optional invisible-OK)
17383 ;; This is an exact copy of the original function, but it uses
17384 ;; `org-back-to-heading', to make it work also in invisible
17385 ;; trees. And is uses an invisible-OK argument.
17386 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17387 (org-back-to-heading invisible-OK)
17388 (let ((first t)
17389 (level (funcall outline-level)))
17390 (while (and (not (eobp))
17391 (or first (> (funcall outline-level) level)))
17392 (setq first nil)
17393 (outline-next-heading))
17394 (if (memq (preceding-char) '(?\n ?\^M))
17395 (progn
17396 ;; Go to end of line before heading
17397 (forward-char -1)
17398 (if (memq (preceding-char) '(?\n ?\^M))
17399 ;; leave blank line before heading
17400 (forward-char -1)))))
17401 (point))
17403 (defun org-show-subtree ()
17404 "Show everything after this heading at deeper levels."
17405 (outline-flag-region
17406 (point)
17407 (save-excursion
17408 (outline-end-of-subtree) (outline-next-heading) (point))
17409 nil))
17411 (defun org-show-entry ()
17412 "Show the body directly following this heading.
17413 Show the heading too, if it is currently invisible."
17414 (interactive)
17415 (save-excursion
17416 (org-back-to-heading t)
17417 (outline-flag-region
17418 (max 1 (1- (point)))
17419 (save-excursion
17420 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
17421 (or (match-beginning 1) (point-max)))
17422 nil)))
17424 (defun org-make-options-regexp (kwds)
17425 "Make a regular expression for keyword lines."
17426 (concat
17428 "#?[ \t]*\\+\\("
17429 (mapconcat 'regexp-quote kwds "\\|")
17430 "\\):[ \t]*"
17431 "\\(.+\\)"))
17433 ;; Make `bookmark-jump' show the jump location if it was hidden.
17434 (eval-after-load "bookmark"
17435 '(if (boundp 'bookmark-after-jump-hook)
17436 ;; We can use the hook
17437 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17438 ;; Hook not available, use advice
17439 (defadvice bookmark-jump (after org-make-visible activate)
17440 "Make the position visible."
17441 (org-bookmark-jump-unhide))))
17443 (defun org-bookmark-jump-unhide ()
17444 "Unhide the current position, to show the bookmark location."
17445 (and (org-mode-p)
17446 (or (org-invisible-p)
17447 (save-excursion (goto-char (max (point-min) (1- (point))))
17448 (org-invisible-p)))
17449 (org-show-context 'bookmark-jump)))
17451 ;; Make session.el ignore our circular variable
17452 (eval-after-load "session"
17453 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17455 ;;; Experimental code
17457 ;;; Finish up
17459 (provide 'org)
17461 (run-hooks 'org-load-hook)
17463 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17464 ;;; org.el ends here