Release 4.57
[org-mode.git] / org.el
blob1ff8f57f24b89782a3b85f20fb075469b79f796f
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.57a
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.57a
65 ;; - Bug fixes for XEmacs.
67 ;; Version 4.57
68 ;; - Sorting of outline items on same level.
69 ;; - Sorting tables automatically selects line range between hlines.
70 ;; - Changes in Agenda buffer
71 ;; - `C-c C-o' follows a link in the current line.
72 ;; - `C-c $' archives the subtree corresponding to the line.
73 ;; - Changing dates with S-left and S-right show new date in agenda,
74 ;; but still do not move the entry to the new date.
75 ;; - new option `org-agenda-skip-scheduled-if-done'.
76 ;; - Agenda and sparse tree construction using tag matches can now
77 ;; use regular expressions.
78 ;; - When prompted for a date/time, entering "+7" indicates a date
79 ;; 7 days from now - but only this is the only thing you give.
80 ;; - Custom time formats also apply to exported html and ascii.
81 ;; - Bug fixes.
83 ;; Version 4.56
84 ;; - `C-k' in agenda kills current line and corresponding subtree in file.
85 ;; - XEmacs compatibility issues fixed, in particular tag alignment.
86 ;; - M-left/right now in/outdents plain list items, no Shift needed.
87 ;; - Bug fixes.
89 ;; Version 4.55
90 ;; - Bug fixes.
92 ;; Version 4.54
93 ;; - Improvements to fast tag selection
94 ;; + show status also in target line.
95 ;; + option to auto-exit after first change to tags list (see manual).
96 ;; - Tags sparse trees now also respect the settings in
97 ;; `org-show-hierarchy-above' and `org-show-following-heading'.
98 ;; - Bug fixes.
100 ;; Version 4.53
101 ;; - Custom time formats can be overlayed over time stamps.
102 ;; - New option `org-agenda-todo-ignore-deadlines'.
103 ;; - Work-around for flyspell bug (CVS Emacs has this fixed in flyspell.el).
104 ;; - Work-around for session.el problem with circular data structures.
105 ;; - Bug fixes.
107 ;; Version 4.52
108 ;; - TAG matches can also specify conditions on TODO keywords.
109 ;; - The fast tag interface allows setting tags that are not in the
110 ;; predefined list.
111 ;; - Bug fixes.
113 ;; Version 4.51
114 ;; - Link abbreviations (manual section 4.5).
115 ;; - More control over how agenda is displayed. See the new variables
116 ;; `org-agenda-window-setup', `org-agenda-restore-windows-after-quit'.
117 ;; - Bug fixes.
119 ;;; Code:
121 (eval-when-compile
122 (require 'cl)
123 (require 'gnus-sum)
124 (require 'calendar))
125 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
126 ;; the file noutline.el being loaded.
127 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
128 ;; We require noutline, which might be provided in outline.el
129 (require 'outline) (require 'noutline)
130 ;; Other stuff we need.
131 (require 'time-date)
132 (require 'easymenu)
134 ;;; Customization variables
136 (defvar org-version "4.57a"
137 "The version number of the file org.el.")
138 (defun org-version ()
139 (interactive)
140 (message "Org-mode version %s" org-version))
142 ;; Compatibility constants
143 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
144 (defconst org-format-transports-properties-p
145 (let ((x "a"))
146 (add-text-properties 0 1 '(test t) x)
147 (get-text-property 0 'test (format "%s" x)))
148 "Does format transport text properties?")
150 (defgroup org nil
151 "Outline-based notes management and organizer."
152 :tag "Org"
153 :group 'outlines
154 :group 'hypermedia
155 :group 'calendar)
157 (defgroup org-startup nil
158 "Options concerning startup of Org-mode."
159 :tag "Org Startup"
160 :group 'org)
162 (defcustom org-startup-folded t
163 "Non-nil means, entering Org-mode will switch to OVERVIEW.
164 This can also be configured on a per-file basis by adding one of
165 the following lines anywhere in the buffer:
167 #+STARTUP: fold
168 #+STARTUP: nofold
169 #+STARTUP: content"
170 :group 'org-startup
171 :type '(choice
172 (const :tag "nofold: show all" nil)
173 (const :tag "fold: overview" t)
174 (const :tag "content: all headlines" content)))
176 (defcustom org-startup-truncated t
177 "Non-nil means, entering Org-mode will set `truncate-lines'.
178 This is useful since some lines containing links can be very long and
179 uninteresting. Also tables look terrible when wrapped."
180 :group 'org-startup
181 :type 'boolean)
183 (defcustom org-startup-align-all-tables nil
184 "Non-nil means, align all tables when visiting a file.
185 This is useful when the column width in tables is forced with <N> cookies
186 in table fields. Such tables will look correct only after the first re-align.
187 This can also be configured on a per-file basis by adding one of
188 the following lines anywhere in the buffer:
189 #+STARTUP: align
190 #+STARTUP: noalign"
191 :group 'org-startup
192 :type 'boolean)
194 (defcustom org-startup-with-deadline-check nil
195 "Non-nil means, entering Org-mode will run the deadline check.
196 This means, if you start editing an org file, you will get an
197 immediate reminder of any due deadlines.
198 This can also be configured on a per-file basis by adding one of
199 the following lines anywhere in the buffer:
200 #+STARTUP: dlcheck
201 #+STARTUP: nodlcheck"
202 :group 'org-startup
203 :type 'boolean)
205 (defcustom org-insert-mode-line-in-empty-file nil
206 "Non-nil means insert the first line setting Org-mode in empty files.
207 When the function `org-mode' is called interactively in an empty file, this
208 normally means that the file name does not automatically trigger Org-mode.
209 To ensure that the file will always be in Org-mode in the future, a
210 line enforcing Org-mode will be inserted into the buffer, if this option
211 has been set."
212 :group 'org-startup
213 :type 'boolean)
215 (defcustom org-CUA-compatible nil
216 "Non-nil means use alternative key bindings for S-<cursor movement>.
217 Org-mode used S-<cursor movement> for changing timestamps and priorities.
218 S-<cursor movement> is also used for example by `CUA-mode' to select text.
219 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
220 alternative bindings. Setting this variable to t will replace the following
221 keys both in Org-mode and in the Org-agenda buffer.
223 S-RET -> C-S-RET
224 S-up -> M-p
225 S-down -> M-n
226 S-left -> M--
227 S-right -> M-+
229 If you do not like the alternative keys, take a look at the variable
230 `org-disputed-keys'.
232 This option is only relevant at load-time of Org-mode. Changing it requires
233 a restart of Emacs to become effective."
234 :group 'org-startup
235 :type 'boolean)
237 (defvar org-disputed-keys
238 '((S-up [(shift up)] [(meta ?p)])
239 (S-down [(shift down)] [(meta ?n)])
240 (S-left [(shift left)] [(meta ?-)])
241 (S-right [(shift right)] [(meta ?+)])
242 (S-return [(shift return)] [(control shift return)]))
243 "Keys for which Org-mode and other modes compete.
244 This is an alist, cars are symbols for lookup, 1st element is the default key,
245 second element will be used when `org-CUA-compatible' is t.")
247 (defun org-key (key)
248 "Select a key according to `org-CUA-compatible'."
249 (nth (if org-CUA-compatible 2 1)
250 (or (assq key org-disputed-keys)
251 (error "Invalid Key %s in `org-key'" key))))
253 (defcustom org-ellipsis nil
254 "The ellipsis to use in the Org-mode outline.
255 When nil, just use the standard three dots. When a string, use that instead,
256 and just in Org-mode (which will then use its own display table).
257 Changing this requires executing `M-x org-mode' in a buffer to become
258 effective."
259 :group 'org-startup
260 :type '(choice (const :tag "Default" nil)
261 (string :tag "String" :value "...#")))
263 (defvar org-display-table nil
264 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
266 (defgroup org-keywords nil
267 "Keywords in Org-mode."
268 :tag "Org Keywords"
269 :group 'org)
271 (defcustom org-deadline-string "DEADLINE:"
272 "String to mark deadline entries.
273 A deadline is this string, followed by a time stamp. Should be a word,
274 terminated by a colon. You can insert a schedule keyword and
275 a timestamp with \\[org-deadline].
276 Changes become only effective after restarting Emacs."
277 :group 'org-keywords
278 :type 'string)
280 (defcustom org-scheduled-string "SCHEDULED:"
281 "String to mark scheduled TODO entries.
282 A schedule is this string, followed by a time stamp. Should be a word,
283 terminated by a colon. You can insert a schedule keyword and
284 a timestamp with \\[org-schedule].
285 Changes become only effective after restarting Emacs."
286 :group 'org-keywords
287 :type 'string)
289 (defcustom org-closed-string "CLOSED:"
290 "String used as the prefix for timestamps logging closing a TODO entry."
291 :group 'org-keywords
292 :type 'string)
294 (defcustom org-clock-string "CLOCK:"
295 "String used as prefix for timestamps clocking work hours on an item."
296 :group 'org-keywords
297 :type 'string)
299 (defcustom org-comment-string "COMMENT"
300 "Entries starting with this keyword will never be exported.
301 An entry can be toggled between COMMENT and normal with
302 \\[org-toggle-comment].
303 Changes become only effective after restarting Emacs."
304 :group 'org-keywords
305 :type 'string)
307 (defcustom org-quote-string "QUOTE"
308 "Entries starting with this keyword will be exported in fixed-width font.
309 Quoting applies only to the text in the entry following the headline, and does
310 not extend beyond the next headline, even if that is lower level.
311 An entry can be toggled between QUOTE and normal with
312 \\[org-toggle-fixed-width-section]."
313 :group 'org-keywords
314 :type 'string)
316 (defgroup org-structure nil
317 "Options concerning the general structure of Org-mode files."
318 :tag "Org Structure"
319 :group 'org)
321 (defgroup org-cycle nil
322 "Options concerning visibility cycling in Org-mode."
323 :tag "Org Cycle"
324 :group 'org-structure)
326 (defcustom org-cycle-global-at-bob t
327 "Cycle globally if cursor is at beginning of buffer and not at a headline.
328 This makes it possible to do global cycling without having to use S-TAB or
329 C-u TAB. For this special case to work, the first line of the buffer
330 must not be a headline - it may be empty ot some other text. When used in
331 this way, `org-cycle-hook' is disables temporarily, to make sure the
332 cursor stays at the beginning of the buffer.
333 When this option is nil, don't do anything special at the beginning
334 of the buffer."
335 :group 'org-cycle
336 :type 'boolean)
338 (defcustom org-cycle-emulate-tab t
339 "Where should `org-cycle' emulate TAB.
340 nil Never
341 white Only in completely white lines
342 whitestart Only at the beginning of lines, before the first non-white char.
343 t Everywhere except in headlines
344 If TAB is used in a place where it does not emulate TAB, the current subtree
345 visibility is cycled."
346 :group 'org-cycle
347 :type '(choice (const :tag "Never" nil)
348 (const :tag "Only in completely white lines" white)
349 (const :tag "Before first char in a line" whitestart)
350 (const :tag "Everywhere except in headlines" t)
353 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
354 org-optimize-window-after-visibility-change)
355 "Hook that is run after `org-cycle' has changed the buffer visibility.
356 The function(s) in this hook must accept a single argument which indicates
357 the new state that was set by the most recent `org-cycle' command. The
358 argument is a symbol. After a global state change, it can have the values
359 `overview', `content', or `all'. After a local state change, it can have
360 the values `folded', `children', or `subtree'."
361 :group 'org-cycle
362 :type 'hook)
364 (defgroup org-edit-structure nil
365 "Options concerning structure editing in Org-mode."
366 :tag "Org Edit Structure"
367 :group 'org-structure)
369 (defcustom org-odd-levels-only nil
370 "Non-nil means, skip even levels and only use odd levels for the outline.
371 This has the effect that two stars are being added/taken away in
372 promotion/demotion commands. It also influences how levels are
373 handled by the exporters.
374 Changing it requires restart of `font-lock-mode' to become effective
375 for fontification also in regions already fontified.
376 You may also set this on a per-file basis by adding one of the following
377 lines to the buffer:
379 #+STARTUP: odd
380 #+STARTUP: oddeven"
381 :group 'org-edit-structure
382 :group 'org-font-lock
383 :type 'boolean)
385 (defcustom org-adapt-indentation t
386 "Non-nil means, adapt indentation when promoting and demoting.
387 When this is set and the *entire* text in an entry is indented, the
388 indentation is increased by one space in a demotion command, and
389 decreased by one in a promotion command. If any line in the entry
390 body starts at column 0, indentation is not changed at all."
391 :group 'org-edit-structure
392 :type 'boolean)
394 (defcustom org-blank-before-new-entry '((heading . nil)
395 (plain-list-item . nil))
396 "Should `org-insert-heading' leave a blank line before new heading/item?
397 The value is an alist, with `heading' and `plain-list-item' as car,
398 and a boolean flag as cdr."
399 :group 'org-edit-structure
400 :type '(list
401 (cons (const heading) (boolean))
402 (cons (const plain-list-item) (boolean))))
404 (defcustom org-insert-heading-hook nil
405 "Hook being run after inserting a new heading."
406 :group 'org-edit-structure
407 :type 'boolean)
409 (defcustom org-enable-fixed-width-editor t
410 "Non-nil means, lines starting with \":\" are treated as fixed-width.
411 This currently only means, they are never auto-wrapped.
412 When nil, such lines will be treated like ordinary lines.
413 See also the QUOTE keyword."
414 :group 'org-edit-structure
415 :type 'boolean)
417 (defgroup org-sparse-trees nil
418 "Options concerning sparse trees in Org-mode."
419 :tag "Org Sparse Trees"
420 :group 'org-structure)
422 (defcustom org-highlight-sparse-tree-matches t
423 "Non-nil means, highlight all matches that define a sparse tree.
424 The highlights will automatically disappear the next time the buffer is
425 changed by an edit command."
426 :group 'org-sparse-trees
427 :type 'boolean)
429 (defcustom org-remove-highlights-with-change t
430 "Non-nil means, any change to the buffer will remove temporary highlights.
431 Such highlights are created by `org-occur' and `org-clock-display'.
432 When nil, `C-c C-c needs to be used to get rid of the highlights.
433 The highlights created by `org-preview-latex-fragment' always need
434 `C-c C-c' to be removed."
435 :group 'org-sparse-trees
436 :group 'org-time
437 :type 'boolean)
439 (defcustom org-show-hierarchy-above '((default . t))
440 "Non-nil means, show full hierarchy when showing a spot in the tree.
441 Turning this off makes sparse trees more compact, but also less clear.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. Valid contexts are
444 agenda when exposing an entry from the agenda
445 org-goto when using the command `org-goto' on key C-c C-j
446 occur-tree when using the command `org-occur' on key C-c /
447 tags-tree when constructing a sparse tree based on tags matches
448 link-search when exposing search matches associated with a link
449 mark-goto when exposing the jump goal of a mark
450 bookmark-jump when exposing a bookmark location
451 default default for all contexts not set explicitly"
452 :group 'org-sparse-trees
453 :type '(choice
454 (const :tag "Always" t)
455 (const :tag "Never" nil)
456 (repeat :greedy t :tag "Individual contexts"
457 (cons
458 (choice :tag "Context"
459 (const agenda)
460 (const org-goto)
461 (const occur-tree)
462 (const tags-tree)
463 (const link-search)
464 (const mark-goto)
465 (const bookmark-jump)
466 (const default))
467 (boolean)))))
469 (defcustom org-show-following-heading '((default . t))
470 "Non-nil means, show heading following match in `org-occur'.
471 When doing an `org-occur' it is useful to show the headline which
472 follows the match, even if they do not match the regexp. This makes it
473 easier to edit directly inside the sparse tree. However, if you use
474 `org-occur' mainly as an overview, the following headlines are
475 unnecessary clutter.
476 Instead of t, this can also be an alist specifying this option for different
477 contexts. See `org-show-hierarchy-above' for valid contexts."
478 :group 'org-sparse-trees
479 :type '(choice
480 (const :tag "Always" t)
481 (const :tag "Never" nil)
482 (repeat :greedy t :tag "Individual contexts"
483 (cons
484 (choice :tag "Context"
485 (const agenda)
486 (const org-goto)
487 (const occur-tree)
488 (const tags-tree)
489 (const link-search)
490 (const mark-goto)
491 (const bookmark-jump)
492 (const default))
493 (boolean)))))
495 (defcustom org-occur-hook '(org-first-headline-recenter)
496 "Hook that is run after `org-occur' has constructed a sparse tree.
497 This can be used to recenter the window to show as much of the structure
498 as possible."
499 :group 'org-sparse-trees
500 :type 'hook)
502 (defgroup org-plain-lists nil
503 "Options concerning plain lists in Org-mode."
504 :tag "Org Plain lists"
505 :group 'org-structure)
507 (defcustom org-cycle-include-plain-lists nil
508 "Non-nil means, include plain lists into visibility cycling.
509 This means that during cycling, plain list items will *temporarily* be
510 interpreted as outline headlines with a level given by 1000+i where i is the
511 indentation of the bullet. In all other operations, plain list items are
512 not seen as headlines. For example, you cannot assign a TODO keyword to
513 such an item."
514 :group 'org-plain-lists
515 :type 'boolean)
517 (defcustom org-plain-list-ordered-item-terminator t
518 "The character that makes a line with leading number an ordered list item.
519 Valid values are ?. and ?\). To get both terminators, use t. While
520 ?. may look nicer, it creates the danger that a line with leading
521 number may be incorrectly interpreted as an item. ?\) therefore is
522 the safe choice."
523 :group 'org-plain-lists
524 :type '(choice (const :tag "dot like in \"2.\"" ?.)
525 (const :tag "paren like in \"2)\"" ?\))
526 (const :tab "both" t)))
528 (defcustom org-auto-renumber-ordered-lists t
529 "Non-nil means, automatically renumber ordered plain lists.
530 Renumbering happens when the sequence have been changed with
531 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
532 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
533 :group 'org-plain-lists
534 :type 'boolean)
536 (defcustom org-provide-checkbox-statistics t
537 "Non-nil means, update checkbox statistics after insert and toggle.
538 When this is set, checkbox statistics is updated each time you either insert
539 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
540 with \\[org-ctrl-c-ctrl-c\\]."
541 :group 'org
542 :type 'boolean)
544 (defgroup org-archive nil
545 "Options concerning archiving in Org-mode."
546 :tag "Org Archive"
547 :group 'org-structure)
549 (defcustom org-archive-tag "ARCHIVE"
550 "The tag that marks a subtree as archived.
551 An archived subtree does not open during visibility cycling, and does
552 not contribute to the agenda listings."
553 :group 'org-archive
554 :group 'org-keywords
555 :type 'string)
557 (defcustom org-agenda-skip-archived-trees t
558 "Non-nil means, the agenda will skip any items located in archived trees.
559 An archived tree is a tree marked with the tag ARCHIVE."
560 :group 'org-archive
561 :group 'org-agenda-display
562 :type 'boolean)
564 (defcustom org-cycle-open-archived-trees nil
565 "Non-nil means, `org-cycle' will open archived trees.
566 An archived tree is a tree marked with the tag ARCHIVE.
567 When nil, archived trees will stay folded. You can still open them with
568 normal outline commands like `show-all', but not with the cycling commands."
569 :group 'org-archive
570 :group 'org-cycle
571 :type 'boolean)
573 (defcustom org-sparse-tree-open-archived-trees nil
574 "Non-nil means sparse tree construction shows matches in archived trees.
575 When nil, matches in these trees are highlighted, but the trees are kept in
576 collapsed state."
577 :group 'org-archive
578 :group 'org-sparse-trees
579 :type 'boolean)
581 (defcustom org-archive-location "%s_archive::"
582 "The location where subtrees should be archived.
583 This string consists of two parts, separated by a double-colon.
585 The first part is a file name - when omitted, archiving happens in the same
586 file. %s will be replaced by the current file name (without directory part).
587 Archiving to a different file is useful to keep archived entries from
588 contributing to the Org-mode Agenda.
590 The part after the double colon is a headline. The archived entries will be
591 filed under that headline. When omitted, the subtrees are simply filed away
592 at the end of the file, as top-level entries.
594 Here are a few examples:
595 \"%s_archive::\"
596 If the current file is Projects.org, archive in file
597 Projects.org_archive, as top-level trees. This is the default.
599 \"::* Archived Tasks\"
600 Archive in the current file, under the top-level headline
601 \"* Archived Tasks\".
603 \"~/org/archive.org::\"
604 Archive in file ~/org/archive.org (absolute path), as top-level trees.
606 \"basement::** Finished Tasks\"
607 Archive in file ./basement (relative path), as level 3 trees
608 below the level 2 heading \"** Finished Tasks\".
610 You may set this option on a per-file basis by adding to the buffer a
611 line like
613 #+ARCHIVE: basement::** Finished Tasks"
614 :group 'org-archive
615 :type 'string)
617 (defcustom org-archive-mark-done t
618 "Non-nil means, mark entries as DONE when they are moved to the archive file."
619 :group 'org-archive
620 :type 'boolean)
622 (defcustom org-archive-stamp-time t
623 "Non-nil means, add a time stamp to entries moved to an archive file.
624 The time stamp will be added directly after the TODO state keyword in the
625 first line, so it is probably best to use this in combinations with
626 `org-archive-mark-done'."
627 :group 'org-archive
628 :type 'boolean)
630 (defgroup org-table nil
631 "Options concerning tables in Org-mode."
632 :tag "Org Table"
633 :group 'org)
635 (defcustom org-enable-table-editor 'optimized
636 "Non-nil means, lines starting with \"|\" are handled by the table editor.
637 When nil, such lines will be treated like ordinary lines.
639 When equal to the symbol `optimized', the table editor will be optimized to
640 do the following:
641 - Automatic overwrite mode in front of whitespace in table fields.
642 This makes the structure of the table stay in tact as long as the edited
643 field does not exceed the column width.
644 - Minimize the number of realigns. Normally, the table is aligned each time
645 TAB or RET are pressed to move to another field. With optimization this
646 happens only if changes to a field might have changed the column width.
647 Optimization requires replacing the functions `self-insert-command',
648 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
649 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
650 very good at guessing when a re-align will be necessary, but you can always
651 force one with \\[org-ctrl-c-ctrl-c].
653 If you would like to use the optimized version in Org-mode, but the
654 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
656 This variable can be used to turn on and off the table editor during a session,
657 but in order to toggle optimization, a restart is required.
659 See also the variable `org-table-auto-blank-field'."
660 :group 'org-table
661 :type '(choice
662 (const :tag "off" nil)
663 (const :tag "on" t)
664 (const :tag "on, optimized" optimized)))
666 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
667 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
668 In the optimized version, the table editor takes over all simple keys that
669 normally just insert a character. In tables, the characters are inserted
670 in a way to minimize disturbing the table structure (i.e. in overwrite mode
671 for empty fields). Outside tables, the correct binding of the keys is
672 restored.
674 The default for this option is t if the optimized version is also used in
675 Org-mode. See the variable `org-enable-table-editor' for details. Changing
676 this variable requires a restart of Emacs to become effective."
677 :group 'org-table
678 :type 'boolean)
680 (defgroup org-table-settings nil
681 "Settings for tables in Org-mode."
682 :tag "Org Table Settings"
683 :group 'org-table)
685 (defcustom org-table-default-size "5x2"
686 "The default size for newly created tables, Columns x Rows."
687 :group 'org-table-settings
688 :type 'string)
690 ;; FIXME: I am no longer sure if including HEX is a good idea.
691 (defcustom org-table-number-regexp
692 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$"
693 "Regular expression for recognizing numbers in table columns.
694 If a table column contains mostly numbers, it will be aligned to the
695 right. If not, it will be aligned to the left.
697 The default value of this option is a regular expression which allows
698 anything which looks remotely like a number as used in scientific
699 context. For example, all of the following will be considered a
700 number:
701 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
703 Other options offered by the customize interface are more restrictive."
704 :group 'org-table-settings
705 :type '(choice
706 (const :tag "Positive Integers"
707 "^[0-9]+$")
708 (const :tag "Integers"
709 "^[-+]?[0-9]+$")
710 (const :tag "Floating Point Numbers"
711 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
712 (const :tag "Floating Point Number or Integer"
713 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
714 (const :tag "Exponential, Floating point, Integer"
715 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
716 (const :tag "Very General Number-Like, including hex"
717 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)?[0-9a-fA-F]+\\)$")
718 (string :tag "Regexp:")))
720 (defcustom org-table-number-fraction 0.5
721 "Fraction of numbers in a column required to make the column align right.
722 In a column all non-white fields are considered. If at least this
723 fraction of fields is matched by `org-table-number-fraction',
724 alignment to the right border applies."
725 :group 'org-table-settings
726 :type 'number)
728 (defgroup org-table-editing nil
729 "Bahavior of tables during editing in Org-mode."
730 :tag "Org Table Editing"
731 :group 'org-table)
733 (defcustom org-table-automatic-realign t
734 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
735 When nil, aligning is only done with \\[org-table-align], or after column
736 removal/insertion."
737 :group 'org-table-editing
738 :type 'boolean)
740 (defcustom org-table-limit-column-width t ;kw
741 "Non-nil means, allow to limit the width of table columns with <N> fields."
742 :group 'org-table-editing
743 :type 'boolean)
745 (defcustom org-table-auto-blank-field t
746 "Non-nil means, automatically blank table field when starting to type into it.
747 This only happens when typing immediately after a field motion
748 command (TAB, S-TAB or RET).
749 Only relevant when `org-enable-table-editor' is equal to `optimized'."
750 :group 'org-table-editing
751 :type 'boolean)
753 (defcustom org-table-tab-jumps-over-hlines t
754 "Non-nil means, tab in the last column of a table with jump over a hline.
755 If a horizontal separator line is following the current line,
756 `org-table-next-field' can either create a new row before that line, or jump
757 over the line. When this option is nil, a new line will be created before
758 this line."
759 :group 'org-table-editing
760 :type 'boolean)
762 (defcustom org-table-tab-recognizes-table.el t
763 "Non-nil means, TAB will automatically notice a table.el table.
764 When it sees such a table, it moves point into it and - if necessary -
765 calls `table-recognize-table'."
766 :group 'org-table-editing
767 :type 'boolean)
769 (defgroup org-table-calculation nil
770 "Options concerning tables in Org-mode."
771 :tag "Org Table Calculation"
772 :group 'org-table)
774 (defcustom org-table-copy-increment t
775 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
776 :group 'org-table-calculation
777 :type 'boolean)
779 (defcustom org-calc-default-modes
780 '(calc-internal-prec 12
781 calc-float-format (float 5)
782 calc-angle-mode deg
783 calc-prefer-frac nil
784 calc-symbolic-mode nil
785 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
786 calc-display-working-message t
788 "List with Calc mode settings for use in calc-eval for table formulas.
789 The list must contain alternating symbols (Calc modes variables and values).
790 Don't remove any of the default settings, just change the values. Org-mode
791 relies on the variables to be present in the list."
792 :group 'org-table-calculation
793 :type 'plist)
795 (defcustom org-table-formula-evaluate-inline t
796 "Non-nil means, TAB and RET evaluate a formula in current table field.
797 If the current field starts with an equal sign, it is assumed to be a formula
798 which should be evaluated as described in the manual and in the documentation
799 string of the command `org-table-eval-formula'. This feature requires the
800 Emacs calc package.
801 When this variable is nil, formula calculation is only available through
802 the command \\[org-table-eval-formula]."
803 :group 'org-table-calculation
804 :type 'boolean)
807 (defcustom org-table-formula-use-constants t
808 "Non-nil means, interpret constants in formulas in tables.
809 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
810 by the value given in `org-table-formula-constants', or by a value obtained
811 from the `constants.el' package."
812 :group 'org-table-calculation
813 :type 'boolean)
815 (defcustom org-table-formula-constants nil
816 "Alist with constant names and values, for use in table formulas.
817 The car of each element is a name of a constant, without the `$' before it.
818 The cdr is the value as a string. For example, if you'd like to use the
819 speed of light in a formula, you would configure
821 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
823 and then use it in an equation like `$1*$c'."
824 :group 'org-table-calculation
825 :type '(repeat
826 (cons (string :tag "name")
827 (string :tag "value"))))
829 (defcustom org-table-formula-numbers-only nil
830 "Non-nil means, calculate only with numbers in table formulas.
831 Then all input fields will be converted to a number, and the result
832 must also be a number. When nil, calc's full potential is available
833 in table calculations, including symbolics etc."
834 :group 'org-table-calculation
835 :type 'boolean)
837 (defcustom org-table-allow-automatic-line-recalculation t
838 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
839 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
840 :group 'org-table-calculation
841 :type 'boolean)
843 (defgroup org-link nil
844 "Options concerning links in Org-mode."
845 :tag "Org Link"
846 :group 'org)
848 (defvar org-link-abbrev-alist-local nil
849 "buffer-local version of `org-link-abbrev-alist', which see.
850 The value of this is taken from the #+LINK lines.")
851 (make-variable-buffer-local 'org-link-abbrev-alist-local)
853 (defcustom org-link-abbrev-alist nil
854 "Alist of link abbreviations.
855 The car of each element is a string, to be replaced at the start of a link.
856 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
857 links in Org-mode buffers can have an optional tag after a double colon, e.g.
859 [[linkkey::tag][description]]
861 If REPLACE is a string, the tag will simply be appended to create the link.
862 If the string contains \"%s\", the tag will be inserted there. REPLACE may
863 also be a function that will be called with the tag as the only argument to
864 create the link. See the manual for examples."
865 :group 'org-link
866 :type 'alist)
868 (defcustom org-descriptive-links t
869 "Non-nil means, hide link part and only show description of bracket links.
870 Bracket links are like [[link][descritpion]]. This variable sets the initial
871 state in new org-mode buffers. The setting can then be toggled on a
872 per-buffer basis from the Org->Hyperlinks menu."
873 :group 'org-link
874 :type 'boolean)
876 (defcustom org-link-style 'bracket
877 "The style of links to be inserted with \\[org-insert-link].
878 Possible values are:
879 bracket [[link][description]]. This is recommended
880 plain Description \\n link. The old way, no longer recommended."
881 :group 'org-link
882 :type '(choice
883 (const :tag "Bracket (recommended)" bracket)
884 (const :tag "Plain (no longer recommended)" plain)))
886 (defcustom org-link-format "%s"
887 "Default format for external, URL-like linkes in the buffer.
888 This is a format string for printf, %s will be replaced by the link text.
889 The recommended value is just \"%s\", since links will be protected by
890 enclosing them in double brackets. If you prefer plain links (see variable
891 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
892 additional URL: prefix, so the format would be \"<URL:%s>\"."
893 :group 'org-link
894 :type '(choice
895 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
896 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
897 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
898 (string :tag "Other" :value "<%s>")))
900 (defcustom org-link-file-path-type 'adaptive
901 "How the path name in file links should be stored.
902 Valid values are:
904 relative relative to the current directory, i.e. the directory of the file
905 into which the link is being inserted.
906 absolute absolute path, if possible with ~ for home directory.
907 noabbrev absolute path, no abbreviation of home directory.
908 adaptive Use relative path for files in the current directory and sub-
909 directories of it. For other files, use an absolute path."
910 :group 'org-link
911 :type '(choice
912 (const relative)
913 (const absolute)
914 (const noabbrev)
915 (const adaptive)))
917 (defcustom org-activate-links '(bracket angle plain radio tag date)
918 "Types of links that should be activated in Org-mode files.
919 This is a list of symbols, each leading to the activation of a certain link
920 type. In principle, it does not hurt to turn on most link types - there may
921 be a small gain when turning off unused link types. The types are:
923 bracket The recommended [[link][description]] or [[link]] links with hiding.
924 angular Links in angular brackes that may contain whitespace like
925 <bbdb:Carsten Dominik>.
926 plain Plain links in normal text, no whitespace, like http://google.com.
927 radio Text that is matched by a radio target, see manual for details.
928 tag Tag settings in a headline (link to tag search).
929 date Time stamps (link to calendar).
930 camel CamelCase words defining text searches.
932 Changing this variable requires a restart of Emacs to become effective."
933 :group 'org-link
934 :type '(set (const :tag "Double bracket links (new style)" bracket)
935 (const :tag "Angular bracket links (old style)" angular)
936 (const :tag "plain text links" plain)
937 (const :tag "Radio target matches" radio)
938 (const :tag "Tags" tag)
939 (const :tag "Timestamps" date)
940 (const :tag "CamelCase words" camel)))
942 (defgroup org-link-store nil
943 "Options concerning storing links in Org-mode"
944 :tag "Org Store Link"
945 :group 'org-link)
947 (defcustom org-context-in-file-links t
948 "Non-nil means, file links from `org-store-link' contain context.
949 A search string will be added to the file name with :: as separator and
950 used to find the context when the link is activated by the command
951 `org-open-at-point'.
952 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
953 negates this setting for the duration of the command."
954 :group 'org-link-store
955 :type 'boolean)
957 (defcustom org-file-link-context-use-camel-case nil
958 "Non-nil means, use CamelCase to store a search context in a file link.
959 When nil, the search string simply consists of the words of the string.
960 CamelCase is deprecated, and support for it may be dropped in the future."
961 :group 'org-link-store
962 :type 'boolean)
964 (defcustom org-keep-stored-link-after-insertion nil
965 "Non-nil means, keep link in list for entire session.
967 The command `org-store-link' adds a link pointing to the current
968 location to an internal list. These links accumulate during a session.
969 The command `org-insert-link' can be used to insert links into any
970 Org-mode file (offering completion for all stored links). When this
971 option is nil, every link which has been inserted once using \\[org-insert-link]
972 will be removed from the list, to make completing the unused links
973 more efficient."
974 :group 'org-link-store
975 :type 'boolean)
977 (defcustom org-usenet-links-prefer-google nil
978 "Non-nil means, `org-store-link' will create web links to Google groups.
979 When nil, Gnus will be used for such links.
980 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
981 negates this setting for the duration of the command."
982 :group 'org-link-store
983 :type 'boolean)
985 (defgroup org-link-follow nil
986 "Options concerning following links in Org-mode"
987 :tag "Org Follow Link"
988 :group 'org-link)
990 (defcustom org-tab-follows-link nil
991 "Non-nil means, on links TAB will follow the link.
992 Needs to be set before org.el is loaded."
993 :group 'org-link-follow
994 :type 'boolean)
996 (defcustom org-return-follows-link nil
997 "Non-nil means, on links RET will follow the link.
998 Needs to be set before org.el is loaded."
999 :group 'org-link-follow
1000 :type 'boolean)
1002 (defcustom org-mouse-1-follows-link t
1003 "Non-nil means, mouse-1 on a link will follow the link.
1004 A longer mouse click will still set point. Does not wortk on XEmacs.
1005 Needs to be set before org.el is loaded."
1006 :group 'org-link-follow
1007 :type 'boolean)
1009 (defcustom org-mark-ring-length 4
1010 "Number of different positions to be recorded in the ring
1011 Changing this requires a restart of Emacs to work correctly."
1012 :group 'org-link-follow
1013 :type 'interger)
1015 (defcustom org-link-frame-setup
1016 '((vm . vm-visit-folder-other-frame)
1017 (gnus . gnus-other-frame)
1018 (file . find-file-other-window))
1019 "Setup the frame configuration for following links.
1020 When following a link with Emacs, it may often be useful to display
1021 this link in another window or frame. This variable can be used to
1022 set this up for the different types of links.
1023 For VM, use any of
1024 `vm-visit-folder'
1025 `vm-visit-folder-other-frame'
1026 For Gnus, use any of
1027 `gnus'
1028 `gnus-other-frame'
1029 For FILE, use any of
1030 `find-file'
1031 `find-file-other-window'
1032 `find-file-other-frame'
1033 For the calendar, use the variable `calendar-setup'.
1034 For BBDB, it is currently only possible to display the matches in
1035 another window."
1036 :group 'org-link-follow
1037 :type '(list
1038 (cons (const vm)
1039 (choice
1040 (const vm-visit-folder)
1041 (const vm-visit-folder-other-window)
1042 (const vm-visit-folder-other-frame)))
1043 (cons (const gnus)
1044 (choice
1045 (const gnus)
1046 (const gnus-other-frame)))
1047 (cons (const file)
1048 (choice
1049 (const find-file)
1050 (const find-file-other-window)
1051 (const find-file-other-frame)))))
1053 (defcustom org-display-internal-link-with-indirect-buffer nil
1054 "Non-nil means, use indirect buffer to display infile links.
1055 Activating internal links (from one location in a file to another location
1056 in the same file) normally just jumps to the location. When the link is
1057 activated with a C-u prefix (or with mouse-3), the link is displayed in
1058 another window. When this option is set, the other window actually displays
1059 an indirect buffer clone of the current buffer, to avoid any visibility
1060 changes to the current buffer."
1061 :group 'org-link-follow
1062 :type 'boolean)
1065 (defcustom org-open-non-existing-files nil
1066 "Non-nil means, `org-open-file' will open non-existing file.
1067 When nil, an error will be generated."
1068 :group 'org-link-follow
1069 :type 'boolean)
1071 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1072 "Function and arguments to call for following mailto links.
1073 This is a list with the first element being a lisp function, and the
1074 remaining elements being arguments to the function. In string arguments,
1075 %a will be replaced by the address, and %s will be replaced by the subject
1076 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1077 :group 'org-link-follow
1078 :type '(choice
1079 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1080 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1081 (const :tag "message-mail" (message-mail "%a" "%s"))
1082 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1084 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1085 "Non-nil means, ask for confirmation before executing shell links.
1086 Shell links can be dangerous, just thing about a link
1088 [[shell:rm -rf ~/*][Google Search]]
1090 This link would show up in your Org-mode document as \"Google Search\"
1091 but really it would remove your entire home directory.
1092 Therefore I *definitely* advise against setting this variable to nil.
1093 Just change it to `y-or-n-p' of you want to confirm with a single key press
1094 rather than having to type \"yes\"."
1095 :group 'org-link-follow
1096 :type '(choice
1097 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1098 (const :tag "with y-or-n (faster)" y-or-n-p)
1099 (const :tag "no confirmation (dangerous)" nil)))
1101 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1102 "Non-nil means, ask for confirmation before executing elisp links.
1103 Elisp links can be dangerous, just think about a link
1105 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1107 This link would show up in your Org-mode document as \"Google Search\"
1108 but really it would remove your entire home directory.
1109 Therefore I *definitely* advise against setting this variable to nil.
1110 Just change it to `y-or-n-p' of you want to confirm with a single key press
1111 rather than having to type \"yes\"."
1112 :group 'org-link-follow
1113 :type '(choice
1114 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1115 (const :tag "with y-or-n (faster)" y-or-n-p)
1116 (const :tag "no confirmation (dangerous)" nil)))
1118 (defconst org-file-apps-defaults-gnu
1119 '((remote . emacs)
1120 (t . mailcap))
1121 "Default file applications on a UNIX or GNU/Linux system.
1122 See `org-file-apps'.")
1124 (defconst org-file-apps-defaults-macosx
1125 '((remote . emacs)
1126 (t . "open %s")
1127 ("ps" . "gv %s")
1128 ("ps.gz" . "gv %s")
1129 ("eps" . "gv %s")
1130 ("eps.gz" . "gv %s")
1131 ("dvi" . "xdvi %s")
1132 ("fig" . "xfig %s"))
1133 "Default file applications on a MacOS X system.
1134 The system \"open\" is known as a default, but we use X11 applications
1135 for some files for which the OS does not have a good default.
1136 See `org-file-apps'.")
1138 (defconst org-file-apps-defaults-windowsnt
1139 (list
1140 '(remote . emacs)
1141 (cons t
1142 (list (if (featurep 'xemacs)
1143 'mswindows-shell-execute
1144 'w32-shell-execute)
1145 "open" 'file)))
1146 "Default file applications on a Windows NT system.
1147 The system \"open\" is used for most files.
1148 See `org-file-apps'.")
1150 (defcustom org-file-apps
1152 ("txt" . emacs)
1153 ("tex" . emacs)
1154 ("ltx" . emacs)
1155 ("org" . emacs)
1156 ("el" . emacs)
1157 ("bib" . emacs)
1159 "External applications for opening `file:path' items in a document.
1160 Org-mode uses system defaults for different file types, but
1161 you can use this variable to set the application for a given file
1162 extension. The entries in this list are cons cells where the car identifies
1163 files and the cdr the corresponding command. Possible values for the
1164 file identifier are
1165 \"ext\" A string identifying an extension
1166 `directory' Matches a directory
1167 `remote' Matches a remote file, accessible through tramp or efs.
1168 Remote files most likely should be visited through Emacs
1169 because external applications cannot handle such paths.
1170 t Default for all remaining files
1172 Possible values for the command are:
1173 `emacs' The file will be visited by the current Emacs process.
1174 `default' Use the default application for this file type.
1175 string A command to be executed by a shell; %s will be replaced
1176 by the path to the file.
1177 sexp A Lisp form which will be evaluated. The file path will
1178 be available in the Lisp variable `file'.
1179 For more examples, see the system specific constants
1180 `org-file-apps-defaults-macosx'
1181 `org-file-apps-defaults-windowsnt'
1182 `org-file-apps-defaults-gnu'."
1183 :group 'org-link-follow
1184 :type '(repeat
1185 (cons (choice :value ""
1186 (string :tag "Extension")
1187 (const :tag "Default for unrecognized files" t)
1188 (const :tag "Remote file" remote)
1189 (const :tag "Links to a directory" directory))
1190 (choice :value ""
1191 (const :tag "Visit with Emacs" emacs)
1192 (const :tag "Use system default" default)
1193 (string :tag "Command")
1194 (sexp :tag "Lisp form")))))
1196 (defcustom org-mhe-search-all-folders nil
1197 "Non-nil means, that the search for the mh-message will be extended to
1198 all folders if the message cannot be found in the folder given in the link.
1199 Searching all folders is very effective with one of the search engines
1200 supported by MH-E, but will be slow with pick."
1201 :group 'org-link-follow
1202 :type 'boolean)
1204 (defgroup org-remember nil
1205 "Options concerning interaction with remember.el."
1206 :tag "Org Remember"
1207 :group 'org)
1209 (defcustom org-directory "~/org"
1210 "Directory with org files.
1211 This directory will be used as default to prompt for org files.
1212 Used by the hooks for remember.el."
1213 :group 'org-remember
1214 :type 'directory)
1216 (defcustom org-default-notes-file "~/.notes"
1217 "Default target for storing notes.
1218 Used by the hooks for remember.el. This can be a string, or nil to mean
1219 the value of `remember-data-file'."
1220 :group 'org-remember
1221 :type '(choice
1222 (const :tag "Default from remember-data-file" nil)
1223 file))
1225 (defcustom org-remember-templates nil
1226 "Templates for the creation of remember buffers.
1227 When nil, just let remember make the buffer.
1228 When not nil, this is a list of 3-element lists. In each entry, the first
1229 element is a character, a unique key to select this template.
1230 The second element is the template. The third element is optional and can
1231 specify a destination file for remember items created with this template.
1232 The default file is given by `org-default-notes-file'.
1234 The template specifies the structure of the remember buffer. It should have
1235 a first line starting with a star, to act as the org-mode headline.
1236 Furthermore, the following %-escapes will be replaced with content:
1237 %t time stamp, date only
1238 %T time stamp with date and time
1239 %u inactive time stamp, date only
1240 %U inactive time stamp with date and time
1241 %n user name
1242 %a annotation, normally the link created with org-store-link
1243 %i initial content, the region when remember is called with C-u.
1244 If %i is indented, the entire inserted text will be indented as well.
1245 %? This will be removed, and the cursor placed at this position."
1246 :group 'org-remember
1247 :type '(repeat :tag "enabled"
1248 (list :value (?a "\n" nil)
1249 (character :tag "Selection Key")
1250 (string :tag "Template")
1251 (file :tag "Destination file (optional)"))))
1253 (defcustom org-reverse-note-order nil
1254 "Non-nil means, store new notes at the beginning of a file or entry.
1255 When nil, new notes will be filed to the end of a file or entry."
1256 :group 'org-remember
1257 :type '(choice
1258 (const :tag "Reverse always" t)
1259 (const :tag "Reverse never" nil)
1260 (repeat :tag "By file name regexp"
1261 (cons regexp boolean))))
1263 (defgroup org-todo nil
1264 "Options concerning TODO items in Org-mode."
1265 :tag "Org TODO"
1266 :group 'org)
1268 (defcustom org-todo-keywords '("TODO" "DONE")
1269 "List of TODO entry keywords.
1270 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1271 considered to mean that the entry is \"done\". All the other mean that
1272 action is required, and will make the entry show up in todo lists, diaries
1273 etc.
1274 The command \\[org-todo] cycles an entry through these states, and an
1275 additional state where no keyword is present. For details about this
1276 cycling, see also the variable `org-todo-interpretation'
1277 Changes become only effective after restarting Emacs."
1278 :group 'org-todo
1279 :group 'org-keywords
1280 :type '(repeat (string :tag "Keyword")))
1282 (defcustom org-todo-interpretation 'sequence
1283 "Controls how TODO keywords are interpreted.
1284 This variable is only relevant if `org-todo-keywords' contains more than two
1285 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1287 When `sequence', \\[org-todo] will always switch to the next state in the
1288 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1289 to state when executed several times in direct succession. Otherwise, it
1290 switches directly to DONE from any state.
1291 See the manual for more information."
1292 :group 'org-todo
1293 :group 'org-keywords
1294 :type '(choice (const sequence)
1295 (const type)))
1297 (defcustom org-after-todo-state-change-hook nil
1298 "Hook which is run after the state of a TODO item was changed.
1299 The new state (a string with a TODO keyword, or nil) is available in the
1300 Lisp variable `state'."
1301 :group 'org-todo
1302 :type 'hook)
1304 (defcustom org-log-done nil
1305 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1306 When the state of an entry is changed from nothing to TODO, remove a previous
1307 closing date.
1309 This can also be a list of symbols indicating under which conditions
1310 the time stamp recording the action should be annotated with a short note.
1311 Valid members of this list are
1313 done Offer to record a note when marking entries done
1314 clock-out Offer to record a note when clocking out of an item.
1316 A separate window will then pop up and allow you to type a note.
1317 After finishing with C-c C-c, the note will be added directly after the
1318 timestamp, as a plain list item. See also the variable
1319 `org-log-note-headings'.
1321 Logging can also be configured on a per-file basis by adding one of
1322 the following lines anywhere in the buffer:
1324 #+STARTUP: logging
1325 #+STARTUP: nologging"
1326 ;; FIXME: in-buffer words for notes???????
1327 :group 'org-todo
1328 :type '(choice
1329 (const :tag "off" nil)
1330 (const :tag "on" t)
1331 (set :tag "on, with notes" :greedy t :value (done)
1332 (const done) (const clock-out))))
1334 (defcustom org-log-note-headings '((done . "CLOSING NOTE %t") (clock-out . ""))
1335 "Headings for notes added when clocking out or closing TODO items.
1336 The value is an alist, with the car being a sympol indicating the note
1337 context, and the cdr is the heading to be used. The heading may also be the
1338 empty string.
1339 %t in the heading will be replaced by a time stamp
1340 %u will be replaced by the user name
1341 %U will be replaced by the full user name."
1342 :group 'org-todo
1343 :type '(list :greedy t
1344 (cons (const :tag "Heading when closing an item" done) string)
1345 (cons (const :tag "Heading when clocking out" clock-out) string)))
1347 (defgroup org-priorities nil
1348 "Priorities in Org-mode."
1349 :tag "Org Priorities"
1350 :group 'org-todo)
1352 (defcustom org-default-priority ?B
1353 "The default priority of TODO items.
1354 This is the priority an item get if no explicit priority is given."
1355 :group 'org-priorities
1356 :type 'character)
1358 (defcustom org-lowest-priority ?C
1359 "The lowest priority of TODO items. A character like ?A, ?B etc."
1360 :group 'org-priorities
1361 :type 'character)
1363 (defgroup org-time nil
1364 "Options concerning time stamps and deadlines in Org-mode."
1365 :tag "Org Time"
1366 :group 'org)
1368 (defcustom org-insert-labeled-timestamps-at-point nil
1369 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1370 When nil, these labeled time stamps are forces into the second line of an
1371 entry, just after the headline. When scheduling from the global TODO list,
1372 the time stamp will always be forced into the second line."
1373 :group 'org-time
1374 :type 'boolean)
1376 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1377 "Formats for `format-time-string' which are used for time stamps.
1378 It is not recommended to change this constant.")
1380 (defcustom org-time-stamp-rounding-minutes 0
1381 "Number of minutes to round time stamps to upon insertion.
1382 When zero, insert the time unmodified. Useful rounding numbers
1383 should be factors of 60, so for example 5, 10, 15.
1384 When this is not zero, you can still force an exact time-stamp by using
1385 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1386 :group 'org-time
1387 :type 'integer)
1389 (defcustom org-display-custom-times nil
1390 "Non-nil means, overlay custom formats over all time stamps.
1391 The formats are defined through the variable `org-time-stamp-custom-formats'.
1392 To turn this on on a per-file basis, insert anywhere in the file:
1393 #+STARTUP: customtime"
1394 :group 'org-time
1395 :set 'set-default
1396 :type 'sexp)
1397 (make-variable-buffer-local 'org-display-custom-times)
1399 (defcustom org-time-stamp-custom-formats
1400 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1401 "Custom formats for time stamps. See `format-time-string' for the syntax.
1402 These are overlayed over the default ISO format if the variable
1403 `org-display-custom-times' is set."
1404 :group 'org-time
1405 :type 'sexp)
1407 (defun org-time-stamp-format (&optional long inactive)
1408 "Get the right format for a time string."
1409 (let ((f (if long (cdr org-time-stamp-formats)
1410 (car org-time-stamp-formats))))
1411 (if inactive
1412 (concat "[" (substring f 1 -1) "]")
1413 f)))
1415 (defcustom org-deadline-warning-days 30
1416 "No. of days before expiration during which a deadline becomes active.
1417 This variable governs the display in sparse trees and in the agenda."
1418 :group 'org-time
1419 :type 'number)
1421 (defcustom org-popup-calendar-for-date-prompt t
1422 "Non-nil means, pop up a calendar when prompting for a date.
1423 In the calendar, the date can be selected with mouse-1. However, the
1424 minibuffer will also be active, and you can simply enter the date as well.
1425 When nil, only the minibuffer will be available."
1426 :group 'org-time
1427 :type 'boolean)
1429 (defcustom org-calendar-follow-timestamp-change t
1430 "Non-nil means, make the calendar window follow timestamp changes.
1431 When a timestamp is modified and the calendar window is visible, it will be
1432 moved to the new date."
1433 :group 'org-time
1434 :type 'boolean)
1436 (defgroup org-tags nil
1437 "Options concerning tags in Org-mode."
1438 :tag "Org Tags"
1439 :group 'org)
1441 (defcustom org-tag-alist nil
1442 "List of tags allowed in Org-mode files.
1443 When this list is nil, Org-mode will base TAG input on what is already in the
1444 buffer.
1445 The value of this variable is an alist, the car may be (and should) be a
1446 character that is used to select that tag through the fast-tag-selection
1447 interface. See the manual for details."
1448 :group 'org-tags
1449 :type '(repeat
1450 (choice
1451 (cons (string :tag "Tag name")
1452 (character :tag "Access char"))
1453 (const :tag "Start radio group" (:startgroup))
1454 (const :tag "End radio group" (:endgroup)))))
1456 (defcustom org-use-fast-tag-selection 'auto
1457 "Non-nil means, use fast tag selection scheme.
1458 This is a special interface to select and deselect tags with single keys.
1459 When nil, fast selection is never used.
1460 When the symbol `auto', fast selection is used if and only if selection
1461 characters for tags have been configured, either through the variable
1462 `org-tag-alist' or through a #+TAGS line in the buffer.
1463 When t, fast selection is always used and selection keys are assigned
1464 automatically if necessary."
1465 :group 'org-tags
1466 :type '(choice
1467 (const :tag "Always" t)
1468 (const :tag "Never" nil)
1469 (const :tag "When selection characters are configured" 'auto)))
1471 (defcustom org-fast-tag-selection-single-key nil
1472 "Non-nil means, fast tag selection exits after first change.
1473 When nil, you have to press RET to exit it.
1474 During fast tag selection, you can toggle this flag with `C-c'."
1475 :group 'org-tags
1476 :type 'boolean)
1478 (defcustom org-tags-column 48
1479 "The column to which tags should be indented in a headline.
1480 If this number is positive, it specifies the column. If it is negative,
1481 it means that the tags should be flushright to that column. For example,
1482 -79 works well for a normal 80 character screen."
1483 :group 'org-tags
1484 :type 'integer)
1486 (defcustom org-auto-align-tags t
1487 "Non-nil means, realign tags after pro/demotion of TODO state change.
1488 These operations change the length of a headline and therefore shift
1489 the tags around. With this options turned on, after each such operation
1490 the tags are again aligned to `org-tags-column'."
1491 :group 'org-tags
1492 :type 'boolean)
1494 (defcustom org-use-tag-inheritance t
1495 "Non-nil means, tags in levels apply also for sublevels.
1496 When nil, only the tags directly given in a specific line apply there.
1497 If you turn off this option, you very likely want to turn on the
1498 companion option `org-tags-match-list-sublevels'."
1499 :group 'org-tags
1500 :type 'boolean)
1502 (defcustom org-tags-match-list-sublevels nil
1503 "Non-nil means list also sublevels of headlines matching tag search.
1504 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1505 the sublevels of a headline matching a tag search often also match
1506 the same search. Listing all of them can create very long lists.
1507 Setting this variable to nil causes subtrees of a match to be skipped.
1508 This option is off by default, because inheritance in on. If you turn
1509 inheritance off, you very likely want to turn this option on.
1511 As a special case, if the tag search is restricted to TODO items, the
1512 value of this variable is ignored and sublevels are always checked, to
1513 make sure all corresponding TODO items find their way into the list."
1514 :group 'org-tags
1515 :type 'boolean)
1517 (defvar org-tags-history nil
1518 "History of minibuffer reads for tags.")
1519 (defvar org-last-tags-completion-table nil
1520 "The last used completion table for tags.")
1522 (defgroup org-agenda nil
1523 "Options concerning agenda display Org-mode."
1524 :tag "Org Agenda"
1525 :group 'org)
1527 (defvar org-category nil
1528 "Variable used by org files to set a category for agenda display.
1529 Such files should use a file variable to set it, for example
1531 -*- mode: org; org-category: \"ELisp\"
1533 or contain a special line
1535 #+CATEGORY: ELisp
1537 If the file does not specify a category, then file's base name
1538 is used instead.")
1539 (make-variable-buffer-local 'org-category)
1541 (defcustom org-agenda-files nil
1542 "The files to be used for agenda display.
1543 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1544 \\[org-remove-file]. You can also use customize to edit the list.
1546 If the value of the variable is not a list but a single file name, then
1547 the list of agenda files is actually stored and maintained in that file, one
1548 agenda file per line."
1549 :group 'org-agenda
1550 :type '(choice
1551 (repeat :tag "List of files" file)
1552 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1554 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1555 "Custom commands for the agenda.
1556 These commands will be offered on the splash screen displayed by the
1557 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1559 (key type match options)
1561 key The key (a single char as a string) to be associated with the command.
1562 type The command type, any of the following symbols:
1563 todo Entries with a specific TODO keyword, in all agenda files.
1564 tags Tags match in all agenda files.
1565 tags-todo Tags match in all agenda files, TODO entries only.
1566 todo-tree Sparse tree of specific TODO keyword in *current* file.
1567 tags-tree Sparse tree with all tags matches in *current* file.
1568 occur-tree Occur sparse tree for *current* file.
1569 match What to search for:
1570 - a single keyword for TODO keyword searches
1571 - a tags match expression for tags searches
1572 - a regular expression for occur searches
1573 options A list of option setttings, similar to that in a let form, so like
1574 this: ((opt1 val1) (opt2 val2) ...)
1576 You can also define a set of commands, to create a composite agenda buffer.
1577 In this case, an entry looks like this:
1579 (key desc (cmd1 cmd2 ...) general-options)
1581 where
1583 desc A description string to be displayed in the dispatcher menu.
1584 cmd An agenda command, similar to the above. However, tree commands
1585 are no allowed, but instead you can get agenda and global todo list.
1586 So valid commands for a set are:
1587 (agenda)
1588 (alltodo)
1589 (todo \"match\" options)
1590 (tags \"match\" options )
1591 (tags-todo \"match\" options)
1593 Each command can carry a list of options, and another set of options can be
1594 given for the whole set of commands. Individual command options take
1595 precedence over the general options."
1596 :group 'org-agenda
1597 :type '(repeat
1598 (choice
1599 (list :tag "Single command"
1600 (string :tag "Key")
1601 (choice
1602 (const :tag "Tags search (all agenda files)" tags)
1603 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1604 (const :tag "TODO keyword search (all agenda files)" todo)
1605 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1606 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1607 (const :tag "Occur tree (current buffer)" occur-tree))
1608 (string :tag "Match")
1609 (repeat :tag "Local options"
1610 (list (variable :tag "Option") (sexp :tag "Value"))))
1611 (list :tag "Command series, all agenda files"
1612 (string :tag "Key")
1613 (string :tag "Description")
1614 (repeat
1615 (choice
1616 (const :tag "Agenda" (agenda))
1617 (const :tag "TODO list" (alltodo))
1618 (list :tag "Tags search"
1619 (const :format "" tags)
1620 (string :tag "Match")
1621 (repeat :tag "Local options"
1622 (list (variable :tag "Option")
1623 (sexp :tag "Value"))))
1625 (list :tag "Tags search, TODO entries only"
1626 (const :format "" tags-todo)
1627 (string :tag "Match")
1628 (repeat :tag "Local options"
1629 (list (variable :tag "Option")
1630 (sexp :tag "Value"))))
1632 (list :tag "TODO keyword search"
1633 (const :format "" todo)
1634 (string :tag "Match")
1635 (repeat :tag "Local options"
1636 (list (variable :tag "Option")
1637 (sexp :tag "Value"))))))
1638 (repeat :tag "General options"
1639 (list (variable :tag "Option")
1640 (sexp :tag "Value")))))))
1642 (defcustom org-agenda-todo-list-sublevels t
1643 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1644 When nil, the sublevels of a TODO entry are not checked, resulting in
1645 potentially much shorter TODO lists."
1646 :group 'org-agenda
1647 :group 'org-todo
1648 :type 'boolean)
1650 (defcustom org-agenda-todo-ignore-scheduled nil
1651 "Non-nil means, don't show scheduled entries in the global todo list.
1652 The idea behind this is that by scheduling it, you have already taken care
1653 of this item."
1654 :group 'org-agenda
1655 :group 'org-todo
1656 :type 'boolean)
1658 (defcustom org-agenda-todo-ignore-deadlines nil
1659 "Non-nil means, don't show near deadline entries in the global todo list.
1660 Near means closer than `org-deadline-warning-days' days.
1661 The idea behind this is that such items will appear in the agenda anyway."
1662 :group 'org-agenda
1663 :group 'org-todo
1664 :type 'boolean)
1666 (defcustom org-agenda-skip-scheduled-if-done nil
1667 "Non-nil means don't show scheduled items in agenda when they are done.
1668 This is relevant for the daily/weekly agenda, not for the TODO list."
1669 :group 'org-agenda
1670 :type 'boolean)
1672 (defcustom org-timeline-show-empty-dates 3
1673 "Non-nil means, `org-timeline' also shows dates without an entry.
1674 When nil, only the days which actually have entries are shown.
1675 When t, all days between the first and the last date are shown.
1676 When an integer, show also empty dates, but if there is a gap of more than
1677 N days, just insert a special line indicating the size of the gap."
1678 :group 'org-agenda
1679 :type '(choice
1680 (const :tag "None" nil)
1681 (const :tag "All" t)
1682 (number :tag "at most")))
1684 (defcustom org-agenda-confirm-kill 1
1685 "When set, remote killing from the agenda buffer needs confirmation.
1686 When t, a confirmation is always needed. When a number N, confirmation is
1687 only needed when the text to be killed contains more than N non-white lines."
1688 :group 'org-agenda
1689 :type '(choice
1690 (const :tag "Never" nil)
1691 (const :tag "Always" t)
1692 (number :tag "When more than N lines")))
1694 ;; FIXME: This variable could be removed
1695 (defcustom org-agenda-include-all-todo nil
1696 "Set means weekly/daily agenda will always contain all TODO entries.
1697 The TODO entries will be listed at the top of the agenda, before
1698 the entries for specific days."
1699 :group 'org-agenda
1700 :type 'boolean)
1702 (defcustom org-agenda-include-diary nil
1703 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1704 :group 'org-agenda
1705 :type 'boolean)
1707 (defcustom org-calendar-to-agenda-key [?c]
1708 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1709 The command `org-calendar-goto-agenda' will be bound to this key. The
1710 default is the character `c' because then `c' can be used to switch back and
1711 forth between agenda and calendar."
1712 :group 'org-agenda
1713 :type 'sexp)
1715 (defgroup org-agenda-setup nil
1716 "Options concerning setting up the Agenda window in Org Mode."
1717 :tag "Org Agenda Window Setup"
1718 :group 'org-agenda)
1720 (defcustom org-agenda-window-setup 'reorganize-frame
1721 "How the agenda buffer should be displayed.
1722 Possible values for this option are:
1724 current-window Show agenda in the current window, keeping all other windows.
1725 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1726 other-window Use `switch-to-buffer-other-window' to display agenda.
1727 reorganize-frame Show only two windows on the current frame, the current
1728 window and the agenda. Also, if the option
1729 `org-fit-agenda-window' is set, resize the agenda window to
1730 try to show as much as possible of the buffer content.
1731 See also the variable `org-agenda-restore-windows-after-quit'."
1732 :group 'org-agenda-setup
1733 :type '(choice
1734 (const current-window)
1735 (const other-frame)
1736 (const other-window)
1737 (const reorganize-frame)))
1739 (defcustom org-agenda-restore-windows-after-quit nil
1740 "Non-nil means, restore window configuration open exiting agenda.
1741 Before the window configuration is changed for displaying the agenda,
1742 the current status is recorded. When the agenda is exited with
1743 `q' or `x' and this option is set, the old state is restored. If
1744 `org-agenda-window-setup' is `other-frame', the value of this
1745 option will be ignored.."
1746 :group 'org-agenda-setup
1747 :type 'boolean)
1749 ;; FIXME: I think this variable could be removed.
1750 (defcustom org-select-agenda-window t
1751 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1752 When nil, cursor will remain in the current window."
1753 :group 'org-agenda-setup
1754 :type 'boolean)
1756 ;; FIXME: I think this variable could be removed.
1757 (defcustom org-fit-agenda-window t
1758 "Non-nil means, change window size of agenda to fit content.
1759 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1760 :group 'org-agenda-setup
1761 :type 'boolean)
1763 (defcustom org-finalize-agenda-hook nil
1764 "Hook run just before displaying an agenda buffer."
1765 :group 'org-agenda-setup
1766 :type 'hook)
1768 (defcustom org-agenda-mouse-1-follows-link nil
1769 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1770 A longer mouse click will still set point. Does not wortk on XEmacs.
1771 Needs to be set before org.el is loaded."
1772 :group 'org-agenda-setup
1773 :type 'boolean)
1775 (defcustom org-agenda-start-with-follow-mode nil
1776 "The initial value of follwo-mode in a newly created agenda window."
1777 :group 'org-agenda-setup
1778 :type 'boolean)
1780 (defgroup org-agenda-display nil
1781 "Options concerning what to display initially in Agenda."
1782 :tag "Org Agenda Display"
1783 :group 'org-agenda)
1785 (defcustom org-agenda-show-all-dates t
1786 "Non-nil means, `org-agenda' shows every day in the selected range.
1787 When nil, only the days which actually have entries are shown."
1788 :group 'org-agenda-display
1789 :type 'boolean)
1791 (defcustom org-agenda-start-on-weekday 1
1792 "Non-nil means, start the overview always on the specified weekday.
1793 0 denotes Sunday, 1 denotes Monday etc.
1794 When nil, always start on the current day."
1795 :group 'org-agenda-display
1796 :type '(choice (const :tag "Today" nil)
1797 (number :tag "Weekday No.")))
1799 (defcustom org-agenda-ndays 7
1800 "Number of days to include in overview display.
1801 Should be 1 or 7."
1802 :group 'org-agenda-display
1803 :type 'number)
1805 (defcustom org-agenda-use-time-grid t
1806 "Non-nil means, show a time grid in the agenda schedule.
1807 A time grid is a set of lines for specific times (like every two hours between
1808 8:00 and 20:00). The items scheduled for a day at specific times are
1809 sorted in between these lines.
1810 For details about when the grid will be shown, and what it will look like, see
1811 the variable `org-agenda-time-grid'."
1812 :group 'org-agenda-display
1813 :type 'boolean)
1815 (defcustom org-agenda-time-grid
1816 '((daily today require-timed)
1817 "----------------"
1818 (800 1000 1200 1400 1600 1800 2000))
1820 "The settings for time grid for agenda display.
1821 This is a list of three items. The first item is again a list. It contains
1822 symbols specifying conditions when the grid should be displayed:
1824 daily if the agenda shows a single day
1825 weekly if the agenda shows an entire week
1826 today show grid on current date, independent of daily/weekly display
1827 require-timed show grid only if at least one item has a time specification
1829 The second item is a string which will be places behing the grid time.
1831 The third item is a list of integers, indicating the times that should have
1832 a grid line."
1833 :group 'org-agenda-display
1834 :type
1835 '(list
1836 (set :greedy t :tag "Grid Display Options"
1837 (const :tag "Show grid in single day agenda display" daily)
1838 (const :tag "Show grid in weekly agenda display" weekly)
1839 (const :tag "Always show grid for today" today)
1840 (const :tag "Show grid only if any timed entries are present"
1841 require-timed)
1842 (const :tag "Skip grid times already present in an entry"
1843 remove-match))
1844 (string :tag "Grid String")
1845 (repeat :tag "Grid Times" (integer :tag "Time"))))
1847 (let ((sorting-choice
1848 '(choice
1849 (const time-up) (const time-down)
1850 (const category-keep) (const category-up) (const category-down)
1851 (const tag-down) (const tag-up)
1852 (const priority-up) (const priority-down))))
1854 (defcustom org-agenda-sorting-strategy
1855 '((agenda time-up category-keep priority-down)
1856 (todo category-keep priority-down)
1857 (tags category-keep))
1858 "Sorting structure for the agenda items of a single day.
1859 This is a list of symbols which will be used in sequence to determine
1860 if an entry should be listed before another entry. The following
1861 symbols are recognized:
1863 time-up Put entries with time-of-day indications first, early first
1864 time-down Put entries with time-of-day indications first, late first
1865 category-keep Keep the default order of categories, corresponding to the
1866 sequence in `org-agenda-files'.
1867 category-up Sort alphabetically by category, A-Z.
1868 category-down Sort alphabetically by category, Z-A.
1869 tag-up Sort alphabetically by last tag, A-Z.
1870 tag-down Sort alphabetically by last tag, Z-A.
1871 priority-up Sort numerically by priority, high priority last.
1872 priority-down Sort numerically by priority, high priority first.
1874 The different possibilities will be tried in sequence, and testing stops
1875 if one comparison returns a \"not-equal\". For example, the default
1876 '(time-up category-keep priority-down)
1877 means: Pull out all entries having a specified time of day and sort them,
1878 in order to make a time schedule for the current day the first thing in the
1879 agenda listing for the day. Of the entries without a time indication, keep
1880 the grouped in categories, don't sort the categories, but keep them in
1881 the sequence given in `org-agenda-files'. Within each category sort by
1882 priority.
1884 Leaving out `category-keep' would mean that items will be sorted across
1885 categories by priority."
1886 :group 'org-agenda-display
1887 :type `(choice
1888 (repeat :tag "General" ,sorting-choice)
1889 (list :tag "Individually"
1890 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1891 (repeat ,sorting-choice))
1892 (cons (const :tag "Strategy for TODO lists" todo)
1893 (repeat ,sorting-choice))
1894 (cons (const :tag "Strategy for Tags matches" tags)
1895 (repeat ,sorting-choice))))))
1897 (defcustom org-sort-agenda-notime-is-late t
1898 "Non-nil means, items without time are considered late.
1899 This is only relevant for sorting. When t, items which have no explicit
1900 time like 15:30 will be considered as 99:01, i.e. later than any items which
1901 do have a time. When nil, the default time is before 0:00. You can use this
1902 option to decide if the schedule for today should come before or after timeless
1903 agenda entries."
1904 :group 'org-agenda-display
1905 :type 'boolean)
1907 (defgroup org-agenda-prefix nil
1908 "Options concerning the entry prefix in the Org-mode agenda display."
1909 :tag "Org Agenda Prefix"
1910 :group 'org-agenda)
1912 (defcustom org-agenda-prefix-format
1913 '((agenda . " %-12:c%?-12t% s")
1914 (timeline . " % s")
1915 (todo . " %-12:c")
1916 (tags . " %-12:c"))
1917 "Format specifications for the prefix of items in the agenda views.
1918 An alist with four entries, for the different agenda types. The keys to the
1919 sublists are `agenda', `timeline', `todo', and `tags'. The values
1920 are format strings.
1921 This format works similar to a printf format, with the following meaning:
1923 %c the category of the item, \"Diary\" for entries from the diary, or
1924 as given by the CATEGORY keyword or derived from the file name.
1925 %T the *last* tag of the item. Last because inherited tags come
1926 first in the list.
1927 %t the time-of-day specification if one applies to the entry, in the
1928 format HH:MM
1929 %s Scheduling/Deadline information, a short string
1931 All specifiers work basically like the standard `%s' of printf, but may
1932 contain two additional characters: A question mark just after the `%' and
1933 a whitespace/punctuation character just before the final letter.
1935 If the first character after `%' is a question mark, the entire field
1936 will only be included if the corresponding value applies to the
1937 current entry. This is useful for fields which should have fixed
1938 width when present, but zero width when absent. For example,
1939 \"%?-12t\" will result in a 12 character time field if a time of the
1940 day is specified, but will completely disappear in entries which do
1941 not contain a time.
1943 If there is punctuation or whitespace character just before the final
1944 format letter, this character will be appended to the field value if
1945 the value is not empty. For example, the format \"%-12:c\" leads to
1946 \"Diary: \" if the category is \"Diary\". If the category were be
1947 empty, no additional colon would be interted.
1949 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1950 - Indent the line with two space characters
1951 - Give the category in a 12 chars wide field, padded with whitespace on
1952 the right (because of `-'). Append a colon if there is a category
1953 (because of `:').
1954 - If there is a time-of-day, put it into a 12 chars wide field. If no
1955 time, don't put in an empty field, just skip it (because of '?').
1956 - Finally, put the scheduling information and append a whitespace.
1958 As another example, if you don't want the time-of-day of entries in
1959 the prefix, you could use:
1961 (setq org-agenda-prefix-format \" %-11:c% s\")
1963 See also the variables `org-agenda-remove-times-when-in-prefix' and
1964 `org-agenda-remove-tags-when-in-prefix'."
1965 :type '(choice
1966 (string :tag "General format")
1967 (list :greedy t :tag "View dependent"
1968 (cons (const agenda) (string :tag "Format"))
1969 (cons (const timeline) (string :tag "Format"))
1970 (cons (const todo) (string :tag "Format"))
1971 (cons (const tags) (string :tag "Format"))))
1972 :group 'org-agenda-prefix)
1974 (defvar org-prefix-format-compiled nil
1975 "The compiled version of the most recently used prefix format.
1976 See the variable `org-agenda-prefix-format'.")
1978 (defcustom org-agenda-remove-times-when-in-prefix t
1979 "Non-nil means, remove duplicate time specifications in agenda items.
1980 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1981 time-of-day specification in a headline or diary entry is extracted and
1982 placed into the prefix. If this option is non-nil, the original specification
1983 \(a timestamp or -range, or just a plain time(range) specification like
1984 11:30-4pm) will be removed for agenda display. This makes the agenda less
1985 cluttered.
1986 The option can be t or nil. It may also be the symbol `beg', indicating
1987 that the time should only be removed what it is located at the beginning of
1988 the headline/diary entry."
1989 :group 'org-agenda-prefix
1990 :type '(choice
1991 (const :tag "Always" t)
1992 (const :tag "Never" nil)
1993 (const :tag "When at beginning of entry" beg)))
1995 (defcustom org-agenda-remove-tags-when-in-prefix nil
1996 "Non-nil means, remove the tags from the headline copy in the agenda.
1997 When this is the symbol `prefix', only remove tags when
1998 `org-agenda-prefix-format' contains a `%T' specifier."
1999 :group 'org-agenda-prefix
2000 :type '(choice
2001 (const :tag "Always" t)
2002 (const :tag "Never" nil)
2003 (const :tag "When prefix format contains %T" prefix)))
2005 (defcustom org-agenda-align-tags-to-column 65
2006 "Shift tags in agenda items to this column."
2007 :group 'org-agenda-prefix
2008 :type 'integer)
2010 (defgroup org-latex nil
2011 "Options for embedding LaTeX code into Org-mode"
2012 :tag "Org LaTeX"
2013 :group 'org)
2015 (defcustom org-format-latex-options
2016 '(:foreground "Black" :background "Transparent" :scale 1.0
2017 :matchers ("begin" "$" "$$" "\\(" "\\["))
2018 "Options for creating images from LaTeX fragments.
2019 This is a property list with the following properties:
2020 :foreground the foreground color, for example \"Black\".
2021 :background the background color, or \"Transparent\".
2022 :scale a scaling factor for the size of the images
2023 :matchers a list indicating which matchers should be used to
2024 find LaTeX fragments. Valid members of this list are:
2025 \"begin\" find environments
2026 \"$\" find math expressions surrounded by $...$
2027 \"$$\" find math expressions surrounded by $$....$$
2028 \"\\(\" find math expressions surrounded by \\(...\\)
2029 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2030 :group 'org-latex
2031 :type 'plist)
2033 (defgroup org-export nil
2034 "Options for exporting org-listings."
2035 :tag "Org Export"
2036 :group 'org)
2038 (defgroup org-export-general nil
2039 "General options for exporting Org-mode files."
2040 :tag "Org Export General"
2041 :group 'org-export)
2043 (defcustom org-export-publishing-directory "."
2044 "Path to the location where exported files should be located.
2045 This path may be relative to the directory where the Org-mode file lives.
2046 The default is to put them into the same directory as the Org-mode file.
2047 The variable may also be an alist with export types `:html', `:ascii',
2048 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2049 is relative, it is interpreted relative to the directory where the exported
2050 Org-mode files lives."
2051 :group 'org-export-general
2052 :type '(choice
2053 (directory)
2054 (repeat
2055 (cons
2056 (choice :tag "Type"
2057 (const :html) (const :ascii) (const :ical) (const :xoxo))
2058 (directory)))))
2060 (defcustom org-export-language-setup
2061 '(("en" "Author" "Date" "Table of Contents")
2062 ("cs" "Autor" "Datum" "Obsah")
2063 ("da" "Ophavsmand" "Dato" "Indhold")
2064 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2065 ("es" "Autor" "Fecha" "\xccndice")
2066 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2067 ("it" "Autore" "Data" "Indice")
2068 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2069 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2070 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2071 "Terms used in export text, translated to different languages.
2072 Use the variable `org-export-default-language' to set the language,
2073 or use the +OPTION lines for a per-file setting."
2074 :group 'org-export-general
2075 :type '(repeat
2076 (list
2077 (string :tag "HTML language tag")
2078 (string :tag "Author")
2079 (string :tag "Date")
2080 (string :tag "Table of Contents"))))
2082 (defcustom org-export-default-language "en"
2083 "The default language of HTML export, as a string.
2084 This should have an association in `org-export-language-setup'."
2085 :group 'org-export-general
2086 :type 'string)
2088 (defcustom org-export-headline-levels 3
2089 "The last level which is still exported as a headline.
2090 Inferior levels will produce itemize lists when exported.
2091 Note that a numeric prefix argument to an exporter function overrides
2092 this setting.
2094 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2095 :group 'org-export-general
2096 :type 'number)
2098 (defcustom org-export-with-section-numbers t
2099 "Non-nil means, add section numbers to headlines when exporting.
2101 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2102 :group 'org-export-general
2103 :type 'boolean)
2105 (defcustom org-export-with-toc t
2106 "Non-nil means, create a table of contents in exported files.
2107 The TOC contains headlines with levels up to`org-export-headline-levels'.
2109 Headlines which contain any TODO items will be marked with \"(*)\" in
2110 ASCII export, and with red color in HTML output.
2112 In HTML output, the TOC will be clickable.
2114 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2115 :group 'org-export-general
2116 :type 'boolean)
2118 (defcustom org-export-mark-todo-in-toc nil
2119 "Non-nil means, mark TOC lines that contain any open TODO items."
2120 :group 'org-export-general
2121 :type 'boolean)
2123 (defcustom org-export-preserve-breaks nil
2124 "Non-nil means, preserve all line breaks when exporting.
2125 Normally, in HTML output paragraphs will be reformatted. In ASCII
2126 export, line breaks will always be preserved, regardless of this variable.
2128 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2129 :group 'org-export-general
2130 :type 'boolean)
2132 (defcustom org-export-with-archived-trees 'headline
2133 "Whether subtrees with the ARCHIVE tag should be exported.
2134 This can have three different values
2135 nil Do not export, pretend this tree is not present
2136 t Do export the entire tree
2137 headline Only export the headline, but skip the tree below it."
2138 :group 'org-export-general
2139 :group 'org-archive
2140 :type '(choice
2141 (const :tag "not at all" nil)
2142 (const :tag "headline only" 'headline)
2143 (const :tag "entirely" t)))
2145 (defcustom org-export-with-timestamps t
2146 "If nil, do not export time stamps and associated keywords."
2147 :group 'org-export-general
2148 :type 'boolean)
2150 (defcustom org-export-remove-timestamps-from-toc t
2151 "If nil, remove timestamps from the table of contents entries."
2152 :group 'org-export-general
2153 :type 'boolean)
2155 (defcustom org-export-with-tags 'not-in-toc
2156 "If nil, do not export tags, just remove them from headlines.
2157 If this is the symbol `not-in-toc', tags will be removed from table of
2158 contents entries, but still be shown in the headlines of the document."
2159 :group 'org-export-general
2160 :type '(choice
2161 (const :tag "Off" nil)
2162 (const :tag "Not in TOC" not-in-toc)
2163 (const :tag "On" t)))
2165 (defgroup org-export-translation nil
2166 "Options for translating special ascii sequences for the export backends."
2167 :tag "Org Export Translation"
2168 :group 'org-export)
2170 (defcustom org-export-with-emphasize t
2171 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2172 If the export target supports emphasizing text, the word will be
2173 typeset in bold, italic, or underlined, respectively. Works only for
2174 single words, but you can say: I *really* *mean* *this*.
2175 Not all export backends support this.
2177 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2178 :group 'org-export-translation
2179 :type 'boolean)
2181 (defcustom org-export-with-sub-superscripts t
2182 "Non-nil means, interpret \"_\" and \"^\" for export.
2183 When this option is turned on, you can use TeX-like syntax for sub- and
2184 superscripts. Several characters after \"_\" or \"^\" will be
2185 considered as a single item - so grouping with {} is normally not
2186 needed. For example, the following things will be parsed as single
2187 sub- or superscripts.
2189 10^24 or 10^tau several digits will be considered 1 item.
2190 10^-12 or 10^-tau a leading sign with digits or a word
2191 x^2-y^3 will be read as x^2 - y^3, because items are
2192 terminated by almost any nonword/nondigit char.
2193 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2195 Still, ambiguity is possible - so when in doubt use {} to enclose the
2196 sub/superscript.
2197 Not all export backends support this, but HTML does.
2199 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2200 :group 'org-export-translation
2201 :type 'boolean)
2203 (defcustom org-export-with-TeX-macros t
2204 "Non-nil means, interpret simple TeX-like macros when exporting.
2205 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2206 No only real TeX macros will work here, but the standard HTML entities
2207 for math can be used as macro names as well. For a list of supported
2208 names in HTML export, see the constant `org-html-entities'.
2209 Not all export backends support this.
2211 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2212 :group 'org-export-translation
2213 :group 'org-latex
2214 :type 'boolean)
2216 (defcustom org-export-with-LaTeX-fragments nil
2217 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2218 When set, the exporter will find LaTeX environments if the \\begin line is
2219 the first non-white thing on a line. It will also find the math delimiters
2220 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2221 display math.
2223 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2224 :group 'org-export-translation
2225 :group 'org-latex
2226 :type 'boolean)
2228 (defcustom org-export-with-fixed-width t
2229 "Non-nil means, lines starting with \":\" will be in fixed width font.
2230 This can be used to have pre-formatted text, fragments of code etc. For
2231 example:
2232 : ;; Some Lisp examples
2233 : (while (defc cnt)
2234 : (ding))
2235 will be looking just like this in also HTML. See also the QUOTE keyword.
2236 Not all export backends support this.
2238 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2239 :group 'org-export-translation
2240 :type 'boolean)
2242 (defcustom org-match-sexp-depth 3
2243 "Number of stacked braces for sub/superscript matching.
2244 This has to be set before loading org.el to be effective."
2245 :group 'org-export-translation
2246 :type 'integer)
2248 (defgroup org-export-tables nil
2249 "Options for exporting tables in Org-mode."
2250 :tag "Org Export Tables"
2251 :group 'org-export)
2253 (defcustom org-export-with-tables t
2254 "If non-nil, lines starting with \"|\" define a table.
2255 For example:
2257 | Name | Address | Birthday |
2258 |-------------+----------+-----------|
2259 | Arthur Dent | England | 29.2.2100 |
2261 Not all export backends support this.
2263 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2264 :group 'org-export-tables
2265 :type 'boolean)
2267 (defcustom org-export-highlight-first-table-line t
2268 "Non-nil means, highlight the first table line.
2269 In HTML export, this means use <th> instead of <td>.
2270 In tables created with table.el, this applies to the first table line.
2271 In Org-mode tables, all lines before the first horizontal separator
2272 line will be formatted with <th> tags."
2273 :group 'org-export-tables
2274 :type 'boolean)
2276 (defcustom org-export-table-remove-special-lines t
2277 "Remove special lines and marking characters in calculating tables.
2278 This removes the special marking character column from tables that are set
2279 up for spreadsheet calculations. It also removes the entire lines
2280 marked with `!', `_', or `^'. The lines with `$' are kept, because
2281 the values of constants may be useful to have."
2282 :group 'org-export-tables
2283 :type 'boolean)
2285 (defcustom org-export-prefer-native-exporter-for-tables nil
2286 "Non-nil means, always export tables created with table.el natively.
2287 Natively means, use the HTML code generator in table.el.
2288 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2289 the table does not use row- or column-spanning). This has the
2290 advantage, that the automatic HTML conversions for math symbols and
2291 sub/superscripts can be applied. Org-mode's HTML generator is also
2292 much faster."
2293 :group 'org-export-tables
2294 :type 'boolean)
2296 (defgroup org-export-ascii nil
2297 "Options specific for ASCII export of Org-mode files."
2298 :tag "Org Export ASCII"
2299 :group 'org-export)
2301 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2302 "Characters for underlining headings in ASCII export.
2303 In the given sequence, these characters will be used for level 1, 2, ..."
2304 :group 'org-export-ascii
2305 :type '(repeat character))
2307 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2308 "Bullet characters for headlines converted to lists in ASCII export.
2309 The first character is is used for the first lest level generated in this
2310 way, and so on. If there are more levels than characters given here,
2311 the list will be repeated.
2312 Note that plain lists will keep the same bullets as the have in the
2313 Org-mode file."
2314 :group 'org-export-ascii
2315 :type '(repeat character))
2317 (defcustom org-export-ascii-show-new-buffer t
2318 "Non-nil means, popup buffer containing the exported ASCII text.
2319 Otherwise the buffer will just be saved to a file and stay hidden."
2320 :group 'org-export-ascii
2321 :type 'boolean)
2323 (defgroup org-export-xml nil
2324 "Options specific for XML export of Org-mode files."
2325 :tag "Org Export XML"
2326 :group 'org-export)
2328 (defgroup org-export-html nil
2329 "Options specific for HTML export of Org-mode files."
2330 :tag "Org Export HTML"
2331 :group 'org-export)
2333 (defcustom org-export-html-style
2334 "<style type=\"text/css\">
2335 html {
2336 font-family: Times, serif;
2337 font-size: 12pt;
2339 .title { text-align: center; }
2340 .todo { color: red; }
2341 .done { color: green; }
2342 .timestamp { color: grey }
2343 .timestamp-kwd { color: CadetBlue }
2344 .tag { background-color:lightblue; font-weight:normal }
2345 .target { background-color: lavender; }
2346 pre {
2347 border: 1pt solid #AEBDCC;
2348 background-color: #F3F5F7;
2349 padding: 5pt;
2350 font-family: courier, monospace;
2352 table { border-collapse: collapse; }
2353 td, th {
2354 vertical-align: top;
2355 border: 1pt solid #ADB9CC;
2357 </style>"
2358 "The default style specification for exported HTML files.
2359 Since there are different ways of setting style information, this variable
2360 needs to contain the full HTML structure to provide a style, including the
2361 surrounding HTML tags. The style specifications should include definitions
2362 for new classes todo, done, title, and deadline. For example, legal values
2363 would be:
2365 <style type=\"text/css\">
2366 p { font-weight: normal; color: gray; }
2367 h1 { color: black; }
2368 .title { text-align: center; }
2369 .todo, .deadline { color: red; }
2370 .done { color: green; }
2371 </style>
2373 or, if you want to keep the style in a file,
2375 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2377 As the value of this option simply gets inserted into the HTML <head> header,
2378 you can \"misuse\" it to add arbitrary text to the header."
2379 :group 'org-export-html
2380 :type 'string)
2382 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2383 "Format for typesetting the document title in HTML export."
2384 :group 'org-export-html
2385 :type 'string)
2387 (defcustom org-export-html-toplevel-hlevel 2
2388 "The <H> level for level 1 headings in HTML export."
2389 :group 'org-export-html
2390 :type 'string)
2392 (defcustom org-export-html-link-org-files-as-html t
2393 "Non-nil means, make file links to `file.org' point to `file.html'.
2394 When org-mode is exporting an org-mode file to HTML, links to
2395 non-html files are directly put into a href tag in HTML.
2396 However, links to other Org-mode files (recognized by the
2397 extension `.org.) should become links to the corresponding html
2398 file, assuming that the linked org-mode file will also be
2399 converted to HTML.
2400 When nil, the links still point to the plain `.org' file."
2401 :group 'org-export-html
2402 :type 'boolean)
2404 (defcustom org-export-html-inline-images 'maybe
2405 "Non-nil means, inline images into exported HTML pages.
2406 This is done using an <img> tag. When nil, an anchor with href is used to
2407 link to the image. If this option is `maybe', then images in links with
2408 an empty description will be inlined, while images with a description will
2409 be linked only."
2410 :group 'org-export-html
2411 :type '(choice (const :tag "Never" nil)
2412 (const :tag "Always" t)
2413 (const :tag "When there is no description" maybe)))
2415 (defcustom org-export-html-expand t
2416 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2417 When nil, these tags will be exported as plain text and therefore
2418 not be interpreted by a browser.
2420 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2421 :group 'org-export-html
2422 :type 'boolean)
2424 (defcustom org-export-html-table-tag
2425 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2426 "The HTML tag used to start a table.
2427 This must be a <table> tag, but you may change the options like
2428 borders and spacing."
2429 :group 'org-export-html
2430 :type 'string)
2432 (defcustom org-export-html-with-timestamp nil
2433 "If non-nil, write `org-export-html-html-helper-timestamp'
2434 into the exported HTML text. Otherwise, the buffer will just be saved
2435 to a file."
2436 :group 'org-export-html
2437 :type 'boolean)
2439 (defcustom org-export-html-html-helper-timestamp
2440 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2441 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2442 :group 'org-export-html
2443 :type 'string)
2445 (defcustom org-export-html-show-new-buffer nil
2446 "Non-nil means, popup buffer containing the exported html text.
2447 Otherwise, the buffer will just be saved to a file and stay hidden."
2448 :group 'org-export-html
2449 :type 'boolean)
2451 (defgroup org-export-icalendar nil
2452 "Options specific for iCalendar export of Org-mode files."
2453 :tag "Org Export iCalendar"
2454 :group 'org-export)
2456 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2457 "The file name for the iCalendar file covering all agenda files.
2458 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2459 The file name should be absolute."
2460 :group 'org-export-icalendar
2461 :type 'file)
2463 (defcustom org-icalendar-include-todo nil
2464 "Non-nil means, export to iCalendar files should also cover TODO items."
2465 :group 'org-export-icalendar
2466 :type 'boolean)
2468 (defcustom org-icalendar-combined-name "OrgMode"
2469 "Calendar name for the combined iCalendar representing all agenda files."
2470 :group 'org-export-icalendar
2471 :type 'string)
2473 (defgroup org-font-lock nil
2474 "Font-lock settings for highlighting in Org-mode."
2475 :tag "Org Font Lock"
2476 :group 'org)
2478 (defcustom org-level-color-stars-only nil
2479 "Non-nil means fontify only the stars in each headline.
2480 When nil, the entire headline is fontified.
2481 Changing it requires restart of `font-lock-mode' to become effective
2482 also in regions already fontified."
2483 :group 'org-font-lock
2484 :type 'boolean)
2486 (defcustom org-hide-leading-stars nil
2487 "Non-nil means, hide the first N-1 stars in a headline.
2488 This works by using the face `org-hide' for these stars. This
2489 face is white for a light background, and black for a dark
2490 background. You may have to customize the face `org-hide' to
2491 make this work.
2492 Changing it requires restart of `font-lock-mode' to become effective
2493 also in regions already fontified.
2494 You may also set this on a per-file basis by adding one of the following
2495 lines to the buffer:
2497 #+STARTUP: hidestars
2498 #+STARTUP: showstars"
2499 :group 'org-font-lock
2500 :type 'boolean)
2502 (defcustom org-fontify-done-headline nil
2503 "Non-nil means, change the face of a headline if it is marked DONE.
2504 Normally, only the TODO/DONE keyword indicates the state of a headline.
2505 When this is non-nil, the headline after the keyword is set to the
2506 `org-headline-done' as an additional indication."
2507 :group 'org-font-lock
2508 :type 'boolean)
2510 (defcustom org-fontify-emphasized-text t
2511 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2512 Changing this variable requires a restart of Emacs to take effect."
2513 :group 'org-font-lock
2514 :type 'boolean)
2516 (defvar org-emph-re nil
2517 "Regular expression for matching emphasis.")
2518 (defvar org-emphasis-regexp-components) ; defined just below
2519 (defvar org-emphasis-alist) ; defined just below
2520 (defun org-set-emph-re (var val)
2521 "Set variable and compute the emphasis regular expression."
2522 (set var val)
2523 (when (and (boundp 'org-emphasis-alist)
2524 (boundp 'org-emphasis-regexp-components)
2525 org-emphasis-alist org-emphasis-regexp-components)
2526 (let* ((e org-emphasis-regexp-components)
2527 (pre (car e))
2528 (post (nth 1 e))
2529 (border (nth 2 e))
2530 (body (nth 3 e))
2531 (nl (nth 4 e))
2532 (stacked (nth 5 e))
2533 (body1 (concat body "*?"))
2534 (markers (mapconcat 'car org-emphasis-alist "")))
2535 ;; make sure special characters appear at the right position in the class
2536 (if (string-match "\\^" markers)
2537 (setq markers (concat (replace-match "" t t markers) "^")))
2538 (if (string-match "-" markers)
2539 (setq markers (concat (replace-match "" t t markers) "-")))
2540 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2541 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2542 (if (> nl 0)
2543 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2544 (int-to-string nl) "\\}")))
2545 ;; Make the regexp
2546 (setq org-emph-re
2547 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2548 "\\("
2549 "\\([" markers "]\\)"
2550 "\\("
2551 "[^" border markers "]"
2552 body1
2553 "[^" border markers "]"
2554 "\\)"
2555 "\\3\\)"
2556 "\\([" post (if stacked markers) "]\\|$\\)")))))
2558 (defcustom org-emphasis-regexp-components
2559 '(" \t(" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2560 "Components used to build the reqular expression for emphasis.
2561 This is a list with 6 entries. Terminology: In an emphasis string
2562 like \" *strong word* \", we call the initial space PREMATCH, the final
2563 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2564 and \"trong wor\" is the body. The different components in this variable
2565 specify what is allowed/forbidden in each part:
2567 pre Chars allowed as prematch. Beginning of line will be allowed too.
2568 post Chars allowed as postmatch. End of line will be allowed too.
2569 border The chars *forbidden* as border characters. In addition to the
2570 characters given here, all marker characters are forbidden too.
2571 body-regexp A regexp like \".\" to match a body character. Don't use
2572 non-shy groups here, and don't allow newline here.
2573 newline The maximum number of newlines allowed in an emphasis exp.
2574 stacked Non-nil means, allow stacked styles. This works only in HTML
2575 export. When this is set, all marker characters (as given in
2576 `org-emphasis-alist') will be allowed as pre/post, aiding
2577 inside-out matching.
2578 Use customize to modify this, or restart Emacs after changing it."
2579 :group 'org-font-lock
2580 :set 'org-set-emph-re
2581 :type '(list
2582 (sexp :tag "Allowed chars in pre ")
2583 (sexp :tag "Allowed chars in post ")
2584 (sexp :tag "Forbidden chars in border ")
2585 (sexp :tag "Regexp for body ")
2586 (integer :tag "number of newlines allowed")
2587 (boolean :tag "Stacking allowed ")))
2589 (defcustom org-emphasis-alist
2590 '(("*" bold "<b>" "</b>")
2591 ("/" italic "<i>" "</i>")
2592 ("_" underline "<u>" "</u>")
2593 ("=" shadow "<code>" "</code>")
2594 ("+" (:strike-through t) "<del>" "</del>")
2596 "Special syntax for emphasized text.
2597 Text starting and ending with a special character will be emphasized, for
2598 example *bold*, _underlined_ and /italic/. This variable sets the marker
2599 characters, the face to bbe used by font-lock for highlighting in Org-mode
2600 Emacs buffers, and the HTML tags to be used for this.
2601 Use customize to modify this, or restart Emacs after changing it."
2602 :group 'org-font-lock
2603 :set 'org-set-emph-re
2604 :type '(repeat
2605 (list
2606 (string :tag "Marker character")
2607 (choice
2608 (face :tag "Font-lock-face")
2609 (plist :tag "Face property list"))
2610 (string :tag "HTML start tag")
2611 (string :tag "HTML end tag"))))
2613 (defgroup org-faces nil
2614 "Faces in Org-mode."
2615 :tag "Org Faces"
2616 :group 'org-font-lock)
2618 (defun org-compatible-face (specs)
2619 "Make a compatible face specification.
2620 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2621 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2622 to the top of the list. The `min-colors' attribute will be removed from
2623 any other entries, and any resulting duplicates will be removed entirely."
2624 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2625 (let (r e a)
2626 (while (setq e (pop specs))
2627 (cond
2628 ((memq (car e) '(t default)) (push e r))
2629 ((setq a (member '(min-colors 8) (car e)))
2630 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2631 (cdr e)))))
2632 ((setq a (assq 'min-colors (car e)))
2633 (setq e (cons (delq a (car e)) (cdr e)))
2634 (or (assoc (car e) r) (push e r)))
2635 (t (or (assoc (car e) r) (push e r)))))
2636 (nreverse r))
2637 specs))
2639 (defface org-hide
2640 '((((background light)) (:foreground "white"))
2641 (((background dark)) (:foreground "black")))
2642 "Face used to hide leading stars in headlines.
2643 The forground color of this face should be equal to the background
2644 color of the frame."
2645 :group 'org-faces)
2647 (defface org-level-1 ;; font-lock-function-name-face
2648 (org-compatible-face
2649 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2650 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2651 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2652 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2653 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2654 (t (:bold t))))
2655 "Face used for level 1 headlines."
2656 :group 'org-faces)
2658 (defface org-level-2 ;; font-lock-variable-name-face
2659 (org-compatible-face
2660 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2661 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2662 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2663 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2664 (t (:bold t))))
2665 "Face used for level 2 headlines."
2666 :group 'org-faces)
2668 (defface org-level-3 ;; font-lock-keyword-face
2669 (org-compatible-face
2670 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2671 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2672 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2673 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2674 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2675 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2676 (t (:bold t))))
2677 "Face used for level 3 headlines."
2678 :group 'org-faces)
2680 (defface org-level-4 ;; font-lock-comment-face
2681 (org-compatible-face
2682 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2683 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2684 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2685 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2686 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2687 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2688 (t (:bold t))))
2689 "Face used for level 4 headlines."
2690 :group 'org-faces)
2692 (defface org-level-5 ;; font-lock-type-face
2693 (org-compatible-face
2694 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2695 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2696 (((class color) (min-colors 8)) (:foreground "green"))))
2697 "Face used for level 5 headlines."
2698 :group 'org-faces)
2700 (defface org-level-6 ;; font-lock-constant-face
2701 (org-compatible-face
2702 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2703 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2704 (((class color) (min-colors 8)) (:foreground "magenta"))))
2705 "Face used for level 6 headlines."
2706 :group 'org-faces)
2708 (defface org-level-7 ;; font-lock-builtin-face
2709 (org-compatible-face
2710 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2711 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2712 (((class color) (min-colors 8)) (:foreground "blue"))))
2713 "Face used for level 7 headlines."
2714 :group 'org-faces)
2716 (defface org-level-8 ;; font-lock-string-face
2717 (org-compatible-face
2718 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2719 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2720 (((class color) (min-colors 8)) (:foreground "green"))))
2721 "Face used for level 8 headlines."
2722 :group 'org-faces)
2724 (defface org-special-keyword ;; font-lock-string-face
2725 (org-compatible-face
2726 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2727 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2728 (t (:italic t))))
2729 "Face used for special keywords."
2730 :group 'org-faces)
2732 (defface org-warning ;; font-lock-warning-face
2733 (org-compatible-face
2734 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2735 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2736 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2737 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2738 (t (:bold t))))
2739 "Face for deadlines and TODO keywords."
2740 :group 'org-faces)
2742 (defface org-headline-done ;; font-lock-string-face
2743 (org-compatible-face
2744 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2745 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2746 (((class color) (min-colors 8) (background light)) (:bold nil))))
2747 "Face used to indicate that a headline is DONE.
2748 This face is only used if `org-fontify-done-headline' is set."
2749 :group 'org-faces)
2751 (defface org-archived ; similar to shadow
2752 (org-compatible-face
2753 '((((class color grayscale) (min-colors 88) (background light))
2754 (:foreground "grey50"))
2755 (((class color grayscale) (min-colors 88) (background dark))
2756 (:foreground "grey70"))
2757 (((class color) (min-colors 8) (background light))
2758 (:foreground "green"))
2759 (((class color) (min-colors 8) (background dark))
2760 (:foreground "yellow"))))
2761 "Face for headline with the ARCHIVE tag."
2762 :group 'org-faces)
2764 (defface org-link
2765 '((((class color) (background light)) (:foreground "Purple" :underline t))
2766 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2767 (t (:underline t)))
2768 "Face for links."
2769 :group 'org-faces)
2771 (defface org-date
2772 '((((class color) (background light)) (:foreground "Purple" :underline t))
2773 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2774 (t (:underline t)))
2775 "Face for links."
2776 :group 'org-faces)
2778 (defface org-tag
2779 '((t (:bold t)))
2780 "Face for tags."
2781 :group 'org-faces)
2783 (defface org-todo ;; font-lock-warning-face
2784 (org-compatible-face
2785 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2786 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2787 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2788 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2789 (t (:inverse-video t :bold t))))
2790 "Face for TODO keywords."
2791 :group 'org-faces)
2793 (defface org-done ;; font-lock-type-face
2794 (org-compatible-face
2795 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2796 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2797 (((class color) (min-colors 8)) (:foreground "green"))
2798 (t (:bold t))))
2799 "Face used for DONE."
2800 :group 'org-faces)
2802 (defface org-table ;; font-lock-function-name-face
2803 (org-compatible-face
2804 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2805 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2806 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2807 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2808 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2809 (((class color) (min-colors 8) (background dark)))))
2810 "Face used for tables."
2811 :group 'org-faces)
2813 (defface org-formula
2814 (org-compatible-face
2815 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2816 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2817 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2818 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2819 (t (:bold t :italic t))))
2820 "Face for formulas."
2821 :group 'org-faces)
2823 (defface org-scheduled-today
2824 (org-compatible-face
2825 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2826 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2827 (((class color) (min-colors 8)) (:foreground "green"))
2828 (t (:bold t :italic t))))
2829 "Face for items scheduled for a certain day."
2830 :group 'org-faces)
2832 (defface org-scheduled-previously
2833 (org-compatible-face
2834 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2835 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2836 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2837 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2838 (t (:bold t))))
2839 "Face for items scheduled previously, and not yet done."
2840 :group 'org-faces)
2842 (defface org-upcoming-deadline
2843 (org-compatible-face
2844 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2845 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2846 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2847 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2848 (t (:bold t))))
2849 "Face for items scheduled previously, and not yet done."
2850 :group 'org-faces)
2852 (defface org-time-grid ;; font-lock-variable-name-face
2853 (org-compatible-face
2854 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2855 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2856 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2857 "Face used for time grids."
2858 :group 'org-faces)
2860 (defconst org-level-faces
2861 '(org-level-1 org-level-2 org-level-3 org-level-4
2862 org-level-5 org-level-6 org-level-7 org-level-8
2864 (defconst org-n-levels (length org-level-faces))
2867 ;; Variables for pre-computed regular expressions, all buffer local
2868 (defvar org-done-string nil
2869 "The last string in `org-todo-keywords', indicating an item is DONE.")
2870 (make-variable-buffer-local 'org-done-string)
2871 (defvar org-todo-regexp nil
2872 "Matches any of the TODO state keywords.")
2873 (make-variable-buffer-local 'org-todo-regexp)
2874 (defvar org-not-done-regexp nil
2875 "Matches any of the TODO state keywords except the last one.")
2876 (make-variable-buffer-local 'org-not-done-regexp)
2877 (defvar org-todo-line-regexp nil
2878 "Matches a headline and puts TODO state into group 2 if present.")
2879 (make-variable-buffer-local 'org-todo-line-regexp)
2880 (defvar org-todo-line-tags-regexp nil
2881 "Matches a headline and puts TODO state into group 2 if present.
2882 Also put tags into group 4 if tags are present.")
2883 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2884 (defvar org-nl-done-regexp nil
2885 "Matches newline followed by a headline with the DONE keyword.")
2886 (make-variable-buffer-local 'org-nl-done-regexp)
2887 (defvar org-looking-at-done-regexp nil
2888 "Matches the DONE keyword a point.")
2889 (make-variable-buffer-local 'org-looking-at-done-regexp)
2890 (defvar org-todo-kwd-priority-p nil
2891 "Do TODO items have priorities?")
2892 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2893 (defvar org-todo-kwd-max-priority nil
2894 "Maximum priority of TODO items.")
2895 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2896 (defvar org-ds-keyword-length 12
2897 "Maximum length of the Deadline and SCHEDULED keywords.")
2898 (make-variable-buffer-local 'org-ds-keyword-length)
2899 (defvar org-deadline-regexp nil
2900 "Matches the DEADLINE keyword.")
2901 (make-variable-buffer-local 'org-deadline-regexp)
2902 (defvar org-deadline-time-regexp nil
2903 "Matches the DEADLINE keyword together with a time stamp.")
2904 (make-variable-buffer-local 'org-deadline-time-regexp)
2905 (defvar org-deadline-line-regexp nil
2906 "Matches the DEADLINE keyword and the rest of the line.")
2907 (make-variable-buffer-local 'org-deadline-line-regexp)
2908 (defvar org-scheduled-regexp nil
2909 "Matches the SCHEDULED keyword.")
2910 (make-variable-buffer-local 'org-scheduled-regexp)
2911 (defvar org-scheduled-time-regexp nil
2912 "Matches the SCHEDULED keyword together with a time stamp.")
2913 (make-variable-buffer-local 'org-scheduled-time-regexp)
2914 (defvar org-closed-time-regexp nil
2915 "Matches the CLOSED keyword together with a time stamp.")
2916 (make-variable-buffer-local 'org-closed-time-regexp)
2918 (defvar org-keyword-time-regexp nil
2919 "Matches any of the 3 keywords, together with the time stamp.")
2920 (make-variable-buffer-local 'org-keyword-time-regexp)
2921 (defvar org-maybe-keyword-time-regexp nil
2922 "Matches a timestamp, possibly preceeded by a keyword.")
2923 (make-variable-buffer-local 'org-keyword-time-regexp)
2925 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2926 rear-nonsticky t mouse-map t)
2927 "Properties to remove when a string without properties is wanted.")
2929 (defsubst org-match-string-no-properties (num &optional string)
2930 (if (featurep 'xemacs)
2931 (let ((s (match-string num string)))
2932 (remove-text-properties 0 (length s) org-rm-props s)
2934 (match-string-no-properties num string)))
2936 (defsubst org-no-properties (s)
2937 (remove-text-properties 0 (length s) org-rm-props s)
2940 (defsubst org-get-alist-option (option key)
2941 (cond ((eq key t) t)
2942 ((eq option t) t)
2943 ((assoc key option) (cdr (assoc key option)))
2944 (t (cdr (assq 'default option)))))
2946 (defsubst org-set-local (var value)
2947 "Make VAR local in current buffer and set it to VALUE."
2948 (set (make-variable-buffer-local var) value))
2950 (defsubst org-mode-p ()
2951 "Check if the current buffer is in Org-mode."
2952 (eq major-mode 'org-mode))
2954 (defsubst org-last (list)
2955 "Return the last element of LIST."
2956 (car (last list)))
2958 (defun org-let (list &rest body)
2959 (eval (cons 'let (cons list body))))
2960 (put 'org-let 'lisp-indent-function 1)
2962 (defun org-let2 (list1 list2 &rest body)
2963 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
2964 (put 'org-let2 'lisp-indent-function 2)
2966 (defconst org-startup-options
2967 '(("fold" org-startup-folded t)
2968 ("overview" org-startup-folded t)
2969 ("nofold" org-startup-folded nil)
2970 ("showall" org-startup-folded nil)
2971 ("content" org-startup-folded content)
2972 ("hidestars" org-hide-leading-stars t)
2973 ("showstars" org-hide-leading-stars nil)
2974 ("odd" org-odd-levels-only t)
2975 ("oddeven" org-odd-levels-only nil)
2976 ("align" org-startup-align-all-tables t)
2977 ("noalign" org-startup-align-all-tables nil)
2978 ("customtime" org-display-custom-times t)
2979 ("logging" org-log-done t)
2980 ("nologging" org-log-done nil)
2981 ("dlcheck" org-startup-with-deadline-check t)
2982 ("nodlcheck" org-startup-with-deadline-check nil)))
2984 (defun org-set-regexps-and-options ()
2985 "Precompute regular expressions for current buffer."
2986 (when (org-mode-p)
2987 (let ((re (org-make-options-regexp
2988 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2989 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
2990 (splitre "[ \t]+")
2991 kwds int key value cat arch tags links)
2992 (save-excursion
2993 (save-restriction
2994 (widen)
2995 (goto-char (point-min))
2996 (while (re-search-forward re nil t)
2997 (setq key (match-string 1) value (org-match-string-no-properties 2))
2998 (cond
2999 ((equal key "CATEGORY")
3000 (if (string-match "[ \t]+$" value)
3001 (setq value (replace-match "" t t value)))
3002 (setq cat (intern value)))
3003 ((equal key "SEQ_TODO")
3004 (setq int 'sequence
3005 kwds (append kwds (org-split-string value splitre))))
3006 ((equal key "PRI_TODO")
3007 (setq int 'priority
3008 kwds (append kwds (org-split-string value splitre))))
3009 ((equal key "TYP_TODO")
3010 (setq int 'type
3011 kwds (append kwds (org-split-string value splitre))))
3012 ((equal key "TAGS")
3013 (setq tags (append tags (org-split-string value splitre))))
3014 ((equal key "LINK")
3015 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3016 (push (cons (match-string 1 value)
3017 (org-trim (match-string 2 value)))
3018 links)))
3019 ((equal key "STARTUP")
3020 (let ((opts (org-split-string value splitre))
3021 l var val)
3022 (while (setq l (assoc (pop opts) org-startup-options))
3023 (setq var (nth 1 l) val (nth 2 l))
3024 (set (make-local-variable var) val))))
3025 ((equal key "ARCHIVE")
3026 (string-match " *$" value)
3027 (setq arch (replace-match "" t t value))
3028 (remove-text-properties 0 (length arch)
3029 '(face t fontified t) arch)))
3031 (and cat (org-set-local 'org-category cat))
3032 (and kwds (org-set-local 'org-todo-keywords kwds))
3033 (and arch (org-set-local 'org-archive-location arch))
3034 (and int (org-set-local 'org-todo-interpretation int))
3035 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3036 (when tags
3037 (let (e tgs)
3038 (while (setq e (pop tags))
3039 (cond
3040 ((equal e "{") (push '(:startgroup) tgs))
3041 ((equal e "}") (push '(:endgroup) tgs))
3042 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3043 (push (cons (match-string 1 e)
3044 (string-to-char (match-string 2 e)))
3045 tgs))
3046 (t (push (list e) tgs))))
3047 (org-set-local 'org-tag-alist nil)
3048 (while (setq e (pop tgs))
3049 (or (and (stringp (car e))
3050 (assoc (car e) org-tag-alist))
3051 (push e org-tag-alist))))))
3053 ;; Compute the regular expressions and other local variables
3054 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3055 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3056 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3057 (length org-scheduled-string)))
3058 org-done-string
3059 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3060 org-todo-regexp
3061 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3062 "\\|") "\\)\\>")
3063 org-not-done-regexp
3064 (concat "\\<\\("
3065 (mapconcat 'regexp-quote
3066 (nreverse (cdr (reverse org-todo-keywords)))
3067 "\\|")
3068 "\\)\\>")
3069 org-todo-line-regexp
3070 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3071 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3072 "\\)\\>\\)? *\\(.*\\)")
3073 org-nl-done-regexp
3074 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3075 org-todo-line-tags-regexp
3076 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3077 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3078 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3079 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3080 org-deadline-regexp (concat "\\<" org-deadline-string)
3081 org-deadline-time-regexp
3082 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3083 org-deadline-line-regexp
3084 (concat "\\<\\(" org-deadline-string "\\).*")
3085 org-scheduled-regexp
3086 (concat "\\<" org-scheduled-string)
3087 org-scheduled-time-regexp
3088 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3089 org-closed-time-regexp
3090 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3091 org-keyword-time-regexp
3092 (concat "\\<\\(" org-scheduled-string
3093 "\\|" org-deadline-string
3094 "\\|" org-closed-string
3095 "\\|" org-clock-string "\\)"
3096 " *[[<]\\([^]>]+\\)[]>]")
3097 org-maybe-keyword-time-regexp
3098 (concat "\\(\\<\\(" org-scheduled-string
3099 "\\|" org-deadline-string
3100 "\\|" org-closed-string
3101 "\\|" org-clock-string "\\)\\)?"
3102 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3104 (org-set-font-lock-defaults)))
3106 ;; Tell the compiler about dynamically scoped variables,
3107 ;; and variables from other packages
3108 (defvar calc-embedded-close-formula) ; defined by the calc package
3109 (defvar calc-embedded-open-formula) ; defined by the calc package
3110 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
3111 (defvar zmacs-regions) ; XEmacs regions
3112 (defvar original-date) ; dynamically scoped in calendar
3113 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
3114 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3115 (defvar org-html-entities) ; defined later in this file
3116 (defvar org-goto-start-pos) ; dynamically scoped parameter
3117 (defvar org-time-was-given) ; dynamically scoped parameter
3118 (defvar org-ts-what) ; dynamically scoped parameter
3119 (defvar org-current-export-file) ; dynamically scoped parameter
3120 (defvar org-current-export-dir) ; dynamically scoped parameter
3121 (defvar mark-active) ; Emacs only, not available in XEmacs.
3122 (defvar timecnt) ; dynamically scoped parameter
3123 (defvar levels-open) ; dynamically scoped parameter
3124 (defvar entry) ; dynamically scoped parameter
3125 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
3126 (defvar date) ; dynamically scoped parameter
3127 (defvar description) ; dynamically scoped parameter
3128 (defvar ans1) ; dynamically scoped parameter
3129 (defvar ans2) ; dynamically scoped parameter
3130 (defvar starting-day) ; local variable
3131 (defvar include-all-loc) ; local variable
3132 (defvar vm-message-pointer) ; from vm
3133 (defvar vm-folder-directory) ; from vm
3134 (defvar gnus-other-frame-object) ; from gnus
3135 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
3136 (defvar wl-summary-buffer-folder-name) ; from wanderlust
3137 (defvar gnus-group-name) ; from gnus
3138 (defvar gnus-article-current) ; from gnus
3139 (defvar w3m-current-url) ; from w3m
3140 (defvar w3m-current-title) ; from w3m
3141 (defvar mh-progs) ; from MH-E
3142 (defvar mh-current-folder) ; from MH-E
3143 (defvar mh-show-folder-buffer) ; from MH-E
3144 (defvar mh-index-folder) ; from MH-E
3145 (defvar mh-searcher) ; from MH-E
3146 (defvar org-selected-point) ; dynamically scoped parameter
3147 (defvar calendar-mode-map) ; from calendar.el
3148 (defvar last-arg) ; local variable
3149 (defvar remember-save-after-remembering) ; from remember.el
3150 (defvar remember-data-file) ; from remember.el
3151 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3152 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3153 (defvar orgtbl-mode) ; defined later in this file
3154 (defvar Info-current-file) ; from info.el
3155 (defvar Info-current-node) ; from info.el
3156 (defvar texmathp-why) ; from texmathp.el
3157 (defvar org-latex-regexps)
3158 (defvar outline-mode-menu-heading)
3159 (defvar outline-mode-menu-show)
3160 (defvar outline-mode-menu-hide)
3162 ;;; Define the mode
3164 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3165 (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."))
3167 (defvar org-struct-menu) ; defined later in this file
3168 (defvar org-org-menu) ; defined later in this file
3169 (defvar org-tbl-menu) ; defined later in this file
3171 ;; We use a before-change function to check if a table might need
3172 ;; an update.
3173 (defvar org-table-may-need-update t
3174 "Indicates that a table might need an update.
3175 This variable is set by `org-before-change-function'.
3176 `org-table-align' sets it back to nil.")
3177 (defvar org-mode-map)
3178 (defvar org-mode-hook nil)
3179 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3180 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3183 ;;;###autoload
3184 (define-derived-mode org-mode outline-mode "Org"
3185 "Outline-based notes management and organizer, alias
3186 \"Carsten's outline-mode for keeping track of everything.\"
3188 Org-mode develops organizational tasks around a NOTES file which
3189 contains information about projects as plain text. Org-mode is
3190 implemented on top of outline-mode, which is ideal to keep the content
3191 of large files well structured. It supports ToDo items, deadlines and
3192 time stamps, which magically appear in the diary listing of the Emacs
3193 calendar. Tables are easily created with a built-in table editor.
3194 Plain text URL-like links connect to websites, emails (VM), Usenet
3195 messages (Gnus), BBDB entries, and any files related to the project.
3196 For printing and sharing of notes, an Org-mode file (or a part of it)
3197 can be exported as a structured ASCII or HTML file.
3199 The following commands are available:
3201 \\{org-mode-map}"
3203 ;; Get rid of Outline menus, they are not needed
3204 ;; Need to do this here because define-derived-mode sets up
3205 ;; the keymap so late. Still, it is a waste to call this each time
3206 ;; we switch another buffer into org-mode.
3207 (if (featurep 'xemacs)
3208 (when (boundp 'outline-mode-menu-heading)
3209 ;; Assume this is Greg's port, it used easymenu
3210 (easy-menu-remove outline-mode-menu-heading)
3211 (easy-menu-remove outline-mode-menu-show)
3212 (easy-menu-remove outline-mode-menu-hide))
3213 (define-key org-mode-map [menu-bar headings] 'undefined)
3214 (define-key org-mode-map [menu-bar hide] 'undefined)
3215 (define-key org-mode-map [menu-bar show] 'undefined))
3217 (easy-menu-add org-org-menu)
3218 (easy-menu-add org-tbl-menu)
3219 (org-install-agenda-files-menu)
3220 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3221 (org-add-to-invisibility-spec '(org-cwidth))
3222 (when (featurep 'xemacs)
3223 (org-set-local 'line-move-ignore-invisible t))
3224 (setq outline-regexp "\\*+")
3225 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3226 (setq outline-level 'org-outline-level)
3227 (when (and org-ellipsis (stringp org-ellipsis))
3228 (unless org-display-table
3229 (setq org-display-table (make-display-table)))
3230 (set-display-table-slot org-display-table
3231 4 (string-to-vector org-ellipsis))
3232 (setq buffer-display-table org-display-table))
3233 (org-set-regexps-and-options)
3234 ;; Calc embedded
3235 (org-set-local 'calc-embedded-open-mode "# ")
3236 (modify-syntax-entry ?# "<")
3237 (if org-startup-truncated (setq truncate-lines t))
3238 (org-set-local 'font-lock-unfontify-region-function
3239 'org-unfontify-region)
3240 ;; Activate before-change-function
3241 (org-set-local 'org-table-may-need-update t)
3242 (org-add-hook 'before-change-functions 'org-before-change-function nil
3243 'local)
3244 ;; Check for running clock before killing a buffer
3245 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3246 ;; Paragraphs and auto-filling
3247 (org-set-autofill-regexps)
3248 (org-update-radio-target-regexp)
3250 (if (and org-insert-mode-line-in-empty-file
3251 (interactive-p)
3252 (= (point-min) (point-max)))
3253 (insert " -*- mode: org -*-\n\n"))
3255 (unless org-inhibit-startup
3256 (when org-startup-align-all-tables
3257 (let ((bmp (buffer-modified-p)))
3258 (org-table-map-tables 'org-table-align)
3259 (set-buffer-modified-p bmp)))
3260 (if org-startup-with-deadline-check
3261 (call-interactively 'org-check-deadlines)
3262 (cond
3263 ((eq org-startup-folded t)
3264 (org-cycle '(4)))
3265 ((eq org-startup-folded 'content)
3266 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3267 (org-cycle '(4)) (org-cycle '(4))))))))
3269 (defsubst org-call-with-arg (command arg)
3270 "Call COMMAND interactively, but pretend prefix are was ARG."
3271 (let ((current-prefix-arg arg)) (call-interactively command)))
3273 (defsubst org-current-line (&optional pos)
3274 (save-excursion
3275 (and pos (goto-char pos))
3276 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
3278 (defun org-current-time ()
3279 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3280 (if (> org-time-stamp-rounding-minutes 0)
3281 (let ((r org-time-stamp-rounding-minutes)
3282 (time (decode-time)))
3283 (apply 'encode-time
3284 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3285 (nthcdr 2 time))))
3286 (current-time)))
3288 (defun org-add-props (string plist &rest props)
3289 "Add text properties to entire string, from beginning to end.
3290 PLIST may be a list of properties, PROPS are individual properties and values
3291 that will be added to PLIST. Returns the string that was modified."
3292 (add-text-properties
3293 0 (length string) (if props (append plist props) plist) string)
3294 string)
3295 (put 'org-add-props 'lisp-indent-function 2)
3298 ;;; Font-Lock stuff
3300 (defvar org-mouse-map (make-sparse-keymap))
3301 (define-key org-mouse-map
3302 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3303 (define-key org-mouse-map
3304 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3305 (when org-mouse-1-follows-link
3306 (define-key org-mouse-map [follow-link] 'mouse-face))
3307 (when org-tab-follows-link
3308 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3309 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3310 (when org-return-follows-link
3311 (define-key org-mouse-map [(return)] 'org-open-at-point)
3312 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3314 (require 'font-lock)
3316 (defconst org-non-link-chars "]\t\n\r<>")
3317 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3318 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3319 (defconst org-link-re-with-space
3320 (concat
3321 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3322 "\\([^" org-non-link-chars " ]"
3323 "[^" org-non-link-chars "]*"
3324 "[^" org-non-link-chars " ]\\)>?")
3325 "Matches a link with spaces, optional angular brackets around it.")
3327 (defconst org-link-re-with-space2
3328 (concat
3329 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3330 "\\([^" org-non-link-chars " ]"
3331 "[^]\t\n\r]*"
3332 "[^" org-non-link-chars " ]\\)>?")
3333 "Matches a link with spaces, optional angular brackets around it.")
3335 (defconst org-angle-link-re
3336 (concat
3337 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3338 "\\([^" org-non-link-chars " ]"
3339 "[^" org-non-link-chars "]*"
3340 "\\)>")
3341 "Matches link with angular brackets, spaces are allowed.")
3342 (defconst org-plain-link-re
3343 (concat
3344 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3345 "\\([^]\t\n\r<>,;() ]+\\)")
3346 "Matches plain link, without spaces.")
3348 (defconst org-bracket-link-regexp
3349 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3350 "Matches a link in double brackets.")
3352 (defconst org-bracket-link-analytic-regexp
3353 (concat
3354 "\\[\\["
3355 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3356 "\\([^]]+\\)"
3357 "\\]"
3358 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3359 "\\]"))
3360 ; 1: http:
3361 ; 2: http
3362 ; 3: path
3363 ; 4: [desc]
3364 ; 5: desc
3366 (defconst org-ts-lengths
3367 (cons (length (format-time-string (car org-time-stamp-formats)))
3368 (length (format-time-string (cdr org-time-stamp-formats))))
3369 "This holds the lengths of the two different time formats.")
3370 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3371 "Regular expression for fast time stamp matching.")
3372 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3373 "Regular expression for fast time stamp matching.")
3374 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3375 "Regular expression matching time strings for analysis.")
3376 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3377 "Regular expression matching time stamps, with groups.")
3378 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3379 "Regular expression matching time stamps (also [..]), with groups.")
3380 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3381 "Regular expression matching a time stamp range.")
3382 (defconst org-tr-regexp-both
3383 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3384 "Regular expression matching a time stamp range.")
3385 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3386 org-ts-regexp "\\)?")
3387 "Regular expression matching a time stamp or time stamp range.")
3388 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3389 org-ts-regexp-both "\\)?")
3390 "Regular expression matching a time stamp or time stamp range.
3391 The time stamps may be either active or inactive.")
3393 (defvar org-emph-face nil)
3395 (defun org-do-emphasis-faces (limit)
3396 "Run through the buffer and add overlays to links."
3397 (if (re-search-forward org-emph-re limit t)
3398 (progn
3399 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3400 'face
3401 (nth 1 (assoc (match-string 3)
3402 org-emphasis-alist)))
3403 (add-text-properties (match-beginning 2) (match-end 2)
3404 '(font-lock-multiline t))
3405 (backward-char 1)
3406 t)))
3408 (defun org-activate-plain-links (limit)
3409 "Run through the buffer and add overlays to links."
3410 (if (re-search-forward org-plain-link-re limit t)
3411 (progn
3412 (add-text-properties (match-beginning 0) (match-end 0)
3413 (list 'mouse-face 'highlight
3414 'rear-nonsticky t
3415 'keymap org-mouse-map
3417 t)))
3419 (defun org-activate-angle-links (limit)
3420 "Run through the buffer and add overlays to links."
3421 (if (re-search-forward org-angle-link-re limit t)
3422 (progn
3423 (add-text-properties (match-beginning 0) (match-end 0)
3424 (list 'mouse-face 'highlight
3425 'rear-nonsticky t
3426 'keymap org-mouse-map
3428 t)))
3430 (defmacro org-maybe-intangible (props)
3431 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3432 In emacs 21, invisible text is not avoided by the command loop, so the
3433 intangible property is needed to make sure point skips this text.
3434 In Emacs 22, this is not necessary. The intangible text property has
3435 led to problems with flyspell. These problems are fixed in flyspell.el,
3436 but we still avoid setting the property in Emacs 22 and later.
3437 We use a macro so that the test can happen at compilation time."
3438 (if (< emacs-major-version 22)
3439 `(append '(intangible t) ,props)
3440 props))
3442 (defun org-activate-bracket-links (limit)
3443 "Run through the buffer and add overlays to bracketed links."
3444 (if (re-search-forward org-bracket-link-regexp limit t)
3445 (let* ((help (concat "LINK: "
3446 (org-match-string-no-properties 1)))
3447 ;; FIXME: above we should remove the escapes.
3448 ;; but that requires another match, protecting match data,
3449 ;; a lot of overhead for font-lock.
3450 (ip (org-maybe-intangible
3451 (list 'invisible 'org-link 'rear-nonsticky t
3452 'keymap org-mouse-map 'mouse-face 'highlight
3453 'help-echo help)))
3454 (vp (list 'rear-nonsticky t
3455 'keymap org-mouse-map 'mouse-face 'highlight
3456 'help-echo help)))
3457 ;; We need to remove the invisible property here. Table narrowing
3458 ;; may have made some of this invisible.
3459 (remove-text-properties (match-beginning 0) (match-end 0)
3460 '(invisible nil))
3461 (if (match-end 3)
3462 (progn
3463 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3464 (add-text-properties (match-beginning 3) (match-end 3) vp)
3465 (add-text-properties (match-end 3) (match-end 0) ip))
3466 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3467 (add-text-properties (match-beginning 1) (match-end 1) vp)
3468 (add-text-properties (match-end 1) (match-end 0) ip))
3469 t)))
3471 (defun org-activate-dates (limit)
3472 "Run through the buffer and add overlays to dates."
3473 ; (if (re-search-forward org-tsr-regexp limit t)
3474 ; (if (re-search-forward
3475 ; (if org-display-custom-times org-ts-regexp-both org-tsr-regexp-both)
3476 ; limit t)
3477 (if (re-search-forward org-tsr-regexp-both limit t)
3478 (progn
3479 (add-text-properties (match-beginning 0) (match-end 0)
3480 (list 'mouse-face 'highlight
3481 'rear-nonsticky t
3482 'keymap org-mouse-map))
3483 (when org-display-custom-times
3484 (if (match-end 3)
3485 (org-display-custom-time (match-beginning 3) (match-end 3)))
3486 (org-display-custom-time (match-beginning 1) (match-end 1)))
3487 t)))
3489 (defvar org-target-link-regexp nil
3490 "Regular expression matching radio targets in plain text.")
3491 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3492 "Regular expression matching a link target.")
3493 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3494 "Regular expression matching a link target.")
3496 (defun org-activate-target-links (limit)
3497 "Run through the buffer and add overlays to target matches."
3498 (when org-target-link-regexp
3499 (let ((case-fold-search t))
3500 (if (re-search-forward org-target-link-regexp limit t)
3501 (progn
3502 (add-text-properties (match-beginning 0) (match-end 0)
3503 (list 'mouse-face 'highlight
3504 'rear-nonsticky t
3505 'keymap org-mouse-map
3506 'help-echo "Radio target link"
3507 'org-linked-text t))
3508 t)))))
3510 (defun org-update-radio-target-regexp ()
3511 "Find all radio targets in this file and update the regular expression."
3512 (interactive)
3513 (when (memq 'radio org-activate-links)
3514 (setq org-target-link-regexp
3515 (org-make-target-link-regexp (org-all-targets 'radio)))
3516 (org-restart-font-lock)))
3518 (defun org-hide-wide-columns (limit)
3519 (let (s e)
3520 (setq s (text-property-any (point) (or limit (point-max))
3521 'org-cwidth t))
3522 (when s
3523 (setq e (next-single-property-change s 'org-cwidth))
3524 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3525 (goto-char e)
3526 t)))
3528 (defun org-restart-font-lock ()
3529 "Restart font-lock-mode, to force refontification."
3530 (when (and (boundp 'font-lock-mode) font-lock-mode)
3531 (font-lock-mode -1)
3532 (font-lock-mode 1)))
3534 (defun org-all-targets (&optional radio)
3535 "Return a list of all targets in this file.
3536 With optional argument RADIO, only find radio targets."
3537 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3538 rtn)
3539 (save-excursion
3540 (goto-char (point-min))
3541 (while (re-search-forward re nil t)
3542 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3543 rtn)))
3545 (defun org-make-target-link-regexp (targets)
3546 "Make regular expression matching all strings in TARGETS.
3547 The regular expression finds the targets also if there is a line break
3548 between words."
3549 (and targets
3550 (concat
3551 "\\<\\("
3552 (mapconcat
3553 (lambda (x)
3554 (while (string-match " +" x)
3555 (setq x (replace-match "\\s-+" t t x)))
3557 targets
3558 "\\|")
3559 "\\)\\>")))
3561 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3562 "Matches CamelCase words, possibly with a star before it.")
3564 (defun org-activate-camels (limit)
3565 "Run through the buffer and add overlays to dates."
3566 (if (re-search-forward org-camel-regexp limit t)
3567 (progn
3568 (add-text-properties (match-beginning 0) (match-end 0)
3569 (list 'mouse-face 'highlight
3570 'rear-nonsticky t
3571 'keymap org-mouse-map))
3572 t)))
3574 (defun org-activate-tags (limit)
3575 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3576 (progn
3577 (add-text-properties (match-beginning 1) (match-end 1)
3578 (list 'mouse-face 'highlight
3579 'rear-nonsticky t
3580 'keymap org-mouse-map))
3581 t)))
3583 (defun org-font-lock-level ()
3584 (save-excursion
3585 (org-back-to-heading t)
3586 (- (match-end 0) (match-beginning 0))))
3588 (defun org-outline-level ()
3589 (save-excursion
3590 (looking-at outline-regexp)
3591 (if (match-beginning 1)
3592 (+ (org-get-string-indentation (match-string 1)) 1000)
3593 (- (match-end 0) (match-beginning 0)))))
3595 (defvar org-font-lock-keywords nil)
3597 (defun org-set-font-lock-defaults ()
3598 (let* ((em org-fontify-emphasized-text)
3599 (lk org-activate-links)
3600 (org-font-lock-extra-keywords
3601 ;; Headlines
3602 (list
3603 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3604 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3605 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3606 (1 'org-table))
3607 ;; Links
3608 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3609 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3610 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3611 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3612 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3613 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3614 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3615 (if org-table-limit-column-width
3616 '(org-hide-wide-columns (0 nil append)))
3617 ;; TODO lines
3618 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3619 '(1 'org-todo t))
3620 ;; Priorities
3621 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3622 ;; Special keywords
3623 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3624 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3625 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3626 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3627 ;; Emphasis
3628 (if em
3629 (if (featurep 'xemacs)
3630 '(org-do-emphasis-faces (0 nil append))
3631 '(org-do-emphasis-faces)))
3632 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3633 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3634 2 'bold prepend)
3635 (if org-provide-checkbox-statistics
3636 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3637 (0 (org-get-checkbox-statistics-face) t)))
3638 ;; COMMENT
3639 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3640 "\\|" org-quote-string "\\)\\>")
3641 '(1 'org-special-keyword t))
3642 '("^#.*" (0 'font-lock-comment-face t))
3643 ;; DONE
3644 (if org-fontify-done-headline
3645 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3646 '(1 'org-done t) '(2 'org-headline-done t))
3647 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3648 '(1 'org-done t)))
3649 ;; Table stuff
3650 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3651 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3652 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3653 (if org-format-transports-properties-p
3654 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3655 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3657 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3658 ;; Now set the full font-lock-keywords
3659 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3660 (org-set-local 'font-lock-defaults
3661 '(org-font-lock-keywords t nil nil backward-paragraph))
3662 (kill-local-variable 'font-lock-keywords) nil))
3664 (defvar org-m nil)
3665 (defvar org-l nil)
3666 (defvar org-f nil)
3667 (defun org-get-level-face (n)
3668 "Get the right face for match N in font-lock matching of healdines."
3669 (setq org-l (- (match-end 2) (match-beginning 1)))
3670 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3671 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3672 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3673 (cond
3674 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3675 ((eq n 2) org-f)
3676 (t (if org-level-color-stars-only nil org-f))))
3678 (defun org-unfontify-region (beg end &optional maybe_loudly)
3679 "Remove fontification and activation overlays from links."
3680 (font-lock-default-unfontify-region beg end)
3681 (let* ((buffer-undo-list t)
3682 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3683 (inhibit-modification-hooks t)
3684 deactivate-mark buffer-file-name buffer-file-truename)
3685 (remove-text-properties beg end
3686 '(mouse-face t keymap t org-linked-text t
3687 rear-nonsticky t
3688 invisible t intangible t))))
3690 ;;; Visibility cycling
3692 (defvar org-cycle-global-status nil)
3693 (make-variable-buffer-local 'org-cycle-global-status)
3694 (defvar org-cycle-subtree-status nil)
3695 (make-variable-buffer-local 'org-cycle-subtree-status)
3697 ;;;###autoload
3698 (defun org-cycle (&optional arg)
3699 "Visibility cycling for Org-mode.
3701 - When this function is called with a prefix argument, rotate the entire
3702 buffer through 3 states (global cycling)
3703 1. OVERVIEW: Show only top-level headlines.
3704 2. CONTENTS: Show all headlines of all levels, but no body text.
3705 3. SHOW ALL: Show everything.
3707 - When point is at the beginning of a headline, rotate the subtree started
3708 by this line through 3 different states (local cycling)
3709 1. FOLDED: Only the main headline is shown.
3710 2. CHILDREN: The main headline and the direct children are shown.
3711 From this state, you can move to one of the children
3712 and zoom in further.
3713 3. SUBTREE: Show the entire subtree, including body text.
3715 - When there is a numeric prefix, go up to a heading with level ARG, do
3716 a `show-subtree' and return to the previous cursor position. If ARG
3717 is negative, go up that many levels.
3719 - When point is not at the beginning of a headline, execute
3720 `indent-relative', like TAB normally does. See the option
3721 `org-cycle-emulate-tab' for details.
3723 - Special case: if point is the the beginning of the buffer and there is
3724 no headline in line 1, this function will act as if called with prefix arg."
3725 (interactive "P")
3726 (let* ((outline-regexp
3727 (if (and (org-mode-p) org-cycle-include-plain-lists)
3728 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3729 outline-regexp))
3730 (bob-special (and org-cycle-global-at-bob (bobp)
3731 (not (looking-at outline-regexp))))
3732 (org-cycle-hook
3733 (if bob-special
3734 (delq 'org-optimize-window-after-visibility-change
3735 (copy-sequence org-cycle-hook))
3736 org-cycle-hook))
3737 (pos (point)))
3739 (if (or bob-special (equal arg '(4)))
3740 ;; special case: use global cycling
3741 (setq arg t))
3743 (cond
3745 ((org-at-table-p 'any)
3746 ;; Enter the table or move to the next field in the table
3747 (or (org-table-recognize-table.el)
3748 (progn
3749 (if arg (org-table-edit-field t)
3750 (org-table-justify-field-maybe)
3751 (call-interactively 'org-table-next-field)))))
3753 ((eq arg t) ;; Global cycling
3755 (cond
3756 ((and (eq last-command this-command)
3757 (eq org-cycle-global-status 'overview))
3758 ;; We just created the overview - now do table of contents
3759 ;; This can be slow in very large buffers, so indicate action
3760 (message "CONTENTS...")
3761 (org-content)
3762 (message "CONTENTS...done")
3763 (setq org-cycle-global-status 'contents)
3764 (run-hook-with-args 'org-cycle-hook 'contents))
3766 ((and (eq last-command this-command)
3767 (eq org-cycle-global-status 'contents))
3768 ;; We just showed the table of contents - now show everything
3769 (show-all)
3770 (message "SHOW ALL")
3771 (setq org-cycle-global-status 'all)
3772 (run-hook-with-args 'org-cycle-hook 'all))
3775 ;; Default action: go to overview
3776 (org-overview)
3777 (message "OVERVIEW")
3778 (setq org-cycle-global-status 'overview)
3779 (run-hook-with-args 'org-cycle-hook 'overview))))
3781 ((integerp arg)
3782 ;; Show-subtree, ARG levels up from here.
3783 (save-excursion
3784 (org-back-to-heading)
3785 (outline-up-heading (if (< arg 0) (- arg)
3786 (- (funcall outline-level) arg)))
3787 (org-show-subtree)))
3789 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3790 ;; At a heading: rotate between three different views
3791 (org-back-to-heading)
3792 (let ((goal-column 0) eoh eol eos)
3793 ;; First, some boundaries
3794 (save-excursion
3795 (org-back-to-heading)
3796 (save-excursion
3797 (beginning-of-line 2)
3798 (while (and (not (eobp)) ;; this is like `next-line'
3799 (get-char-property (1- (point)) 'invisible))
3800 (beginning-of-line 2)) (setq eol (point)))
3801 (outline-end-of-heading) (setq eoh (point))
3802 (org-end-of-subtree t) (setq eos (point))
3803 (outline-next-heading))
3804 ;; Find out what to do next and set `this-command'
3805 (cond
3806 ((and (= eos eoh)
3807 ;; Nothing is hidden behind this heading
3808 (message "EMPTY ENTRY")
3809 (setq org-cycle-subtree-status nil)))
3810 ((>= eol eos)
3811 ;; Entire subtree is hidden in one line: open it
3812 (org-show-entry)
3813 (show-children)
3814 (message "CHILDREN")
3815 (setq org-cycle-subtree-status 'children)
3816 (run-hook-with-args 'org-cycle-hook 'children))
3817 ((and (eq last-command this-command)
3818 (eq org-cycle-subtree-status 'children))
3819 ;; We just showed the children, now show everything.
3820 (org-show-subtree)
3821 (message "SUBTREE")
3822 (setq org-cycle-subtree-status 'subtree)
3823 (run-hook-with-args 'org-cycle-hook 'subtree))
3825 ;; Default action: hide the subtree.
3826 (hide-subtree)
3827 (message "FOLDED")
3828 (setq org-cycle-subtree-status 'folded)
3829 (run-hook-with-args 'org-cycle-hook 'folded)))))
3831 ;; TAB emulation
3832 (buffer-read-only (org-back-to-heading))
3834 ((org-try-cdlatex-tab))
3836 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3837 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3838 (or (and (eq org-cycle-emulate-tab 'white)
3839 (= (match-end 0) (point-at-eol)))
3840 (and (eq org-cycle-emulate-tab 'whitestart)
3841 (>= (match-end 0) pos))))
3843 (eq org-cycle-emulate-tab t))
3844 (if (and (looking-at "[ \n\r\t]")
3845 (string-match "^[ \t]*$" (buffer-substring
3846 (point-at-bol) (point))))
3847 (progn
3848 (beginning-of-line 1)
3849 (and (looking-at "[ \t]+") (replace-match ""))))
3850 (indent-relative))
3852 (t (save-excursion
3853 (org-back-to-heading)
3854 (org-cycle))))))
3856 ;;;###autoload
3857 (defun org-global-cycle (&optional arg)
3858 "Cycle the global visibility. For details see `org-cycle'."
3859 (interactive "P")
3860 (let ((org-cycle-include-plain-lists
3861 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3862 (if (integerp arg)
3863 (progn
3864 (show-all)
3865 (hide-sublevels arg)
3866 (setq org-cycle-global-status 'contents))
3867 (org-cycle '(4)))))
3869 (defun org-overview ()
3870 "Switch to overview mode, shoing only top-level headlines.
3871 Really, this shows all headlines with level equal or greater than the level
3872 of the first headline in the buffer. This is important, because if the
3873 first headline is not level one, then (hide-sublevels 1) gives confusing
3874 results."
3875 (interactive)
3876 (hide-sublevels (save-excursion
3877 (goto-char (point-min))
3878 (if (re-search-forward (concat "^" outline-regexp) nil t)
3879 (progn
3880 (goto-char (match-beginning 0))
3881 (funcall outline-level))
3882 1))))
3884 ;; FIXME: allow an argument to give a limiting level for this.
3885 (defun org-content ()
3886 "Show all headlines in the buffer, like a table of contents"
3887 (interactive)
3888 (save-excursion
3889 ;; Visit all headings and show their offspring
3890 (goto-char (point-max))
3891 (catch 'exit
3892 (while (and (progn (condition-case nil
3893 (outline-previous-visible-heading 1)
3894 (error (goto-char (point-min))))
3896 (looking-at outline-regexp))
3897 (show-branches)
3898 (if (bobp) (throw 'exit nil))))))
3901 (defun org-optimize-window-after-visibility-change (state)
3902 "Adjust the window after a change in outline visibility.
3903 This function is the default value of the hook `org-cycle-hook'."
3904 (when (get-buffer-window (current-buffer))
3905 (cond
3906 ((eq state 'overview) (org-first-headline-recenter 1))
3907 ((eq state 'content) nil)
3908 ((eq state 'all) nil)
3909 ((eq state 'folded) nil)
3910 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3911 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3913 (defun org-subtree-end-visible-p ()
3914 "Is the end of the current subtree visible?"
3915 (pos-visible-in-window-p
3916 (save-excursion (org-end-of-subtree t) (point))))
3918 (defun org-first-headline-recenter (&optional N)
3919 "Move cursor to the first headline and recenter the headline.
3920 Optional argument N means, put the headline into the Nth line of the window."
3921 (goto-char (point-min))
3922 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3923 (beginning-of-line)
3924 (recenter (prefix-numeric-value N))))
3926 (defvar org-goto-window-configuration nil)
3927 (defvar org-goto-marker nil)
3928 (defvar org-goto-map (make-sparse-keymap))
3929 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3930 (while (setq cmd (pop cmds))
3931 (substitute-key-definition cmd cmd org-goto-map global-map)))
3932 (define-key org-goto-map "\C-m" 'org-goto-ret)
3933 (define-key org-goto-map [(left)] 'org-goto-left)
3934 (define-key org-goto-map [(right)] 'org-goto-right)
3935 (define-key org-goto-map [(?q)] 'org-goto-quit)
3936 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3937 (define-key org-goto-map "\C-i" 'org-cycle)
3938 (define-key org-goto-map [(tab)] 'org-cycle)
3939 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3940 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3941 (define-key org-goto-map "n" 'outline-next-visible-heading)
3942 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3943 (define-key org-goto-map "f" 'outline-forward-same-level)
3944 (define-key org-goto-map "b" 'outline-backward-same-level)
3945 (define-key org-goto-map "u" 'outline-up-heading)
3946 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3947 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3948 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3949 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3950 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3951 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3952 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3954 (defconst org-goto-help
3955 "Select a location to jump to, press RET
3956 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3958 (defun org-goto ()
3959 "Go to a different location of the document, keeping current visibility.
3961 When you want to go to a different location in a document, the fastest way
3962 is often to fold the entire buffer and then dive into the tree. This
3963 method has the disadvantage, that the previous location will be folded,
3964 which may not be what you want.
3966 This command works around this by showing a copy of the current buffer in
3967 overview mode. You can dive into the tree in that copy, to find the
3968 location you want to reach. When pressing RET, the command returns to the
3969 original buffer in which the visibility is still unchanged. It then jumps
3970 to the new location, making it and the headline hierarchy above it visible."
3971 (interactive)
3972 (let* ((org-goto-start-pos (point))
3973 (selected-point
3974 (org-get-location (current-buffer) org-goto-help)))
3975 (if selected-point
3976 (progn
3977 (org-mark-ring-push org-goto-start-pos)
3978 (goto-char selected-point)
3979 (if (or (org-invisible-p) (org-invisible-p2))
3980 (org-show-context 'org-goto)))
3981 (error "Quit"))))
3983 (defun org-get-location (buf help)
3984 "Let the user select a location in the Org-mode buffer BUF.
3985 This function uses a recursive edit. It returns the selected position
3986 or nil."
3987 (let (org-selected-point)
3988 (save-excursion
3989 (save-window-excursion
3990 (delete-other-windows)
3991 (switch-to-buffer (get-buffer-create "*org-goto*"))
3992 (with-output-to-temp-buffer "*Help*"
3993 (princ help))
3994 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3995 (setq buffer-read-only nil)
3996 (erase-buffer)
3997 (insert-buffer-substring buf)
3998 (let ((org-startup-truncated t)
3999 (org-startup-folded t)
4000 (org-startup-align-all-tables nil)
4001 (org-startup-with-deadline-check nil))
4002 (org-mode))
4003 (setq buffer-read-only t)
4004 (if (boundp 'org-goto-start-pos)
4005 (goto-char org-goto-start-pos)
4006 (goto-char (point-min)))
4007 (org-beginning-of-line)
4008 (message "Select location and press RET")
4009 ;; now we make sure that during selection, ony very few keys work
4010 ;; and that it is impossible to switch to another window.
4011 (let ((gm (current-global-map))
4012 (overriding-local-map org-goto-map))
4013 (unwind-protect
4014 (progn
4015 (use-global-map org-goto-map)
4016 (recursive-edit))
4017 (use-global-map gm)))))
4018 (kill-buffer "*org-goto*")
4019 org-selected-point))
4021 (defun org-goto-ret (&optional arg)
4022 "Finish `org-goto' by going to the new location."
4023 (interactive "P")
4024 (setq org-selected-point (point)
4025 current-prefix-arg arg)
4026 (throw 'exit nil))
4028 (defun org-goto-left ()
4029 "Finish `org-goto' by going to the new location."
4030 (interactive)
4031 (if (org-on-heading-p)
4032 (progn
4033 (beginning-of-line 1)
4034 (setq org-selected-point (point)
4035 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4036 (throw 'exit nil))
4037 (error "Not on a heading")))
4039 (defun org-goto-right ()
4040 "Finish `org-goto' by going to the new location."
4041 (interactive)
4042 (if (org-on-heading-p)
4043 (progn
4044 (outline-end-of-subtree)
4045 (or (eobp) (forward-char 1))
4046 (setq org-selected-point (point)
4047 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4048 (throw 'exit nil))
4049 (error "Not on a heading")))
4051 (defun org-goto-quit ()
4052 "Finish `org-goto' without cursor motion."
4053 (interactive)
4054 (setq org-selected-point nil)
4055 (throw 'exit nil))
4057 ;;; Promotion, Demotion, Inserting new headlines
4059 (defvar org-ignore-region nil
4060 "To temporarily disable the active region.")
4062 (defun org-insert-heading (&optional force-heading)
4063 "Insert a new heading or item with same depth at point.
4064 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4065 If point is at the beginning of a headline, insert a sibling before the
4066 current headline. If point is in the middle of a headline, split the headline
4067 at that position and make the rest of the headline part of the sibling below
4068 the current headline."
4069 (interactive "P")
4070 (if (= (buffer-size) 0)
4071 (insert "\n* ")
4072 (when (or force-heading (not (org-insert-item)))
4073 (let* ((head (save-excursion
4074 (condition-case nil
4075 (progn
4076 (org-back-to-heading)
4077 (match-string 0))
4078 (error "*"))))
4079 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4080 pos)
4081 (cond
4082 ((and (org-on-heading-p) (bolp)
4083 (save-excursion (backward-char 1) (not (org-invisible-p))))
4084 (open-line (if blank 2 1)))
4085 ((and (bolp) (save-excursion
4086 (backward-char 1) (not (org-invisible-p))))
4087 nil)
4088 (t (newline (if blank 2 1))))
4089 (insert head) (just-one-space)
4090 (setq pos (point))
4091 (end-of-line 1)
4092 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4093 (run-hooks 'org-insert-heading-hook)))))
4095 (defun org-in-item-p ()
4096 "It the cursor inside a plain list item.
4097 Does not have to be the first line."
4098 (save-excursion
4099 (condition-case nil
4100 (progn
4101 (org-beginning-of-item)
4102 (org-at-item-p)
4104 (error nil))))
4106 (defun org-insert-item (&optional checkbox)
4107 "Insert a new item at the current level.
4108 Return t when things worked, nil when we are not in an item."
4109 (when (save-excursion
4110 (condition-case nil
4111 (progn
4112 (org-beginning-of-item)
4113 (org-at-item-p)
4114 (if (org-invisible-p) (error "Invisible item"))
4116 (error nil)))
4117 (let* ((bul (match-string 0))
4118 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
4119 (match-end 0)))
4120 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
4121 pos)
4122 (cond
4123 ((and (org-at-item-p) (<= (point) eow))
4124 ;; before the bullet
4125 (beginning-of-line 1)
4126 (open-line (if blank 2 1)))
4127 ((<= (point) eow)
4128 (beginning-of-line 1))
4129 (t (newline (if blank 2 1))))
4130 (insert bul (if checkbox "[ ]" ""))
4131 (just-one-space)
4132 (setq pos (point))
4133 (end-of-line 1)
4134 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
4135 (org-maybe-renumber-ordered-list)
4136 (and checkbox (org-update-checkbox-count-maybe))
4139 (defun org-insert-todo-heading (arg)
4140 "Insert a new heading with the same level and TODO state as current heading.
4141 If the heading has no TODO state, or if the state is DONE, use the first
4142 state (TODO by default). Also with prefix arg, force first state."
4143 (interactive "P")
4144 (when (not (org-insert-item 'checkbox))
4145 (org-insert-heading)
4146 (save-excursion
4147 (org-back-to-heading)
4148 (outline-previous-heading)
4149 (looking-at org-todo-line-regexp))
4150 (if (or arg
4151 (not (match-beginning 2))
4152 (equal (match-string 2) org-done-string))
4153 (insert (car org-todo-keywords) " ")
4154 (insert (match-string 2) " "))))
4156 (defun org-promote-subtree ()
4157 "Promote the entire subtree.
4158 See also `org-promote'."
4159 (interactive)
4160 (save-excursion
4161 (org-map-tree 'org-promote))
4162 (org-fix-position-after-promote))
4164 (defun org-demote-subtree ()
4165 "Demote the entire subtree. See `org-demote'.
4166 See also `org-promote'."
4167 (interactive)
4168 (save-excursion
4169 (org-map-tree 'org-demote))
4170 (org-fix-position-after-promote))
4173 (defun org-do-promote ()
4174 "Promote the current heading higher up the tree.
4175 If the region is active in `transient-mark-mode', promote all headings
4176 in the region."
4177 (interactive)
4178 (save-excursion
4179 (if (org-region-active-p)
4180 (org-map-region 'org-promote (region-beginning) (region-end))
4181 (org-promote)))
4182 (org-fix-position-after-promote))
4184 (defun org-do-demote ()
4185 "Demote the current heading lower down the tree.
4186 If the region is active in `transient-mark-mode', demote all headings
4187 in the region."
4188 (interactive)
4189 (save-excursion
4190 (if (org-region-active-p)
4191 (org-map-region 'org-demote (region-beginning) (region-end))
4192 (org-demote)))
4193 (org-fix-position-after-promote))
4195 (defun org-fix-position-after-promote ()
4196 "Make sure that after pro/demotion cursor position is right."
4197 (if (and (equal (char-after) ?\n)
4198 (save-excursion
4199 (skip-chars-backward "a-zA-Z0-9_@")
4200 (looking-at org-todo-regexp)))
4201 (insert " "))
4202 (and (equal (char-after) ?\ )
4203 (equal (char-before) ?*)
4204 (forward-char 1)))
4206 (defun org-get-legal-level (level &optional change)
4207 "Rectify a level change under the influence of `org-odd-levels-only'
4208 LEVEL is a current level, CHANGE is by how much the level should be
4209 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4210 even level numbers will become the next higher odd number."
4211 (if org-odd-levels-only
4212 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4213 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4214 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4215 (max 1 (+ level change))))
4217 (defun org-promote ()
4218 "Promote the current heading higher up the tree.
4219 If the region is active in `transient-mark-mode', promote all headings
4220 in the region."
4221 (org-back-to-heading t)
4222 (let* ((level (save-match-data (funcall outline-level)))
4223 (up-head (make-string (org-get-legal-level level -1) ?*))
4224 (diff (abs (- level (length up-head)))))
4225 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4226 (replace-match up-head nil t)
4227 ;; Fixup tag positioning
4228 (and org-auto-align-tags (org-set-tags nil t))
4229 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4231 (defun org-demote ()
4232 "Demote the current heading lower down the tree.
4233 If the region is active in `transient-mark-mode', demote all headings
4234 in the region."
4235 (org-back-to-heading t)
4236 (let* ((level (save-match-data (funcall outline-level)))
4237 (down-head (make-string (org-get-legal-level level 1) ?*))
4238 (diff (abs (- level (length down-head)))))
4239 (replace-match down-head nil t)
4240 ;; Fixup tag positioning
4241 (and org-auto-align-tags (org-set-tags nil t))
4242 (if org-adapt-indentation (org-fixup-indentation diff))))
4244 (defun org-sort (with-case)
4245 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4246 (interactive "P")
4247 (if (org-at-table-p)
4248 (org-call-with-arg 'org-table-sort-lines with-case)
4249 (org-call-with-arg 'org-sort-entries with-case)))
4251 (defun org-sort-entries (&optional with-case sorting-type)
4252 "Sort entries on a certain level of an outline tree.
4253 If there is an active region, the entries in the region are sorted.
4254 If not, the children of the entry at point are sorted.
4256 Sorting can be alphabetically, numerically, and by date/time as given by
4257 the first time stamp in the entry. The command prompts for the sorting
4258 type unless it has been given to the function through the SORTING-TYPE
4259 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4261 Comparing entries ignores case by default. However, with an optional argument
4262 WITH-CASE, the sorting considers case as well. With two prefix arguments
4263 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4264 (interactive "P")
4265 (let ((unique (equal with-case '(16)))
4266 start beg end entries stars re re2 p nentries (nremoved 0) last txt)
4268 ;; Find beginning and end of region to sort
4269 (if (org-region-active-p)
4270 (progn
4271 ;; we will sort the region
4272 (setq end (region-end))
4273 (goto-char (1- (setq start (region-beginning)))))
4274 ;; we will sort the children of the current headline
4275 (setq start (point) end (org-end-of-subtree))
4276 (goto-char start)
4277 (show-subtree))
4278 (outline-next-heading) ; this is the first heading to be included
4279 (setq beg (point))
4280 (if (>= (point) end) (error "Nothing to sort"))
4281 (looking-at "\\(\\*+\\)")
4282 (setq stars (match-string 1)
4283 re (concat "^" (regexp-quote stars) " +")
4284 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4285 txt (buffer-substring beg end))
4286 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4287 (if (string-match re2 txt)
4288 (error "Region to sort contains a level above the first entry"))
4289 ;; Make a list that can be sorted.
4290 ;; The car is the string for comparison, the cdr is the subtree
4291 (message "Sorting entries...")
4292 (setq entries
4293 (mapcar
4294 (lambda (x)
4295 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4296 (cons (match-string 0 x) x))
4297 (org-split-string txt re)))
4299 ;; Sort the list
4300 (setq entries (org-do-sort
4301 entries
4302 (if (org-region-active-p) "region" "children")
4303 with-case sorting-type))
4305 ;; Delete the old stuff
4306 (goto-char beg)
4307 (kill-region beg end)
4308 (setq nentries (length entries))
4309 ;; Insert the sorted entries, and remove duplicates if this is required
4310 (while (setq p (pop entries))
4311 (if (and unique (equal last (setq last (org-trim (cdr p)))))
4312 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
4313 (insert stars " " (cdr p))))
4314 (goto-char start)
4315 (message "Sorting entries...done (%d entries%s)"
4316 nentries
4317 (if unique (format ", %d duplicates removed" nremoved) ""))))
4319 (defun org-do-sort (table what &optional with-case sorting-type)
4320 "Sort TABLE of WHAT according to SORTING-TYPE.
4321 The user will be prompted for the SORTING-TYPE if the call to this
4322 function does not specify it. WHAT is only for the prompt, to indicate
4323 what is being sorted. The sorting key will be extracted from
4324 the car of the elements of the table.
4325 If WITH-CASE is non-nil, the sorting will be case-sensitive."
4326 (unless sorting-type
4327 (message
4328 "Sort %s:[a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
4329 what)
4330 (setq sorting-type (read-char-exclusive)))
4331 (let ((dcst (downcase sorting-type))
4332 extractfun comparefun)
4333 ;; Define the appropriate functions
4334 (cond
4335 ((= dcst ?n)
4336 (setq extractfun 'string-to-number
4337 comparefun (if (= dcst sorting-type) '< '>)))
4338 ((= dcst ?a)
4339 (setq extractfun (if with-case 'identity 'downcase)
4340 comparefun (if (= dcst sorting-type)
4341 'string<
4342 (lambda (a b) (and (not (string< a b))
4343 (not (string= a b)))))))
4344 ((= dcst ?t)
4345 (setq extractfun
4346 (lambda (x)
4347 (if (string-match org-ts-regexp x)
4348 (time-to-seconds
4349 (org-time-string-to-time (match-string 0 x)))
4350 0))
4351 comparefun (if (= dcst sorting-type) '< '>)))
4352 (t (error "Invalid sorting type `%c'" sorting-type)))
4354 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
4355 table)
4356 (lambda (a b) (funcall comparefun (car a) (car b))))))
4358 (defun org-map-tree (fun)
4359 "Call FUN for every heading underneath the current one."
4360 (org-back-to-heading)
4361 (let ((level (funcall outline-level)))
4362 (save-excursion
4363 (funcall fun)
4364 (while (and (progn
4365 (outline-next-heading)
4366 (> (funcall outline-level) level))
4367 (not (eobp)))
4368 (funcall fun)))))
4370 (defun org-map-region (fun beg end)
4371 "Call FUN for every heading between BEG and END."
4372 (let ((org-ignore-region t))
4373 (save-excursion
4374 (setq end (copy-marker end))
4375 (goto-char beg)
4376 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4377 (< (point) end))
4378 (funcall fun))
4379 (while (and (progn
4380 (outline-next-heading)
4381 (< (point) end))
4382 (not (eobp)))
4383 (funcall fun)))))
4385 (defun org-fixup-indentation (diff)
4386 "Change the indentation in the current entry by DIFF
4387 However, if any line in the current entry has no indentation, or if it
4388 would end up with no indentation after the change, nothing at all is done."
4389 (save-excursion
4390 (let ((end (save-excursion (outline-next-heading)
4391 (point-marker)))
4392 (prohibit (if (> diff 0)
4393 "^\\S-"
4394 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4395 col)
4396 (unless (save-excursion (re-search-forward prohibit end t))
4397 (while (re-search-forward "^[ \t]+" end t)
4398 (goto-char (match-end 0))
4399 (setq col (current-column))
4400 (if (< diff 0) (replace-match ""))
4401 (indent-to (+ diff col))))
4402 (move-marker end nil))))
4404 ;;; Vertical tree motion, cutting and pasting of subtrees
4406 (defun org-move-subtree-up (&optional arg)
4407 "Move the current subtree up past ARG headlines of the same level."
4408 (interactive "p")
4409 (org-move-subtree-down (- (prefix-numeric-value arg))))
4411 (defun org-move-subtree-down (&optional arg)
4412 "Move the current subtree down past ARG headlines of the same level."
4413 (interactive "p")
4414 (setq arg (prefix-numeric-value arg))
4415 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4416 'outline-get-last-sibling))
4417 (ins-point (make-marker))
4418 (cnt (abs arg))
4419 beg end txt folded)
4420 ;; Select the tree
4421 (org-back-to-heading)
4422 (setq beg (point))
4423 (save-match-data
4424 (save-excursion (outline-end-of-heading)
4425 (setq folded (org-invisible-p)))
4426 (outline-end-of-subtree))
4427 (outline-next-heading)
4428 (setq end (point))
4429 ;; Find insertion point, with error handling
4430 (goto-char beg)
4431 (while (> cnt 0)
4432 (or (and (funcall movfunc) (looking-at outline-regexp))
4433 (progn (goto-char beg)
4434 (error "Cannot move past superior level or buffer limit")))
4435 (setq cnt (1- cnt)))
4436 (if (> arg 0)
4437 ;; Moving forward - still need to move over subtree
4438 (progn (outline-end-of-subtree)
4439 (outline-next-heading)
4440 (if (not (or (looking-at (concat "^" outline-regexp))
4441 (bolp)))
4442 (newline))))
4443 (move-marker ins-point (point))
4444 (setq txt (buffer-substring beg end))
4445 (delete-region beg end)
4446 (insert txt)
4447 (goto-char ins-point)
4448 (if folded (hide-subtree))
4449 (move-marker ins-point nil)))
4451 (defvar org-subtree-clip ""
4452 "Clipboard for cut and paste of subtrees.
4453 This is actually only a copy of the kill, because we use the normal kill
4454 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4456 (defvar org-subtree-clip-folded nil
4457 "Was the last copied subtree folded?
4458 This is used to fold the tree back after pasting.")
4460 (defun org-cut-subtree ()
4461 "Cut the current subtree into the clipboard.
4462 This is a short-hand for marking the subtree and then cutting it."
4463 (interactive)
4464 (org-copy-subtree 'cut))
4466 (defun org-copy-subtree (&optional cut)
4467 "Cut the current subtree into the clipboard.
4468 This is a short-hand for marking the subtree and then copying it.
4469 If CUT is non-nil, actually cut the subtree."
4470 (interactive)
4471 (let (beg end folded)
4472 (org-back-to-heading)
4473 (setq beg (point))
4474 (save-match-data
4475 (save-excursion (outline-end-of-heading)
4476 (setq folded (org-invisible-p)))
4477 (outline-end-of-subtree))
4478 (if (equal (char-after) ?\n) (forward-char 1))
4479 (setq end (point))
4480 (goto-char beg)
4481 (when (> end beg)
4482 (setq org-subtree-clip-folded folded)
4483 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4484 (setq org-subtree-clip (current-kill 0))
4485 (message "%s: Subtree with %d characters"
4486 (if cut "Cut" "Copied")
4487 (length org-subtree-clip)))))
4489 (defun org-paste-subtree (&optional level tree)
4490 "Paste the clipboard as a subtree, with modification of headline level.
4491 The entire subtree is promoted or demoted in order to match a new headline
4492 level. By default, the new level is derived from the visible headings
4493 before and after the insertion point, and taken to be the inferior headline
4494 level of the two. So if the previous visible heading is level 3 and the
4495 next is level 4 (or vice versa), level 4 will be used for insertion.
4496 This makes sure that the subtree remains an independent subtree and does
4497 not swallow low level entries.
4499 You can also force a different level, either by using a numeric prefix
4500 argument, or by inserting the heading marker by hand. For example, if the
4501 cursor is after \"*****\", then the tree will be shifted to level 5.
4503 If you want to insert the tree as is, just use \\[yank].
4505 If optional TREE is given, use this text instead of the kill ring."
4506 (interactive "P")
4507 (unless (org-kill-is-subtree-p tree)
4508 (error
4509 (substitute-command-keys
4510 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4511 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4512 (^re (concat "^\\(" outline-regexp "\\)"))
4513 (re (concat "\\(" outline-regexp "\\)"))
4514 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4516 (old-level (if (string-match ^re txt)
4517 (- (match-end 0) (match-beginning 0))
4518 -1))
4519 (force-level (cond (level (prefix-numeric-value level))
4520 ((string-match
4521 ^re_ (buffer-substring (point-at-bol) (point)))
4522 (- (match-end 0) (match-beginning 0)))
4523 (t nil)))
4524 (previous-level (save-excursion
4525 (condition-case nil
4526 (progn
4527 (outline-previous-visible-heading 1)
4528 (if (looking-at re)
4529 (- (match-end 0) (match-beginning 0))
4531 (error 1))))
4532 (next-level (save-excursion
4533 (condition-case nil
4534 (progn
4535 (outline-next-visible-heading 1)
4536 (if (looking-at re)
4537 (- (match-end 0) (match-beginning 0))
4539 (error 1))))
4540 (new-level (or force-level (max previous-level next-level)))
4541 (shift (if (or (= old-level -1)
4542 (= new-level -1)
4543 (= old-level new-level))
4545 (- new-level old-level)))
4546 (shift1 shift)
4547 (delta (if (> shift 0) -1 1))
4548 (func (if (> shift 0) 'org-demote 'org-promote))
4549 (org-odd-levels-only nil)
4550 beg end)
4551 ;; Remove the forces level indicator
4552 (if force-level
4553 (delete-region (point-at-bol) (point)))
4554 ;; Make sure we start at the beginning of an empty line
4555 (if (not (bolp)) (insert "\n"))
4556 (if (not (looking-at "[ \t]*$"))
4557 (progn (insert "\n") (backward-char 1)))
4558 ;; Paste
4559 (setq beg (point))
4560 (if (string-match "[ \t\r\n]+\\'" txt)
4561 (setq txt (replace-match "\n" t t txt)))
4562 (insert txt)
4563 (setq end (point))
4564 (if (looking-at "[ \t\r\n]+")
4565 (replace-match "\n"))
4566 (goto-char beg)
4567 ;; Shift if necessary
4568 (if (= shift 0)
4569 (message "Pasted at level %d, without shift" new-level)
4570 (save-restriction
4571 (narrow-to-region beg end)
4572 (while (not (= shift 0))
4573 (org-map-region func (point-min) (point-max))
4574 (setq shift (+ delta shift)))
4575 (goto-char (point-min))
4576 (message "Pasted at level %d, with shift by %d levels"
4577 new-level shift1)))
4578 (if (and kill-ring
4579 (eq org-subtree-clip (current-kill 0))
4580 org-subtree-clip-folded)
4581 ;; The tree was folded before it was killed/copied
4582 (hide-subtree))))
4584 (defun org-kill-is-subtree-p (&optional txt)
4585 "Check if the current kill is an outline subtree, or a set of trees.
4586 Returns nil if kill does not start with a headline, or if the first
4587 headline level is not the largest headline level in the tree.
4588 So this will actually accept several entries of equal levels as well,
4589 which is OK for `org-paste-subtree'.
4590 If optional TXT is given, check this string instead of the current kill."
4591 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4592 (start-level (and kill
4593 (string-match (concat "\\`" outline-regexp) kill)
4594 (- (match-end 0) (match-beginning 0))))
4595 (re (concat "^" outline-regexp))
4596 (start 1))
4597 (if (not start-level)
4598 nil ;; does not even start with a heading
4599 (catch 'exit
4600 (while (setq start (string-match re kill (1+ start)))
4601 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4602 (throw 'exit nil)))
4603 t))))
4605 (defun org-narrow-to-subtree ()
4606 "Narrow buffer to the current subtree."
4607 (interactive)
4608 (save-excursion
4609 (narrow-to-region
4610 (progn (org-back-to-heading) (point))
4611 (progn (org-end-of-subtree t) (point)))))
4613 ;;; Plain list items
4615 (defun org-at-item-p ()
4616 "Is point in a line starting a hand-formatted item?"
4617 (let ((llt org-plain-list-ordered-item-terminator))
4618 (save-excursion
4619 (goto-char (point-at-bol))
4620 (looking-at
4621 (cond
4622 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4623 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4624 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4625 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4627 (defun org-at-item-checkbox-p ()
4628 "Is point at a line starting a plain-list item with a checklet?"
4629 (and (org-at-item-p)
4630 (save-excursion
4631 (goto-char (match-end 0))
4632 (skip-chars-forward " \t")
4633 (looking-at "\\[[ X]\\]"))))
4635 (defun org-toggle-checkbox (&optional arg)
4636 "Toggle the checkbox in the current line."
4637 (interactive "P")
4638 (catch 'exit
4639 (let (beg end status (firstnew 'unknown))
4640 (cond
4641 ((org-region-active-p)
4642 (setq beg (region-beginning) end (region-end)))
4643 ((org-on-heading-p)
4644 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4645 ((org-at-item-checkbox-p)
4646 (save-excursion
4647 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4648 (throw 'exit t))
4649 (t (error "Not at a checkbox or heading, and no active region")))
4650 (save-excursion
4651 (goto-char beg)
4652 (while (< (point) end)
4653 (when (org-at-item-checkbox-p)
4654 (setq status (equal (match-string 0) "[X]"))
4655 (when (eq firstnew 'unknown)
4656 (setq firstnew (not status)))
4657 (replace-match
4658 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4659 (beginning-of-line 2)))))
4660 (org-update-checkbox-count-maybe))
4662 (defun org-update-checkbox-count-maybe ()
4663 "Update checkbox statistics unless turned off by user."
4664 (when org-provide-checkbox-statistics
4665 (org-update-checkbox-count)))
4667 (defun org-update-checkbox-count (&optional all)
4668 "Update the checkbox statistics in the current section.
4669 This will find all statistic cookies like [57%] and [6/12] and update them
4670 with the current numbers. With optional prefix argument ALL, do this for
4671 the whole buffer."
4672 (interactive "P")
4673 (save-excursion
4674 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
4675 (beg (progn (outline-back-to-heading) (point)))
4676 (end (move-marker (make-marker)
4677 (progn (outline-next-heading) (point))))
4678 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
4679 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
4680 b1 e1 f1 c-on c-off lim (cstat 0))
4681 (when all
4682 (goto-char (point-min))
4683 (outline-next-heading)
4684 (setq beg (point) end (point-max)))
4685 (goto-char beg)
4686 (while (re-search-forward re end t)
4687 (setq cstat (1+ cstat)
4688 b1 (match-beginning 0)
4689 e1 (match-end 0)
4690 f1 (match-beginning 1)
4691 lim (cond
4692 ((org-on-heading-p) (outline-next-heading) (point))
4693 ((org-at-item-p) (org-end-of-item) (point))
4694 (t nil))
4695 c-on 0 c-off 0)
4696 (goto-char e1)
4697 (when lim
4698 (while (re-search-forward re-box lim t)
4699 (if (equal (match-string 2) "[ ]")
4700 (setq c-off (1+ c-off))
4701 (setq c-on (1+ c-on))))
4702 (delete-region b1 e1)
4703 (goto-char b1)
4704 (insert (if f1
4705 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
4706 (format "[%d/%d]" c-on (+ c-on c-off))))))
4707 (when (interactive-p)
4708 (message "Checkbox satistics updated %s (%d places)"
4709 (if all "in entire file" "in current outline entry") cstat)))))
4711 (defun org-get-checkbox-statistics-face ()
4712 "Select the face for checkbox statistics.
4713 The face will be `org-done' when all relevant boxes are checked. Otherwise
4714 it will be `org-todo'."
4715 (if (match-end 1)
4716 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
4717 (if (and (> (match-end 2) (match-beginning 2))
4718 (equal (match-string 2) (match-string 3)))
4719 'org-done
4720 'org-todo)))
4722 (defun org-get-indentation (&optional line)
4723 "Get the indentation of the current line, interpreting tabs.
4724 When LINE is given, assume it represents a line and compute its indentation."
4725 (if line
4726 (if (string-match "^ *" (org-remove-tabs line))
4727 (match-end 0))
4728 (save-excursion
4729 (beginning-of-line 1)
4730 (skip-chars-forward " \t")
4731 (current-column))))
4733 (defun org-remove-tabs (s &optional width)
4734 "Replace tabulators in S with spaces.
4735 Assumes that s is a single line, starting in column 0."
4736 (setq width (or width tab-width))
4737 (while (string-match "\t" s)
4738 (setq s (replace-match
4739 (make-string
4740 (- (* width (/ (+ (match-beginning 0) width) width))
4741 (match-beginning 0)) ?\ )
4742 t t s)))
4745 ;; FIXME: document properly.
4746 (defun org-fix-indentation (line ind)
4747 "If the current indenation is smaller than ind1, leave it alone.
4748 If it is larger than ind, reduce it by ind."
4749 (let* ((l (org-remove-tabs line))
4750 (i (org-get-indentation l))
4751 (i1 (car ind)) (i2 (cdr ind)))
4752 (if (>= i i2) (setq l (substring line i2)))
4753 (if (> i1 0)
4754 (concat (make-string i1 ?\ ) l)
4755 l)))
4757 (defun org-beginning-of-item ()
4758 "Go to the beginning of the current hand-formatted item.
4759 If the cursor is not in an item, throw an error."
4760 (interactive)
4761 (let ((pos (point))
4762 (limit (save-excursion (org-back-to-heading)
4763 (beginning-of-line 2) (point)))
4764 ind ind1)
4765 (if (org-at-item-p)
4766 (beginning-of-line 1)
4767 (beginning-of-line 1)
4768 (skip-chars-forward " \t")
4769 (setq ind (current-column))
4770 (if (catch 'exit
4771 (while t
4772 (beginning-of-line 0)
4773 (if (< (point) limit) (throw 'exit nil))
4774 (unless (looking-at "[ \t]*$")
4775 (skip-chars-forward " \t")
4776 (setq ind1 (current-column))
4777 (if (< ind1 ind)
4778 (throw 'exit (org-at-item-p))))))
4780 (goto-char pos)
4781 (error "Not in an item")))))
4783 (defun org-end-of-item ()
4784 "Go to the end of the current hand-formatted item.
4785 If the cursor is not in an item, throw an error."
4786 (interactive)
4787 (let ((pos (point))
4788 (limit (save-excursion (outline-next-heading) (point)))
4789 (ind (save-excursion
4790 (org-beginning-of-item)
4791 (skip-chars-forward " \t")
4792 (current-column)))
4793 ind1)
4794 (if (catch 'exit
4795 (while t
4796 (beginning-of-line 2)
4797 (if (>= (point) limit) (throw 'exit t))
4798 (unless (looking-at "[ \t]*$")
4799 (skip-chars-forward " \t")
4800 (setq ind1 (current-column))
4801 (if (<= ind1 ind) (throw 'exit t)))))
4802 (beginning-of-line 1)
4803 (goto-char pos)
4804 (error "Not in an item"))))
4806 (defun org-next-item ()
4807 "Move to the beginning of the next item in the current plain list.
4808 Error if not at a plain list, or if this is the last item in the list."
4809 (interactive)
4810 (let (ind ind1 (pos (point)))
4811 (org-beginning-of-item)
4812 (setq ind (org-get-indentation))
4813 (org-end-of-item)
4814 (setq ind1 (org-get-indentation))
4815 (unless (and (org-at-item-p) (= ind ind1))
4816 (goto-char pos)
4817 (error "On last item"))))
4819 (defun org-previous-item ()
4820 "Move to the beginning of the previous item in the current plain list.
4821 Error if not at a plain list, or if this is the last item in the list."
4822 (interactive)
4823 (let (beg ind (pos (point)))
4824 (org-beginning-of-item)
4825 (setq beg (point))
4826 (setq ind (org-get-indentation))
4827 (goto-char beg)
4828 (catch 'exit
4829 (while t
4830 (beginning-of-line 0)
4831 (if (looking-at "[ \t]*$")
4833 (if (<= (org-get-indentation) ind)
4834 (throw 'exit t)))))
4835 (condition-case nil
4836 (org-beginning-of-item)
4837 (error (goto-char pos)
4838 (error "On first item")))))
4840 (defun org-move-item-down ()
4841 "Move the plain list item at point down, i.e. swap with following item.
4842 Subitems (items with larger indentation) are considered part of the item,
4843 so this really moves item trees."
4844 (interactive)
4845 (let (beg end ind ind1 (pos (point)) txt)
4846 (org-beginning-of-item)
4847 (setq beg (point))
4848 (setq ind (org-get-indentation))
4849 (org-end-of-item)
4850 (setq end (point))
4851 (setq ind1 (org-get-indentation))
4852 (if (and (org-at-item-p) (= ind ind1))
4853 (progn
4854 (org-end-of-item)
4855 (setq txt (buffer-substring beg end))
4856 (save-excursion
4857 (delete-region beg end))
4858 (setq pos (point))
4859 (insert txt)
4860 (goto-char pos)
4861 (org-maybe-renumber-ordered-list))
4862 (goto-char pos)
4863 (error "Cannot move this item further down"))))
4865 (defun org-move-item-up (arg)
4866 "Move the plain list item at point up, i.e. swap with previous item.
4867 Subitems (items with larger indentation) are considered part of the item,
4868 so this really moves item trees."
4869 (interactive "p")
4870 (let (beg end ind ind1 (pos (point)) txt)
4871 (org-beginning-of-item)
4872 (setq beg (point))
4873 (setq ind (org-get-indentation))
4874 (org-end-of-item)
4875 (setq end (point))
4876 (goto-char beg)
4877 (catch 'exit
4878 (while t
4879 (beginning-of-line 0)
4880 (if (looking-at "[ \t]*$")
4882 (if (<= (setq ind1 (org-get-indentation)) ind)
4883 (throw 'exit t)))))
4884 (condition-case nil
4885 (org-beginning-of-item)
4886 (error (goto-char beg)
4887 (error "Cannot move this item further up")))
4888 (setq ind1 (org-get-indentation))
4889 (if (and (org-at-item-p) (= ind ind1))
4890 (progn
4891 (setq txt (buffer-substring beg end))
4892 (save-excursion
4893 (delete-region beg end))
4894 (setq pos (point))
4895 (insert txt)
4896 (goto-char pos)
4897 (org-maybe-renumber-ordered-list))
4898 (goto-char pos)
4899 (error "Cannot move this item further up"))))
4901 (defun org-maybe-renumber-ordered-list ()
4902 "Renumber the ordered list at point if setup allows it.
4903 This tests the user option `org-auto-renumber-ordered-lists' before
4904 doing the renumbering."
4905 (and org-auto-renumber-ordered-lists
4906 (org-at-item-p)
4907 (match-beginning 3)
4908 (org-renumber-ordered-list 1)))
4910 (defun org-get-string-indentation (s)
4911 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4912 (let ((n -1) (i 0) (w tab-width) c)
4913 (catch 'exit
4914 (while (< (setq n (1+ n)) (length s))
4915 (setq c (aref s n))
4916 (cond ((= c ?\ ) (setq i (1+ i)))
4917 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4918 (t (throw 'exit t)))))
4921 (defun org-renumber-ordered-list (arg)
4922 "Renumber an ordered plain list.
4923 Cursor needs to be in the first line of an item, the line that starts
4924 with something like \"1.\" or \"2)\"."
4925 (interactive "p")
4926 (unless (and (org-at-item-p)
4927 (match-beginning 3))
4928 (error "This is not an ordered list"))
4929 (let ((line (org-current-line))
4930 (col (current-column))
4931 (ind (org-get-string-indentation
4932 (buffer-substring (point-at-bol) (match-beginning 3))))
4933 ;; (term (substring (match-string 3) -1))
4934 ind1 (n (1- arg)))
4935 ;; find where this list begins
4936 (catch 'exit
4937 (while t
4938 (catch 'next
4939 (beginning-of-line 0)
4940 (if (looking-at "[ \t]*$") (throw 'next t))
4941 (skip-chars-forward " \t") (setq ind1 (current-column))
4942 (if (or (< ind1 ind)
4943 (and (= ind1 ind)
4944 (not (org-at-item-p))))
4945 (throw 'exit t)))))
4946 ;; Walk forward and replace these numbers
4947 (catch 'exit
4948 (while t
4949 (catch 'next
4950 (beginning-of-line 2)
4951 (if (eobp) (throw 'exit nil))
4952 (if (looking-at "[ \t]*$") (throw 'next nil))
4953 (skip-chars-forward " \t") (setq ind1 (current-column))
4954 (if (> ind1 ind) (throw 'next t))
4955 (if (< ind1 ind) (throw 'exit t))
4956 (if (not (org-at-item-p)) (throw 'exit nil))
4957 (if (not (match-beginning 3))
4958 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4959 (delete-region (match-beginning 3) (1- (match-end 3)))
4960 (goto-char (match-beginning 3))
4961 (insert (format "%d" (setq n (1+ n)))))))
4962 (goto-line line)
4963 (move-to-column col)))
4965 (defvar org-last-indent-begin-marker (make-marker))
4966 (defvar org-last-indent-end-marker (make-marker))
4968 (defun org-outdent-item (arg)
4969 "Outdent a local list item."
4970 (interactive "p")
4971 (org-indent-item (- arg)))
4973 (defun org-indent-item (arg)
4974 "Indent a local list item."
4975 (interactive "p")
4976 (unless (org-at-item-p)
4977 (error "Not on an item"))
4978 (save-excursion
4979 (let (beg end ind ind1)
4980 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4981 (setq beg org-last-indent-begin-marker
4982 end org-last-indent-end-marker)
4983 (org-beginning-of-item)
4984 (setq beg (move-marker org-last-indent-begin-marker (point)))
4985 (org-end-of-item)
4986 (setq end (move-marker org-last-indent-end-marker (point))))
4987 (goto-char beg)
4988 (skip-chars-forward " \t") (setq ind (current-column))
4989 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4990 (while (< (point) end)
4991 (beginning-of-line 1)
4992 (skip-chars-forward " \t") (setq ind1 (current-column))
4993 (delete-region (point-at-bol) (point))
4994 (indent-to-column (+ ind1 arg))
4995 (beginning-of-line 2)))))
4997 ;;; Archiving
4999 (defun org-archive-subtree (&optional find-done)
5000 "Move the current subtree to the archive.
5001 The archive can be a certain top-level heading in the current file, or in
5002 a different file. The tree will be moved to that location, the subtree
5003 heading be marked DONE, and the current time will be added.
5005 When called with prefix argument FIND-DONE, find whole trees without any
5006 open TODO items and archive them (after getting confirmation from the user).
5007 If the cursor is not at a headline when this comand is called, try all level
5008 1 trees. If the cursor is on a headline, only try the direct children of
5009 this heading. "
5010 (interactive "P")
5011 (if find-done
5012 (org-archive-all-done)
5013 ;; Save all relevant TODO keyword-relatex variables
5015 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5016 (tr-org-todo-keywords org-todo-keywords)
5017 (tr-org-todo-interpretation org-todo-interpretation)
5018 (tr-org-done-string org-done-string)
5019 (tr-org-todo-regexp org-todo-regexp)
5020 (tr-org-todo-line-regexp org-todo-line-regexp)
5021 (this-buffer (current-buffer))
5022 file heading buffer level newfile-p)
5023 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5024 (progn
5025 (setq file (format (match-string 1 org-archive-location)
5026 (file-name-nondirectory buffer-file-name))
5027 heading (match-string 2 org-archive-location)))
5028 (error "Invalid `org-archive-location'"))
5029 (if (> (length file) 0)
5030 (setq newfile-p (not (file-exists-p file))
5031 buffer (find-file-noselect file))
5032 (setq buffer (current-buffer)))
5033 (unless buffer
5034 (error "Cannot access file \"%s\"" file))
5035 (if (and (> (length heading) 0)
5036 (string-match "^\\*+" heading))
5037 (setq level (match-end 0))
5038 (setq heading nil level 0))
5039 (save-excursion
5040 ;; We first only copy, in case something goes wrong
5041 ;; we need to protect this-command, to avoid kill-region sets it,
5042 ;; which would lead to duplication of subtrees
5043 (let (this-command) (org-copy-subtree))
5044 (set-buffer buffer)
5045 ;; Enforce org-mode for the archive buffer
5046 (if (not (org-mode-p))
5047 ;; Force the mode for future visits.
5048 (let ((org-insert-mode-line-in-empty-file t))
5049 (call-interactively 'org-mode)))
5050 (when newfile-p
5051 (goto-char (point-max))
5052 (insert (format "\nArchived entries from file %s\n\n"
5053 (buffer-file-name this-buffer))))
5054 ;; Force the TODO keywords of the original buffer
5055 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5056 (org-todo-keywords tr-org-todo-keywords)
5057 (org-todo-interpretation tr-org-todo-interpretation)
5058 (org-done-string tr-org-done-string)
5059 (org-todo-regexp tr-org-todo-regexp)
5060 (org-todo-line-regexp tr-org-todo-line-regexp))
5061 (goto-char (point-min))
5062 (if heading
5063 (progn
5064 (if (re-search-forward
5065 (concat "\\(^\\|\r\\)"
5066 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
5067 nil t)
5068 (goto-char (match-end 0))
5069 ;; Heading not found, just insert it at the end
5070 (goto-char (point-max))
5071 (or (bolp) (insert "\n"))
5072 (insert "\n" heading "\n")
5073 (end-of-line 0))
5074 ;; Make the subtree visible
5075 (show-subtree)
5076 (org-end-of-subtree t)
5077 (skip-chars-backward " \t\r\n")
5078 (and (looking-at "[ \t\r\n]*")
5079 (replace-match "\n\n")))
5080 ;; No specific heading, just go to end of file.
5081 (goto-char (point-max)) (insert "\n"))
5082 ;; Paste
5083 (org-paste-subtree (1+ level))
5084 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5085 (if org-archive-mark-done
5086 (let (org-log-done)
5087 (org-todo (length org-todo-keywords))))
5088 ;; Move cursor to right after the TODO keyword
5089 (when org-archive-stamp-time
5090 (beginning-of-line 1)
5091 (looking-at org-todo-line-regexp)
5092 (goto-char (or (match-end 2) (match-beginning 3)))
5093 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5094 ;; Save the buffer, if it is not the same buffer.
5095 (if (not (eq this-buffer buffer)) (save-buffer))))
5096 ;; Here we are back in the original buffer. Everything seems to have
5097 ;; worked. So now cut the tree and finish up.
5098 (let (this-command) (org-cut-subtree))
5099 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5100 (message "Subtree archived %s"
5101 (if (eq this-buffer buffer)
5102 (concat "under heading: " heading)
5103 (concat "in file: " (abbreviate-file-name file)))))))
5105 (defun org-archive-all-done (&optional tag)
5106 "Archive sublevels of the current tree without open TODO items.
5107 If the cursor is not on a headline, try all level 1 trees. If
5108 it is on a headline, try all direct children.
5109 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5110 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5111 (rea (concat ".*:" org-archive-tag ":"))
5112 (begm (make-marker))
5113 (endm (make-marker))
5114 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5115 "Move subtree to archive (no open TODO items)? "))
5116 beg end (cntarch 0))
5117 (if (org-on-heading-p)
5118 (progn
5119 (setq re1 (concat "^" (regexp-quote
5120 (make-string
5121 (1+ (- (match-end 0) (match-beginning 0)))
5122 ?*))
5123 " "))
5124 (move-marker begm (point))
5125 (move-marker endm (org-end-of-subtree t)))
5126 (setq re1 "^* ")
5127 (move-marker begm (point-min))
5128 (move-marker endm (point-max)))
5129 (save-excursion
5130 (goto-char begm)
5131 (while (re-search-forward re1 endm t)
5132 (setq beg (match-beginning 0)
5133 end (save-excursion (org-end-of-subtree t) (point)))
5134 (goto-char beg)
5135 (if (re-search-forward re end t)
5136 (goto-char end)
5137 (goto-char beg)
5138 (if (and (or (not tag) (not (looking-at rea)))
5139 (y-or-n-p question))
5140 (progn
5141 (if tag
5142 (org-toggle-tag org-archive-tag 'on)
5143 (org-archive-subtree))
5144 (setq cntarch (1+ cntarch)))
5145 (goto-char end)))))
5146 (message "%d trees archived" cntarch)))
5148 (defun org-cycle-hide-archived-subtrees (state)
5149 "Re-hide all archived subtrees after a visibility state change."
5150 (when (and (not org-cycle-open-archived-trees)
5151 (not (memq state '(overview folded))))
5152 (save-excursion
5153 (let* ((globalp (memq state '(contents all)))
5154 (beg (if globalp (point-min) (point)))
5155 (end (if globalp (point-max) (org-end-of-subtree t))))
5156 (org-hide-archived-subtrees beg end)
5157 (goto-char beg)
5158 (if (looking-at (concat ".*:" org-archive-tag ":"))
5159 (message (substitute-command-keys
5160 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5162 (defun org-force-cycle-archived ()
5163 "Cycle subtree even if it is archived."
5164 (interactive)
5165 (setq this-command 'org-cycle)
5166 (let ((org-cycle-open-archived-trees t))
5167 (call-interactively 'org-cycle)))
5169 (defun org-hide-archived-subtrees (beg end)
5170 "Re-hide all archived subtrees after a visibility state change."
5171 (save-excursion
5172 (let* ((re (concat ":" org-archive-tag ":")))
5173 (goto-char beg)
5174 (while (re-search-forward re end t)
5175 (and (org-on-heading-p) (hide-subtree))
5176 (org-end-of-subtree t)))))
5178 (defun org-toggle-tag (tag &optional onoff)
5179 "Toggle the tag TAG for the current line.
5180 If ONOFF is `on' or `off', don't toggle but set to this state."
5181 (unless (org-on-heading-p) (error "Not on headling"))
5182 (let (res current)
5183 (save-excursion
5184 (beginning-of-line)
5185 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5186 (point-at-eol) t)
5187 (progn
5188 (setq current (match-string 1))
5189 (replace-match ""))
5190 (setq current ""))
5191 (setq current (nreverse (org-split-string current ":")))
5192 (cond
5193 ((eq onoff 'on)
5194 (setq res t)
5195 (or (member tag current) (push tag current)))
5196 ((eq onoff 'off)
5197 (or (not (member tag current)) (setq current (delete tag current))))
5198 (t (if (member tag current)
5199 (setq current (delete tag current))
5200 (setq res t)
5201 (push tag current))))
5202 (end-of-line 1)
5203 (when current
5204 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5205 (org-set-tags nil t))
5206 res))
5208 (defun org-toggle-archive-tag (&optional arg)
5209 "Toggle the archive tag for the current headline.
5210 With prefix ARG, check all children of current headline and offer tagging
5211 the children that do not contain any open TODO items."
5212 (interactive "P")
5213 (if arg
5214 (org-archive-all-done 'tag)
5215 (let (set)
5216 (save-excursion
5217 (org-back-to-heading t)
5218 (setq set (org-toggle-tag org-archive-tag))
5219 (when set (hide-subtree)))
5220 (and set (beginning-of-line 1))
5221 (message "Subtree %s" (if set "archived" "unarchived")))))
5223 (defvar org-agenda-multi nil) ; dynammically scoped
5224 (defvar org-agenda-buffer-name "*Org Agenda*")
5225 (defvar org-pre-agenda-window-conf nil)
5226 (defun org-prepare-agenda ()
5227 (if org-agenda-multi
5228 (progn
5229 (setq buffer-read-only nil)
5230 (goto-char (point-max))
5231 (unless (= (point) 1)
5232 (insert "\n" (make-string (window-width) ?=) "\n"))
5233 (narrow-to-region (point) (point-max)))
5234 (org-agenda-maybe-reset-markers 'force)
5235 (org-prepare-agenda-buffers (org-agenda-files))
5236 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
5237 (awin (get-buffer-window abuf)))
5238 (cond
5239 ((equal (current-buffer) abuf) nil)
5240 (awin (select-window awin))
5241 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
5242 ((equal org-agenda-window-setup 'current-window)
5243 (switch-to-buffer abuf))
5244 ((equal org-agenda-window-setup 'other-window)
5245 (switch-to-buffer-other-window abuf))
5246 ((equal org-agenda-window-setup 'other-frame)
5247 (switch-to-buffer-other-frame abuf))
5248 ((equal org-agenda-window-setup 'reorganize-frame)
5249 (delete-other-windows)
5250 (switch-to-buffer-other-window abuf))))
5251 (setq buffer-read-only nil)
5252 (erase-buffer)
5253 (org-agenda-mode))
5254 (setq buffer-read-only nil))
5256 (defun org-finalize-agenda ()
5257 "Finishing touch for the agenda buffer, called just before displaying it."
5258 (unless org-agenda-multi
5259 (org-agenda-align-tags)
5260 (save-excursion
5261 (let ((buffer-read-only))
5262 (goto-char (point-min))
5263 (while (org-activate-bracket-links (point-max))
5264 (add-text-properties (match-beginning 0) (match-end 0)
5265 '(face org-link))))
5266 (run-hooks 'org-finalize-agenda-hook))))
5268 (defun org-prepare-agenda-buffers (files)
5269 "Create buffers for all agenda files, protect archived trees and comments."
5270 (interactive)
5271 (let ((pa '(:org-archived t))
5272 (pc '(:org-comment t))
5273 (pall '(:org-archived t :org-comment t))
5274 (rea (concat ":" org-archive-tag ":"))
5275 bmp file re)
5276 (save-excursion
5277 (while (setq file (pop files))
5278 (org-check-agenda-file file)
5279 (set-buffer (org-get-agenda-file-buffer file))
5280 (widen)
5281 (setq bmp (buffer-modified-p))
5282 (save-excursion
5283 (remove-text-properties (point-min) (point-max) pall)
5284 (when org-agenda-skip-archived-trees
5285 (goto-char (point-min))
5286 (while (re-search-forward rea nil t)
5287 (if (org-on-heading-p)
5288 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
5289 (goto-char (point-min))
5290 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
5291 (while (re-search-forward re nil t)
5292 (add-text-properties
5293 (match-beginning 0) (org-end-of-subtree t) pc)))
5294 (set-buffer-modified-p bmp)))))
5296 (defun org-agenda-skip ()
5297 "Throw to `:skip' in places that should be skipped."
5298 (let ((p (point-at-bol)))
5299 (and org-agenda-skip-archived-trees
5300 (get-text-property p :org-archived)
5301 (org-end-of-subtree t)
5302 (throw :skip t))
5303 (and (get-text-property p :org-comment)
5304 (org-end-of-subtree t)
5305 (throw :skip t))
5306 (if (equal (char-after p) ?#) (throw :skip t))))
5308 (defun org-agenda-toggle-archive-tag ()
5309 "Toggle the archive tag for the current entry."
5310 (interactive)
5311 (org-agenda-check-no-diary)
5312 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
5313 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
5314 (org-agenda-error)))
5315 (buffer (marker-buffer hdmarker))
5316 (pos (marker-position hdmarker))
5317 (buffer-read-only nil)
5318 newhead)
5319 (with-current-buffer buffer
5320 (widen)
5321 (goto-char pos)
5322 (org-show-context 'agenda)
5323 (save-excursion
5324 (and (outline-next-heading)
5325 (org-flag-heading nil))) ; show the next heading
5326 (call-interactively 'org-toggle-archive-tag)
5327 (end-of-line 1)
5328 (setq newhead (org-get-heading)))
5329 (org-agenda-change-all-lines newhead hdmarker)
5330 (beginning-of-line 1)))
5332 ;;; Dynamic blocks
5334 (defun org-find-dblock (name)
5335 "Find the first dynamic block with name NAME in the buffer.
5336 If not found, stay at current position and return nil."
5337 (let (pos)
5338 (save-excursion
5339 (goto-char (point-min))
5340 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
5341 nil t)
5342 (match-beginning 0))))
5343 (if pos (goto-char pos))
5344 pos))
5346 (defconst org-dblock-start-re
5347 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
5348 "Matches the startline of a dynamic block, with parameters.")
5350 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
5351 "Matches the end of a dyhamic block.")
5353 (defun org-create-dblock (plist)
5354 "Create a dynamic block section, with parameters taken from PLIST.
5355 PLIST must containe a :name entry which is used as name of the block."
5356 (unless (bolp) (newline))
5357 (let ((name (plist-get plist :name)))
5358 (insert "#+BEGIN: " name)
5359 (while plist
5360 (if (eq (car plist) :name)
5361 (setq plist (cddr plist))
5362 (insert " " (prin1-to-string (pop plist)))))
5363 (insert "\n\n#+END:\n")
5364 (beginning-of-line -2)))
5366 (defun org-prepare-dblock ()
5367 "Prepare dynamic block for refresh.
5368 This empties the block, puts the cursor at the insert position and returns
5369 the property list including an extra property :name with the block name."
5370 (unless (looking-at org-dblock-start-re)
5371 (error "Not at a dynamic block"))
5372 (let* ((begdel (1+ (match-end 0)))
5373 (name (match-string 1))
5374 (params (append (list :name name)
5375 (read (concat "(" (match-string 3) ")")))))
5376 (unless (re-search-forward org-dblock-end-re nil t)
5377 (error "Dynamic block not terminated"))
5378 (delete-region begdel (match-beginning 0))
5379 (goto-char begdel)
5380 (open-line 1)
5381 params))
5383 (defun org-map-dblocks (&optional command)
5384 "Apply COMMAND to all dynamic blocks in the current buffer.
5385 If COMMAND is not given, use `org-update-dblock'."
5386 (let ((cmd (or command 'org-update-dblock))
5387 pos)
5388 (save-excursion
5389 (goto-char (point-min))
5390 (while (re-search-forward org-dblock-start-re nil t)
5391 (goto-char (setq pos (match-beginning 0)))
5392 (condition-case nil
5393 (funcall cmd)
5394 (error (message "Error during update of dynamic block")))
5395 (goto-char pos)
5396 (unless (re-search-forward org-dblock-end-re nil t)
5397 (error "Dynamic block not terminated"))))))
5399 (defun org-dblock-update (&optional arg)
5400 "User command for updating dynamic blocks.
5401 Update the dynamic block at point. With prefix ARG, update all dynamic
5402 blocks in the buffer."
5403 (interactive "P")
5404 (if arg
5405 (org-update-all-dblocks)
5406 (or (looking-at org-dblock-start-re)
5407 (org-beginning-of-dblock))
5408 (org-update-dblock)))
5410 (defun org-update-dblock ()
5411 "Update the dynamic block at point
5412 This means to empty the block, parse for parameters and then call
5413 the correct writing function."
5414 (let* ((pos (point))
5415 (params (org-prepare-dblock))
5416 (name (plist-get params :name))
5417 (cmd (intern (concat "org-dblock-write:" name))))
5418 (funcall cmd params)
5419 (goto-char pos)))
5421 (defun org-beginning-of-dblock ()
5422 "Find the beginning of the dynamic block at point.
5423 Error if there is no scuh block at point."
5424 (let ((pos (point))
5425 beg)
5426 (end-of-line 1)
5427 (if (and (re-search-backward org-dblock-start-re nil t)
5428 (setq beg (match-beginning 0))
5429 (re-search-forward org-dblock-end-re nil t)
5430 (> (match-end 0) pos))
5431 (goto-char beg)
5432 (goto-char pos)
5433 (error "Not in a dynamic block"))))
5435 (defun org-update-all-dblocks ()
5436 "Update all dynamic blocks in the buffer.
5437 This function can be used in a hook."
5438 (when (org-mode-p)
5439 (org-map-dblocks 'org-update-dblock)))
5442 ;;; Completion
5444 (defun org-complete (&optional arg)
5445 "Perform completion on word at point.
5446 At the beginning of a headline, this completes TODO keywords as given in
5447 `org-todo-keywords'.
5448 If the current word is preceded by a backslash, completes the TeX symbols
5449 that are supported for HTML support.
5450 If the current word is preceded by \"#+\", completes special words for
5451 setting file options.
5452 In the line after \"#+STARTUP:, complete valid keywords.\"
5453 At all other locations, this simply calls `ispell-complete-word'."
5454 (interactive "P")
5455 (catch 'exit
5456 (let* ((end (point))
5457 (beg1 (save-excursion
5458 (skip-chars-backward "a-zA-Z_@0-9")
5459 (point)))
5460 (beg (save-excursion
5461 (skip-chars-backward "a-zA-Z0-9_:$")
5462 (point)))
5463 (confirm (lambda (x) (stringp (car x))))
5464 (camel (equal (char-before beg) ?*))
5465 (tag (equal (char-before beg1) ?:))
5466 (texp (equal (char-before beg) ?\\))
5467 (link (equal (char-before beg) ?\[))
5468 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
5469 beg)
5470 "#+"))
5471 (startup (string-match "^#\\+STARTUP:.*"
5472 (buffer-substring (point-at-bol) (point))))
5473 (completion-ignore-case opt)
5474 (type nil)
5475 (tbl nil)
5476 (table (cond
5477 (opt
5478 (setq type :opt)
5479 (mapcar (lambda (x)
5480 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
5481 (cons (match-string 2 x) (match-string 1 x)))
5482 (org-split-string (org-get-current-options) "\n")))
5483 (startup
5484 (setq type :startup)
5485 org-startup-options)
5486 (link (append org-link-abbrev-alist-local
5487 org-link-abbrev-alist))
5488 (texp
5489 (setq type :tex)
5490 org-html-entities)
5491 ((string-match "\\`\\*+[ \t]*\\'"
5492 (buffer-substring (point-at-bol) beg))
5493 (setq type :todo)
5494 (mapcar 'list org-todo-keywords))
5495 (camel
5496 (setq type :camel)
5497 (save-excursion
5498 (goto-char (point-min))
5499 (while (re-search-forward org-todo-line-regexp nil t)
5500 (push (list
5501 (if org-file-link-context-use-camel-case
5502 (org-make-org-heading-camel (match-string 3) t)
5503 (org-make-org-heading-search-string
5504 (match-string 3) t)))
5505 tbl)))
5506 tbl)
5507 (tag (setq type :tag beg beg1)
5508 (or org-tag-alist (org-get-buffer-tags)))
5509 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
5510 (pattern (buffer-substring-no-properties beg end))
5511 (completion (try-completion pattern table confirm)))
5512 (cond ((eq completion t)
5513 (if (equal type :opt)
5514 (insert (substring (cdr (assoc (upcase pattern) table))
5515 (length pattern)))
5516 (if (equal type :tag) (insert ":"))))
5517 ((null completion)
5518 (message "Can't find completion for \"%s\"" pattern)
5519 (ding))
5520 ((not (string= pattern completion))
5521 (delete-region beg end)
5522 (if (string-match " +$" completion)
5523 (setq completion (replace-match "" t t completion)))
5524 (insert completion)
5525 (if (get-buffer-window "*Completions*")
5526 (delete-window (get-buffer-window "*Completions*")))
5527 (if (assoc completion table)
5528 (if (eq type :todo) (insert " ")
5529 (if (eq type :tag) (insert ":"))))
5530 (if (and (equal type :opt) (assoc completion table))
5531 (message "%s" (substitute-command-keys
5532 "Press \\[org-complete] again to insert example settings"))))
5534 (message "Making completion list...")
5535 (let ((list (sort (all-completions pattern table confirm)
5536 'string<)))
5537 (with-output-to-temp-buffer "*Completions*"
5538 (condition-case nil
5539 ;; Protection needed for XEmacs and emacs 21
5540 (display-completion-list list pattern)
5541 (error (display-completion-list list)))))
5542 (message "Making completion list...%s" "done"))))))
5544 ;;; Comments, TODO and DEADLINE
5546 (defun org-toggle-comment ()
5547 "Change the COMMENT state of an entry."
5548 (interactive)
5549 (save-excursion
5550 (org-back-to-heading)
5551 (if (looking-at (concat outline-regexp
5552 "\\( +\\<" org-comment-string "\\>\\)"))
5553 (replace-match "" t t nil 1)
5554 (if (looking-at outline-regexp)
5555 (progn
5556 (goto-char (match-end 0))
5557 (insert " " org-comment-string))))))
5559 (defvar org-last-todo-state-is-todo nil
5560 "This is non-nil when the last TODO state change led to a TODO state.
5561 If the last change removed the TODO tag or switched to DONE, then
5562 this is nil.")
5564 (defun org-todo (&optional arg)
5565 "Change the TODO state of an item.
5566 The state of an item is given by a keyword at the start of the heading,
5567 like
5568 *** TODO Write paper
5569 *** DONE Call mom
5571 The different keywords are specified in the variable `org-todo-keywords'.
5572 By default the available states are \"TODO\" and \"DONE\".
5573 So for this example: when the item starts with TODO, it is changed to DONE.
5574 When it starts with DONE, the DONE is removed. And when neither TODO nor
5575 DONE are present, add TODO at the beginning of the heading.
5577 With prefix arg, use completion to determine the new state. With numeric
5578 prefix arg, switch to that state."
5579 (interactive "P")
5580 (save-excursion
5581 (org-back-to-heading)
5582 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5583 (or (looking-at (concat " +" org-todo-regexp " *"))
5584 (looking-at " *"))
5585 (let* ((this (match-string 1))
5586 (completion-ignore-case t)
5587 (member (member this org-todo-keywords))
5588 (tail (cdr member))
5589 (state (cond
5590 ((equal arg '(4))
5591 ;; Read a state with completion
5592 (completing-read "State: " (mapcar (lambda(x) (list x))
5593 org-todo-keywords)
5594 nil t))
5595 ((eq arg 'right)
5596 (if this
5597 (if tail (car tail) nil)
5598 (car org-todo-keywords)))
5599 ((eq arg 'left)
5600 (if (equal member org-todo-keywords)
5602 (if this
5603 (nth (- (length org-todo-keywords) (length tail) 2)
5604 org-todo-keywords)
5605 org-done-string)))
5606 (arg
5607 ;; user requests a specific state
5608 (nth (1- (prefix-numeric-value arg))
5609 org-todo-keywords))
5610 ((null member) (car org-todo-keywords))
5611 ((null tail) nil) ;; -> first entry
5612 ((eq org-todo-interpretation 'sequence)
5613 (car tail))
5614 ((memq org-todo-interpretation '(type priority))
5615 (if (eq this-command last-command)
5616 (car tail)
5617 (if (> (length tail) 0) org-done-string nil)))
5618 (t nil)))
5619 (next (if state (concat " " state " ") " ")))
5620 (replace-match next t t)
5621 (setq org-last-todo-state-is-todo
5622 (not (equal state org-done-string)))
5623 (when org-log-done
5624 (if (equal state org-done-string)
5625 (org-add-planning-info 'closed (org-current-time) 'scheduled)
5626 (if (not this)
5627 (org-add-planning-info nil nil 'closed))))
5628 ;; Fixup tag positioning
5629 (and org-auto-align-tags (org-set-tags nil t))
5630 (run-hooks 'org-after-todo-state-change-hook)))
5631 ;; Fixup cursor location if close to the keyword
5632 (if (and (outline-on-heading-p)
5633 (not (bolp))
5634 (save-excursion (beginning-of-line 1)
5635 (looking-at org-todo-line-regexp))
5636 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5637 (progn
5638 (goto-char (or (match-end 2) (match-end 1)))
5639 (just-one-space))))
5641 (defun org-show-todo-tree (arg)
5642 "Make a compact tree which shows all headlines marked with TODO.
5643 The tree will show the lines where the regexp matches, and all higher
5644 headlines above the match.
5645 With \\[universal-argument] prefix, also show the DONE entries.
5646 With a numeric prefix N, construct a sparse tree for the Nth element
5647 of `org-todo-keywords'."
5648 (interactive "P")
5649 (let ((case-fold-search nil)
5650 (kwd-re
5651 (cond ((null arg) org-not-done-regexp)
5652 ((equal arg '(4)) org-todo-regexp)
5653 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5654 (regexp-quote (nth (1- (prefix-numeric-value arg))
5655 org-todo-keywords)))
5656 (t (error "Invalid prefix argument: %s" arg)))))
5657 (message "%d TODO entries found"
5658 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5660 (defun org-deadline ()
5661 "Insert the DEADLINE: string to make a deadline.
5662 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5663 to modify it to the correct date."
5664 (interactive)
5665 (org-add-planning-info 'deadline nil 'closed))
5667 (defun org-schedule ()
5668 "Insert the SCHEDULED: string to schedule a TODO item.
5669 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5670 to modify it to the correct date."
5671 (interactive)
5672 (org-add-planning-info 'scheduled nil 'closed))
5674 (defun org-add-planning-info (what &optional time &rest remove)
5675 "Insert new timestamp with keyword in the line directly after the headline.
5676 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5677 If non is given, the user is prompted for a date.
5678 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5679 be removed."
5680 (interactive)
5681 (when what (setq time (or time (org-read-date nil 'to-time))))
5682 (when (and org-insert-labeled-timestamps-at-point
5683 (member what '(scheduled deadline)))
5684 (insert
5685 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
5686 (org-insert-time-stamp time)
5687 (setq what nil))
5688 (save-excursion
5689 (save-restriction
5690 (let (col list elt ts buffer-invisibility-spec)
5691 (org-back-to-heading t)
5692 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5693 (goto-char (match-end 1))
5694 (setq col (current-column))
5695 (goto-char (1+ (match-end 0)))
5696 (if (and (not (looking-at outline-regexp))
5697 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5698 "[^\r\n]*"))
5699 (not (equal (match-string 1) org-clock-string)))
5700 (narrow-to-region (match-beginning 0) (match-end 0))
5701 (insert "\n")
5702 (backward-char 1)
5703 (narrow-to-region (point) (point))
5704 (indent-to-column col))
5705 ;; Check if we have to remove something.
5706 (setq list (cons what remove))
5707 (while list
5708 (setq elt (pop list))
5709 (goto-char (point-min))
5710 (when (or (and (eq elt 'scheduled)
5711 (re-search-forward org-scheduled-time-regexp nil t))
5712 (and (eq elt 'deadline)
5713 (re-search-forward org-deadline-time-regexp nil t))
5714 (and (eq elt 'closed)
5715 (re-search-forward org-closed-time-regexp nil t)))
5716 (replace-match "")
5717 (if (looking-at "--+<[^>]+>") (replace-match ""))
5718 (if (looking-at " +") (replace-match ""))))
5719 (goto-char (point-max))
5720 (when what
5721 (insert
5722 (if (not (equal (char-before) ?\ )) " " "")
5723 (cond ((eq what 'scheduled) org-scheduled-string)
5724 ((eq what 'deadline) org-deadline-string)
5725 ((eq what 'closed) org-closed-string))
5726 " ")
5727 (org-insert-time-stamp time nil (eq what 'closed))
5728 (end-of-line 1)
5729 (and (eq what 'closed) (org-add-log-maybe 'done)))
5730 (goto-char (point-min))
5731 (widen)
5732 (if (looking-at "[ \t]+\r?\n")
5733 (replace-match ""))
5734 ts))))
5736 (defvar org-log-note-marker (make-marker))
5737 (defvar org-log-note-purpose nil)
5738 (defvar org-log-note-window-configuration nil)
5740 (defun org-add-log-maybe (&optional purpose)
5741 (when (and (listp org-log-done)
5742 (memq purpose org-log-done))
5743 (move-marker org-log-note-marker (point))
5744 (setq org-log-note-purpose purpose)
5745 (add-hook 'post-command-hook 'org-add-log-note 'append)))
5747 (defun org-add-log-note (&optional purpose)
5748 "Pop up a window for taking a note, and add this note later at point."
5749 (remove-hook 'post-command-hook 'org-add-log-note)
5750 (setq org-log-note-window-configuration (current-window-configuration))
5751 (delete-other-windows)
5752 (switch-to-buffer (marker-buffer org-log-note-marker))
5753 (goto-char org-log-note-marker)
5754 (switch-to-buffer-other-window "*Org Note*")
5755 (erase-buffer)
5756 (org-mode)
5757 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
5758 (cond
5759 ((eq org-log-note-purpose 'clock-out) "stopped clock")
5760 ((eq org-log-note-purpose 'done) "closed todo item")
5761 (t (error "This should not happen")))))
5762 (org-set-local 'org-finish-function 'org-store-log-note))
5764 (defun org-store-log-note ()
5765 "Finish taking a log note, and insert it to where it belongs."
5766 (let ((txt (buffer-string))
5767 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
5768 lines ind)
5769 (kill-buffer (current-buffer))
5770 (if (string-match "^#.*\n[ \t\\n]*" txt)
5771 (setq txt (replace-match "" t t txt)))
5772 (when (string-match "\\S-" txt)
5773 (if (string-match "\\s-+\\'" txt)
5774 (setq txt (replace-match "" t t txt)))
5775 (setq lines (org-split-string txt "\n"))
5776 (when (and note (string-match "\\S-" note))
5777 (setq note
5778 (org-replace-escapes
5779 note
5780 (list (cons "%u" user-login-name)
5781 (cons "%U" user-full-name)
5782 (cons "%t" (format-time-string
5783 (org-time-stamp-format 'long 'inactive)
5784 (current-time))))))
5785 (push note lines))
5786 (save-excursion
5787 (set-buffer (marker-buffer org-log-note-marker))
5788 (save-excursion
5789 (goto-char org-log-note-marker)
5790 (if (not (bolp)) (newline))
5791 (indent-relative t)
5792 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
5793 (insert " - " (pop lines))
5794 (while lines
5795 (insert "\n" ind (pop lines))))))
5796 (set-window-configuration org-log-note-window-configuration)))
5798 (defvar org-occur-highlights nil)
5799 (make-variable-buffer-local 'org-occur-highlights)
5801 (defun org-occur (regexp &optional keep-previous callback)
5802 "Make a compact tree which shows all matches of REGEXP.
5803 The tree will show the lines where the regexp matches, and all higher
5804 headlines above the match. It will also show the heading after the match,
5805 to make sure editing the matching entry is easy.
5806 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
5807 call to `org-occur' will be kept, to allow stacking of calls to this
5808 command.
5809 If CALLBACK is non-nil, it is a function which is called to confirm
5810 that the match should indeed be shown."
5811 (interactive "sRegexp: \nP")
5812 (or keep-previous (org-remove-occur-highlights nil nil t))
5813 (let ((cnt 0))
5814 (save-excursion
5815 (goto-char (point-min))
5816 (if (or (not keep-previous) ; do not want to keep
5817 (not org-occur-highlights)) ; no previous matches
5818 ;; hide everything
5819 (org-overview))
5820 (while (re-search-forward regexp nil t)
5821 (when (or (not callback)
5822 (save-match-data (funcall callback)))
5823 (setq cnt (1+ cnt))
5824 (org-highlight-new-match (match-beginning 0) (match-end 0))
5825 (org-show-context 'occur-tree))))
5826 (when org-remove-highlights-with-change
5827 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5828 nil 'local))
5829 (unless org-sparse-tree-open-archived-trees
5830 (org-hide-archived-subtrees (point-min) (point-max)))
5831 (run-hooks 'org-occur-hook)
5832 (if (interactive-p)
5833 (message "%d match(es) for regexp %s" cnt regexp))
5834 cnt))
5836 (defun org-show-context (&optional key siblings)
5837 "Make sure point and context and visible.
5838 How much context is shown depends upon the variables
5839 `org-show-hierarchy-above' and `org-show-following-heading'.
5840 When SIBLINGS is non-nil, show all siblings on each hierarchy level."
5841 (let ((heading-p (org-on-heading-p t))
5842 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
5843 (following-p (org-get-alist-option org-show-following-heading key)))
5844 (catch 'exit
5845 ;; Show heading or entry text
5846 (if heading-p
5847 (org-flag-heading nil) ; only show the heading
5848 (and (or (org-invisible-p) (org-invisible-p2))
5849 (org-show-hidden-entry))) ; show entire entry
5850 (when following-p
5851 ;; Show next sibling, or heading below text
5852 (save-excursion
5853 (and (if heading-p (org-goto-sibling) (outline-next-heading))
5854 (org-flag-heading nil))))
5855 (when hierarchy-p
5856 ;; show all higher headings, possibly with siblings
5857 (save-excursion
5858 (while (and (condition-case nil
5859 (progn (org-up-heading-all 1) t)
5860 (error nil))
5861 (not (bobp)))
5862 (org-flag-heading nil)
5863 (when siblings
5864 (save-excursion
5865 (while (org-goto-sibling) (org-flag-heading nil)))
5866 (save-excursion
5867 (while (org-goto-sibling 'previous)
5868 (org-flag-heading nil))))))))))
5870 (defun org-reveal (&optional siblings)
5871 "Show current entry, hierarchy above it, and the following headline.
5872 This can be used to show a consistent set of context around locations
5873 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
5874 not t for the search context.
5876 With optional argument SIBLINGS, on each level of the hierarchy all
5877 siblings are shown. This repairs the tree structure so what it would
5878 look like when opend with successive calls to `org-cycle'."
5879 (interactive "P")
5880 (let ((org-show-hierarchy-above t)
5881 (org-show-following-heading t))
5882 (org-show-context nil siblings)))
5884 ;; Overlay compatibility functions
5885 (defun org-make-overlay (beg end &optional buffer)
5886 (if (featurep 'xemacs)
5887 (make-extent beg end buffer)
5888 (make-overlay beg end buffer)))
5889 (defun org-delete-overlay (ovl)
5890 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5891 (defun org-detach-overlay (ovl)
5892 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5893 (defun org-move-overlay (ovl beg end &optional buffer)
5894 (if (featurep 'xemacs)
5895 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
5896 (move-overlay ovl beg end buffer)))
5897 (defun org-overlay-put (ovl prop value)
5898 (if (featurep 'xemacs)
5899 (set-extent-property ovl prop value)
5900 (overlay-put ovl prop value)))
5901 (defun org-overlay-display (ovl text &optional face)
5902 "Make overlay OVL display TEXT with face FACE."
5903 (if (featurep 'xemacs)
5904 (let ((gl (make-glyph text)))
5905 (and face (set-glyph-face gl face))
5906 (set-extent-property ovl 'invisible t)
5907 (set-extent-property ovl 'end-glyph gl))
5908 (overlay-put ovl 'display text)
5909 (if face (overlay-put ovl 'face face))))
5910 (defun org-overlay-get (ovl prop)
5911 (if (featurep 'xemacs)
5912 (extent-property ovl prop)
5913 (overlay-get ovl prop)))
5914 (defun org-overlays-at (pos)
5915 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5916 (defun org-overlays-in (&optional start end)
5917 (if (featurep 'xemacs)
5918 (extent-list nil start end)
5919 (overlays-in start end)))
5920 (defun org-overlay-start (o)
5921 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5922 (defun org-overlay-end (o)
5923 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5924 (defun org-find-overlays (prop &optional pos delete)
5925 "Find all overlays specifying PROP at POS or point.
5926 If DELETE is non-nil, delete all those overlays."
5927 (let ((overlays (org-overlays-at (or pos (point))))
5928 ov found)
5929 (while (setq ov (pop overlays))
5930 (if (org-overlay-get ov prop)
5931 (if delete (org-delete-overlay ov) (push ov found))))
5932 found))
5934 (defun org-highlight-new-match (beg end)
5935 "Highlight from BEG to END and mark the highlight is an occur headline."
5936 (let ((ov (org-make-overlay beg end)))
5937 (org-overlay-put ov 'face 'secondary-selection)
5938 (push ov org-occur-highlights)))
5940 (defvar org-inhibit-highlight-removal nil)
5941 (defun org-remove-occur-highlights (&optional beg end noremove)
5942 "Remove the occur highlights from the buffer.
5943 BEG and END are ignored. If NOREMOVE is nil, remove this function
5944 from the `before-change-functions' in the current buffer."
5945 (interactive)
5946 (unless org-inhibit-highlight-removal
5947 (mapc 'org-delete-overlay org-occur-highlights)
5948 (setq org-occur-highlights nil)
5949 (unless noremove
5950 (remove-hook 'before-change-functions
5951 'org-remove-occur-highlights 'local))))
5953 ;;; Priorities
5955 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5956 "Regular expression matching the priority indicator.")
5958 (defvar org-remove-priority-next-time nil)
5960 (defun org-priority-up ()
5961 "Increase the priority of the current item."
5962 (interactive)
5963 (org-priority 'up))
5965 (defun org-priority-down ()
5966 "Decrease the priority of the current item."
5967 (interactive)
5968 (org-priority 'down))
5970 (defun org-priority (&optional action)
5971 "Change the priority of an item by ARG.
5972 ACTION can be set, up, or down."
5973 (interactive)
5974 (setq action (or action 'set))
5975 (let (current new news have remove)
5976 (save-excursion
5977 (org-back-to-heading)
5978 (if (looking-at org-priority-regexp)
5979 (setq current (string-to-char (match-string 2))
5980 have t)
5981 (setq current org-default-priority))
5982 (cond
5983 ((eq action 'set)
5984 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5985 (setq new (read-char-exclusive))
5986 (cond ((equal new ?\ ) (setq remove t))
5987 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5988 (error "Priority must be between `%c' and `%c'"
5989 ?A org-lowest-priority))))
5990 ((eq action 'up)
5991 (setq new (1- current)))
5992 ((eq action 'down)
5993 (setq new (1+ current)))
5994 (t (error "Invalid action")))
5995 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5996 (setq news (format "%c" new))
5997 (if have
5998 (if remove
5999 (replace-match "" t t nil 1)
6000 (replace-match news t t nil 2))
6001 (if remove
6002 (error "No priority cookie found in line")
6003 (looking-at org-todo-line-regexp)
6004 (if (match-end 2)
6005 (progn
6006 (goto-char (match-end 2))
6007 (insert " [#" news "]"))
6008 (goto-char (match-beginning 3))
6009 (insert "[#" news "] ")))))
6010 (if remove
6011 (message "Priority removed")
6012 (message "Priority of current item set to %s" news))))
6015 (defun org-get-priority (s)
6016 "Find priority cookie and return priority."
6017 (save-match-data
6018 (if (not (string-match org-priority-regexp s))
6019 (* 1000 (- org-lowest-priority org-default-priority))
6020 (* 1000 (- org-lowest-priority
6021 (string-to-char (match-string 2 s)))))))
6023 ;;; Timestamps
6025 (defvar org-last-changed-timestamp nil)
6027 (defun org-time-stamp (arg)
6028 "Prompt for a date/time and insert a time stamp.
6029 If the user specifies a time like HH:MM, or if this command is called
6030 with a prefix argument, the time stamp will contain date and time.
6031 Otherwise, only the date will be included. All parts of a date not
6032 specified by the user will be filled in from the current date/time.
6033 So if you press just return without typing anything, the time stamp
6034 will represent the current date/time. If there is already a timestamp
6035 at the cursor, it will be modified."
6036 (interactive "P")
6037 (let (org-time-was-given time)
6038 (cond
6039 ((and (org-at-timestamp-p)
6040 (eq last-command 'org-time-stamp)
6041 (eq this-command 'org-time-stamp))
6042 (insert "--")
6043 (setq time (let ((this-command this-command))
6044 (org-read-date arg 'totime)))
6045 (org-insert-time-stamp time (or org-time-was-given arg)))
6046 ((org-at-timestamp-p)
6047 (setq time (let ((this-command this-command))
6048 (org-read-date arg 'totime)))
6049 (when (org-at-timestamp-p) ; just to get the match data
6050 (replace-match "")
6051 (setq org-last-changed-timestamp
6052 (org-insert-time-stamp time (or org-time-was-given arg))))
6053 (message "Timestamp updated"))
6055 (setq time (let ((this-command this-command))
6056 (org-read-date arg 'totime)))
6057 (org-insert-time-stamp time (or org-time-was-given arg))))))
6059 (defun org-time-stamp-inactive (&optional arg)
6060 "Insert an inactive time stamp.
6061 An inactive time stamp is enclosed in square brackets instead of angle
6062 brackets. It is inactive in the sense that it does not trigger agenda entries,
6063 does not link to the calendar and cannot be changed with the S-cursor keys.
6064 So these are more for recording a certain time/date."
6065 (interactive "P")
6066 (let (org-time-was-given time)
6067 (setq time (org-read-date arg 'totime))
6068 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
6070 (defvar org-date-ovl (org-make-overlay 1 1))
6071 (org-overlay-put org-date-ovl 'face 'org-warning)
6072 (org-detach-overlay org-date-ovl)
6074 (defun org-read-date (&optional with-time to-time from-string)
6075 "Read a date and make things smooth for the user.
6076 The prompt will suggest to enter an ISO date, but you can also enter anything
6077 which will at least partially be understood by `parse-time-string'.
6078 Unrecognized parts of the date will default to the current day, month, year,
6079 hour and minute. For example,
6080 3-2-5 --> 2003-02-05
6081 feb 15 --> currentyear-02-15
6082 sep 12 9 --> 2009-09-12
6083 12:45 --> today 12:45
6084 22 sept 0:34 --> currentyear-09-22 0:34
6085 12 --> currentyear-currentmonth-12
6086 Fri --> nearest Friday (today or later)
6087 +4 --> four days from today (only if +N is the only thing given)
6088 etc.
6089 The function understands only English month and weekday abbreviations,
6090 but this can be configured with the variables `parse-time-months' and
6091 `parse-time-weekdays'.
6093 While prompting, a calendar is popped up - you can also select the
6094 date with the mouse (button 1). The calendar shows a period of three
6095 months. To scroll it to other months, use the keys `>' and `<'.
6096 If you don't like the calendar, turn it off with
6097 \(setq org-popup-calendar-for-date-prompt nil)
6099 With optional argument TO-TIME, the date will immediately be converted
6100 to an internal time.
6101 With an optional argument WITH-TIME, the prompt will suggest to also
6102 insert a time. Note that when WITH-TIME is not set, you can still
6103 enter a time, and this function will inform the calling routine about
6104 this change. The calling routine may then choose to change the format
6105 used to insert the time stamp into the buffer to include the time."
6106 (require 'parse-time)
6107 (let* ((org-time-stamp-rounding-minutes
6108 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
6109 (ct (org-current-time))
6110 (default-time
6111 ;; Default time is either today, or, when entering a range,
6112 ;; the range start.
6113 (if (save-excursion
6114 (re-search-backward
6115 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
6116 (- (point) 20) t))
6117 (apply
6118 'encode-time
6119 (mapcar (lambda(x) (or x 0))
6120 (parse-time-string (match-string 1))))
6121 ct))
6122 (calendar-move-hook nil)
6123 (view-diary-entries-initially nil)
6124 (view-calendar-holidays-initially nil)
6125 (timestr (format-time-string
6126 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
6127 (prompt (format "YYYY-MM-DD [%s]: " timestr))
6128 ans ans1 ans2 (deltadays 0)
6129 second minute hour day month year tl wday wday1)
6131 (cond
6132 (from-string (setq ans from-string))
6133 (org-popup-calendar-for-date-prompt
6134 (save-excursion
6135 (save-window-excursion
6136 (calendar)
6137 (calendar-forward-day (- (time-to-days default-time)
6138 (calendar-absolute-from-gregorian
6139 (calendar-current-date))))
6140 (org-eval-in-calendar nil)
6141 (let* ((old-map (current-local-map))
6142 (map (copy-keymap calendar-mode-map))
6143 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
6144 (define-key map (kbd "RET") 'org-calendar-select)
6145 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
6146 'org-calendar-select-mouse)
6147 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
6148 'org-calendar-select-mouse)
6149 (define-key minibuffer-local-map [(meta shift left)]
6150 (lambda () (interactive)
6151 (org-eval-in-calendar '(calendar-backward-month 1))))
6152 (define-key minibuffer-local-map [(meta shift right)]
6153 (lambda () (interactive)
6154 (org-eval-in-calendar '(calendar-forward-month 1))))
6155 (define-key minibuffer-local-map [(shift up)]
6156 (lambda () (interactive)
6157 (org-eval-in-calendar '(calendar-backward-week 1))))
6158 (define-key minibuffer-local-map [(shift down)]
6159 (lambda () (interactive)
6160 (org-eval-in-calendar '(calendar-forward-week 1))))
6161 (define-key minibuffer-local-map [(shift left)]
6162 (lambda () (interactive)
6163 (org-eval-in-calendar '(calendar-backward-day 1))))
6164 (define-key minibuffer-local-map [(shift right)]
6165 (lambda () (interactive)
6166 (org-eval-in-calendar '(calendar-forward-day 1))))
6167 (define-key minibuffer-local-map ">"
6168 (lambda () (interactive)
6169 (org-eval-in-calendar '(scroll-calendar-left 1))))
6170 (define-key minibuffer-local-map "<"
6171 (lambda () (interactive)
6172 (org-eval-in-calendar '(scroll-calendar-right 1))))
6173 (unwind-protect
6174 (progn
6175 (use-local-map map)
6176 (setq ans (read-string prompt "" nil nil))
6177 (if (not (string-match "\\S-" ans)) (setq ans nil))
6178 (setq ans (or ans1 ans ans2)))
6179 (use-local-map old-map))))))
6180 (t ; Naked prompt only
6181 (setq ans (read-string prompt "" nil timestr))))
6182 (org-detach-overlay org-date-ovl)
6184 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" ans)
6185 (setq deltadays (string-to-number ans) ans ""))
6187 (if (string-match
6188 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
6189 (progn
6190 (setq year (if (match-end 2)
6191 (string-to-number (match-string 2 ans))
6192 (string-to-number (format-time-string "%Y")))
6193 month (string-to-number (match-string 3 ans))
6194 day (string-to-number (match-string 4 ans)))
6195 (if (< year 100) (setq year (+ 2000 year)))
6196 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
6197 t nil ans))))
6198 (setq tl (parse-time-string ans)
6199 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
6200 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
6201 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
6202 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
6203 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
6204 second (or (nth 0 tl) 0)
6205 wday (nth 6 tl))
6206 (setq day (+ day deltadays))
6207 (when (and wday (not (nth 3 tl)))
6208 ;; Weekday was given, but no day, so pick that day in the week
6209 ;; on or after the derived date.
6210 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
6211 (unless (equal wday wday1)
6212 (setq day (+ day (% (- wday wday1 -7) 7)))))
6213 (if (and (boundp 'org-time-was-given)
6214 (nth 2 tl))
6215 (setq org-time-was-given t))
6216 (if (< year 100) (setq year (+ 2000 year)))
6217 (if to-time
6218 (encode-time second minute hour day month year)
6219 (if (or (nth 1 tl) (nth 2 tl))
6220 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
6221 (format "%04d-%02d-%02d" year month day)))))
6223 (defun org-eval-in-calendar (form)
6224 "Eval FORM in the calendar window and return to current window.
6225 Also, store the cursor date in variable ans2."
6226 (let ((sw (selected-window)))
6227 (select-window (get-buffer-window "*Calendar*"))
6228 (eval form)
6229 (when (calendar-cursor-to-date)
6230 (let* ((date (calendar-cursor-to-date))
6231 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6232 (setq ans2 (format-time-string "%Y-%m-%d" time))))
6233 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
6234 (select-window sw)))
6236 (defun org-calendar-select ()
6237 "Return to `org-read-date' with the date currently selected.
6238 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6239 (interactive)
6240 (when (calendar-cursor-to-date)
6241 (let* ((date (calendar-cursor-to-date))
6242 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6243 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6244 (if (active-minibuffer-window) (exit-minibuffer))))
6246 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
6247 "Insert a date stamp for the date given by the internal TIME.
6248 WITH-HM means, use the stamp format that includes the time of the day.
6249 INACTIVE means use square brackets instead of angular ones, so that the
6250 stamp will not contribute to the agenda.
6251 PRE and POST are optional strings to be inserted before and after the
6252 stamp.
6253 The command returns the inserted time stamp."
6254 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
6255 stamp)
6256 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
6257 (insert (or pre ""))
6258 (insert (setq stamp (format-time-string fmt time)))
6259 (insert (or post ""))
6260 stamp))
6262 (defun org-toggle-time-stamp-overlays ()
6263 "Toggle the use of custom time stamp formats."
6264 (interactive)
6265 (setq org-display-custom-times (not org-display-custom-times))
6266 (unless org-display-custom-times
6267 (let ((p (point-min)) (bmp (buffer-modified-p)))
6268 (while (setq p (next-single-property-change p 'display))
6269 (if (and (get-text-property p 'display)
6270 (eq (get-text-property p 'face) 'org-date))
6271 (remove-text-properties
6272 p (setq p (next-single-property-change p 'display))
6273 '(display t))))
6274 (set-buffer-modified-p bmp)))
6275 (if (featurep 'xemacs)
6276 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
6277 (org-restart-font-lock)
6278 (setq org-table-may-need-update t)
6279 (if org-display-custom-times
6280 (message "Time stamps are overlayed with custom format")
6281 (message "Time stamp overlays removed")))
6283 (defun org-display-custom-time (beg end)
6284 "Overlay modified time stamp format over timestamp between BED and END."
6285 (let* ((t1 (save-match-data
6286 (org-parse-time-string (buffer-substring beg end) t)))
6287 (w1 (- end beg))
6288 (with-hm (and (nth 1 t1) (nth 2 t1)))
6289 (inactive (= (char-before (1- beg)) ?\[))
6290 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
6291 (time (org-fix-decoded-time t1))
6292 (str (org-add-props
6293 (format-time-string
6294 (substring tf 1 -1) (apply 'encode-time time))
6295 nil 'mouse-face 'highlight))
6296 (w2 (length str)))
6297 (if (not (= w2 w1))
6298 (add-text-properties (1+ beg) (+ 2 beg)
6299 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
6300 (if (featurep 'xemacs)
6301 (progn
6302 (put-text-property beg end 'invisible t)
6303 (put-text-property beg end 'end-glyph (make-glyph str)))
6304 (put-text-property beg end 'display str))))
6306 (defun org-translate-time (string)
6307 "Translate all timestamps in STRING to custom format.
6308 But do this only if the variable `org-display-custom-times' is set."
6309 (when org-display-custom-times
6310 (save-match-data
6311 (let* ((start 0)
6312 (re org-ts-regexp-both)
6313 t1 with-hm inactive tf time str beg end)
6314 (while (setq start (string-match re string start))
6315 (setq beg (match-beginning 0)
6316 end (match-end 0)
6317 t1 (save-match-data
6318 (org-parse-time-string (substring string beg end) t))
6319 with-hm (and (nth 1 t1) (nth 2 t1))
6320 inactive (equal (substring string beg (1+ beg)) "[")
6321 tf (funcall (if with-hm 'cdr 'car)
6322 org-time-stamp-custom-formats)
6323 time (org-fix-decoded-time t1)
6324 str (format-time-string
6325 (concat
6326 (if inactive "[" "<") (substring tf 1 -1)
6327 (if inactive "]" ">"))
6328 (apply 'encode-time time))
6329 string (replace-match str t t string)
6330 start (+ start (length str)))))))
6331 string)
6333 (defun org-fix-decoded-time (time)
6334 "Set 0 instead of nil for the first 6 elements of time.
6335 Don't touch the rest."
6336 (let ((n 0))
6337 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
6339 (defun org-days-to-time (timestamp-string)
6340 "Difference between TIMESTAMP-STRING and now in days."
6341 (- (time-to-days (org-time-string-to-time timestamp-string))
6342 (time-to-days (current-time))))
6344 (defun org-deadline-close (timestamp-string &optional ndays)
6345 "Is the time in TIMESTAMP-STRING close to the current date?"
6346 (and (< (org-days-to-time timestamp-string)
6347 (or ndays org-deadline-warning-days))
6348 (not (org-entry-is-done-p))))
6350 (defun org-calendar-select-mouse (ev)
6351 "Return to `org-read-date' with the date currently selected.
6352 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
6353 (interactive "e")
6354 (mouse-set-point ev)
6355 (when (calendar-cursor-to-date)
6356 (let* ((date (calendar-cursor-to-date))
6357 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
6358 (setq ans1 (format-time-string "%Y-%m-%d" time)))
6359 (if (active-minibuffer-window) (exit-minibuffer))))
6361 (defun org-check-deadlines (ndays)
6362 "Check if there are any deadlines due or past due.
6363 A deadline is considered due if it happens within `org-deadline-warning-days'
6364 days from today's date. If the deadline appears in an entry marked DONE,
6365 it is not shown. The prefix arg NDAYS can be used to test that many
6366 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
6367 (interactive "P")
6368 (let* ((org-warn-days
6369 (cond
6370 ((equal ndays '(4)) 100000)
6371 (ndays (prefix-numeric-value ndays))
6372 (t org-deadline-warning-days)))
6373 (case-fold-search nil)
6374 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
6375 (callback
6376 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
6378 (message "%d deadlines past-due or due within %d days"
6379 (org-occur regexp nil callback)
6380 org-warn-days)))
6382 (defun org-evaluate-time-range (&optional to-buffer)
6383 "Evaluate a time range by computing the difference between start and end.
6384 Normally the result is just printed in the echo area, but with prefix arg
6385 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
6386 If the time range is actually in a table, the result is inserted into the
6387 next column.
6388 For time difference computation, a year is assumed to be exactly 365
6389 days in order to avoid rounding problems."
6390 (interactive "P")
6392 (org-clock-update-time-maybe)
6393 (save-excursion
6394 (unless (org-at-date-range-p)
6395 (goto-char (point-at-bol))
6396 (re-search-forward org-tr-regexp (point-at-eol) t))
6397 (if (not (org-at-date-range-p))
6398 (error "Not at a time-stamp range, and none found in current line")))
6399 (let* ((ts1 (match-string 1))
6400 (ts2 (match-string 2))
6401 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
6402 (match-end (match-end 0))
6403 (time1 (org-time-string-to-time ts1))
6404 (time2 (org-time-string-to-time ts2))
6405 (t1 (time-to-seconds time1))
6406 (t2 (time-to-seconds time2))
6407 (diff (abs (- t2 t1)))
6408 (negative (< (- t2 t1) 0))
6409 ;; (ys (floor (* 365 24 60 60)))
6410 (ds (* 24 60 60))
6411 (hs (* 60 60))
6412 (fy "%dy %dd %02d:%02d")
6413 (fy1 "%dy %dd")
6414 (fd "%dd %02d:%02d")
6415 (fd1 "%dd")
6416 (fh "%02d:%02d")
6417 y d h m align)
6418 (if havetime
6419 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6421 d (floor (/ diff ds)) diff (mod diff ds)
6422 h (floor (/ diff hs)) diff (mod diff hs)
6423 m (floor (/ diff 60)))
6424 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
6426 d (floor (+ (/ diff ds) 0.5))
6427 h 0 m 0))
6428 (if (not to-buffer)
6429 (message (org-make-tdiff-string y d h m))
6430 (when (org-at-table-p)
6431 (goto-char match-end)
6432 (setq align t)
6433 (and (looking-at " *|") (goto-char (match-end 0))))
6434 (if (looking-at
6435 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
6436 (replace-match ""))
6437 (if negative (insert " -"))
6438 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
6439 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
6440 (insert " " (format fh h m))))
6441 (if align (org-table-align))
6442 (message "Time difference inserted")))))
6444 (defun org-make-tdiff-string (y d h m)
6445 (let ((fmt "")
6446 (l nil))
6447 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
6448 l (push y l)))
6449 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
6450 l (push d l)))
6451 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
6452 l (push h l)))
6453 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
6454 l (push m l)))
6455 (apply 'format fmt (nreverse l))))
6457 (defun org-time-string-to-time (s)
6458 (apply 'encode-time (org-parse-time-string s)))
6460 (defun org-parse-time-string (s &optional nodefault)
6461 "Parse the standard Org-mode time string.
6462 This should be a lot faster than the normal `parse-time-string'.
6463 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
6464 hour and minute fields will be nil if not given."
6465 (if (string-match org-ts-regexp1 s)
6466 (list 0
6467 (if (or (match-beginning 8) (not nodefault))
6468 (string-to-number (or (match-string 8 s) "0")))
6469 (if (or (match-beginning 7) (not nodefault))
6470 (string-to-number (or (match-string 7 s) "0")))
6471 (string-to-number (match-string 4 s))
6472 (string-to-number (match-string 3 s))
6473 (string-to-number (match-string 2 s))
6474 nil nil nil)
6475 (make-list 9 0)))
6477 (defun org-timestamp-up (&optional arg)
6478 "Increase the date item at the cursor by one.
6479 If the cursor is on the year, change the year. If it is on the month or
6480 the day, change that.
6481 With prefix ARG, change by that many units."
6482 (interactive "p")
6483 (org-timestamp-change (prefix-numeric-value arg)))
6485 (defun org-timestamp-down (&optional arg)
6486 "Decrease the date item at the cursor by one.
6487 If the cursor is on the year, change the year. If it is on the month or
6488 the day, change that.
6489 With prefix ARG, change by that many units."
6490 (interactive "p")
6491 (org-timestamp-change (- (prefix-numeric-value arg))))
6493 (defun org-timestamp-up-day (&optional arg)
6494 "Increase the date in the time stamp by one day.
6495 With prefix ARG, change that many days."
6496 (interactive "p")
6497 (if (and (not (org-at-timestamp-p t))
6498 (org-on-heading-p))
6499 (org-todo 'up)
6500 (org-timestamp-change (prefix-numeric-value arg) 'day)))
6502 (defun org-timestamp-down-day (&optional arg)
6503 "Decrease the date in the time stamp by one day.
6504 With prefix ARG, change that many days."
6505 (interactive "p")
6506 (if (and (not (org-at-timestamp-p t))
6507 (org-on-heading-p))
6508 (org-todo 'down)
6509 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
6511 (defsubst org-pos-in-match-range (pos n)
6512 (and (match-beginning n)
6513 (<= (match-beginning n) pos)
6514 (>= (match-end n) pos)))
6516 (defun org-at-timestamp-p (&optional inactive-ok)
6517 "Determine if the cursor is in or at a timestamp."
6518 (interactive)
6519 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
6520 (pos (point))
6521 (ans (or (looking-at tsr)
6522 (save-excursion
6523 (skip-chars-backward "^[<\n\r\t")
6524 (if (> (point) 1) (backward-char 1))
6525 (and (looking-at tsr)
6526 (> (- (match-end 0) pos) -1))))))
6527 (and (boundp 'org-ts-what)
6528 (setq org-ts-what
6529 (cond
6530 ((org-pos-in-match-range pos 2) 'year)
6531 ((org-pos-in-match-range pos 3) 'month)
6532 ((org-pos-in-match-range pos 7) 'hour)
6533 ((org-pos-in-match-range pos 8) 'minute)
6534 ((or (org-pos-in-match-range pos 4)
6535 (org-pos-in-match-range pos 5)) 'day)
6536 (t 'day))))
6537 ans))
6539 (defun org-timestamp-change (n &optional what)
6540 "Change the date in the time stamp at point.
6541 The date will be changed by N times WHAT. WHAT can be `day', `month',
6542 `year', `minute', `second'. If WHAT is not given, the cursor position
6543 in the timestamp determines what will be changed."
6544 (let ((pos (point))
6545 with-hm inactive
6546 org-ts-what
6547 ts time time0)
6548 (if (not (org-at-timestamp-p t))
6549 (error "Not at a timestamp"))
6550 (if (and (not what) (not (eq org-ts-what 'day))
6551 org-display-custom-times
6552 (get-text-property (point) 'display)
6553 (not (get-text-property (1- (point)) 'display)))
6554 (setq org-ts-what 'day))
6555 (setq org-ts-what (or what org-ts-what)
6556 with-hm (<= (abs (- (cdr org-ts-lengths)
6557 (- (match-end 0) (match-beginning 0))))
6559 inactive (= (char-after (match-beginning 0)) ?\[)
6560 ts (match-string 0))
6561 (replace-match "")
6562 (setq time0 (org-parse-time-string ts))
6563 (setq time
6564 (apply 'encode-time
6565 (append
6566 (list (or (car time0) 0))
6567 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
6568 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
6569 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
6570 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
6571 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
6572 (nthcdr 6 time0))))
6573 (if (eq what 'calendar)
6574 (let ((cal-date
6575 (save-excursion
6576 (save-match-data
6577 (set-buffer "*Calendar*")
6578 (calendar-cursor-to-date)))))
6579 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
6580 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
6581 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
6582 (setcar time0 (or (car time0) 0))
6583 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
6584 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
6585 (setq time (apply 'encode-time time0))))
6586 (setq org-last-changed-timestamp
6587 (org-insert-time-stamp time with-hm inactive))
6588 (org-clock-update-time-maybe)
6589 (goto-char pos)
6590 ;; Try to recenter the calendar window, if any
6591 (if (and org-calendar-follow-timestamp-change
6592 (get-buffer-window "*Calendar*" t)
6593 (memq org-ts-what '(day month year)))
6594 (org-recenter-calendar (time-to-days time)))))
6596 (defun org-recenter-calendar (date)
6597 "If the calendar is visible, recenter it to DATE."
6598 (let* ((win (selected-window))
6599 (cwin (get-buffer-window "*Calendar*" t))
6600 (calendar-move-hook nil))
6601 (when cwin
6602 (select-window cwin)
6603 (calendar-goto-date (if (listp date) date
6604 (calendar-gregorian-from-absolute date)))
6605 (select-window win))))
6607 (defun org-goto-calendar (&optional arg)
6608 "Go to the Emacs calendar at the current date.
6609 If there is a time stamp in the current line, go to that date.
6610 A prefix ARG can be used to force the current date."
6611 (interactive "P")
6612 (let ((tsr org-ts-regexp) diff
6613 (calendar-move-hook nil)
6614 (view-calendar-holidays-initially nil)
6615 (view-diary-entries-initially nil))
6616 (if (or (org-at-timestamp-p)
6617 (save-excursion
6618 (beginning-of-line 1)
6619 (looking-at (concat ".*" tsr))))
6620 (let ((d1 (time-to-days (current-time)))
6621 (d2 (time-to-days
6622 (org-time-string-to-time (match-string 1)))))
6623 (setq diff (- d2 d1))))
6624 (calendar)
6625 (calendar-goto-today)
6626 (if (and diff (not arg)) (calendar-forward-day diff))))
6628 (defun org-date-from-calendar ()
6629 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
6630 If there is already a time stamp at the cursor position, update it."
6631 (interactive)
6632 (org-timestamp-change 0 'calendar))
6634 ;;; The clock for measuring work time.
6636 (defvar org-clock-marker (make-marker)
6637 "Marker recording the last clock-in.")
6639 (defun org-clock-in ()
6640 "Start the clock on the current item.
6641 If necessary, clock-out of the currently active clock."
6642 (interactive)
6643 (org-clock-out t)
6644 (let (ts)
6645 (save-excursion
6646 (org-back-to-heading t)
6647 (beginning-of-line 2)
6648 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6649 (not (equal (match-string 1) org-clock-string)))
6650 (beginning-of-line 1))
6651 (insert "\n") (backward-char 1)
6652 (indent-relative)
6653 (insert org-clock-string " ")
6654 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6655 (move-marker org-clock-marker (point))
6656 (message "Clock started at %s" ts))))
6658 (defun org-clock-out (&optional fail-quietly)
6659 "Stop the currently running clock.
6660 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
6661 (interactive)
6662 (catch 'exit
6663 (if (not (marker-buffer org-clock-marker))
6664 (if fail-quietly (throw 'exit t) (error "No active clock")))
6665 (let (ts te s h m)
6666 (save-excursion
6667 (set-buffer (marker-buffer org-clock-marker))
6668 (goto-char org-clock-marker)
6669 (beginning-of-line 1)
6670 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6671 (equal (match-string 1) org-clock-string))
6672 (setq ts (match-string 2))
6673 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
6674 (goto-char org-clock-marker)
6675 (insert "--")
6676 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
6677 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
6678 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
6679 h (floor (/ s 3600))
6680 s (- s (* 3600 h))
6681 m (floor (/ s 60))
6682 s (- s (* 60 s)))
6683 (insert " => " (format "%2d:%02d" h m))
6684 (move-marker org-clock-marker nil)
6685 (org-add-log-maybe 'clock-out)
6686 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
6688 (defun org-clock-cancel ()
6689 "Cancel the running clock be removing the start timestamp."
6690 (interactive)
6691 (if (not (marker-buffer org-clock-marker))
6692 (error "No active clock"))
6693 (save-excursion
6694 (set-buffer (marker-buffer org-clock-marker))
6695 (goto-char org-clock-marker)
6696 (delete-region (1- (point-at-bol)) (point-at-eol)))
6697 (message "Clock canceled"))
6699 (defvar org-clock-file-total-minutes nil
6700 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
6701 (make-variable-buffer-local 'org-clock-file-total-minutes)
6703 (defun org-clock-sum (&optional tstart tend)
6704 "Sum the times for each subtree.
6705 Puts the resulting times in minutes as a text property on each headline."
6706 (interactive)
6707 (let* ((bmp (buffer-modified-p))
6708 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
6709 org-clock-string
6710 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
6711 (lmax 30)
6712 (ltimes (make-vector lmax 0))
6713 (t1 0)
6714 (level 0)
6715 ts te dt
6716 time)
6717 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
6718 (save-excursion
6719 (goto-char (point-max))
6720 (while (re-search-backward re nil t)
6721 (if (match-end 2)
6722 ;; A time
6723 (setq ts (match-string 2)
6724 te (match-string 3)
6725 ts (time-to-seconds
6726 (apply 'encode-time (org-parse-time-string ts)))
6727 te (time-to-seconds
6728 (apply 'encode-time (org-parse-time-string te)))
6729 ts (if tstart (max ts tstart) ts)
6730 te (if tend (min te tend) te)
6731 dt (- te ts)
6732 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
6733 ;; A headline
6734 (setq level (- (match-end 1) (match-beginning 1)))
6735 (when (or (> t1 0) (> (aref ltimes level) 0))
6736 (loop for l from 0 to level do
6737 (aset ltimes l (+ (aref ltimes l) t1)))
6738 (setq t1 0 time (aref ltimes level))
6739 (loop for l from level to (1- lmax) do
6740 (aset ltimes l 0))
6741 (goto-char (match-beginning 0))
6742 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
6743 (setq org-clock-file-total-minutes (aref ltimes 0)))
6744 (set-buffer-modified-p bmp)))
6746 (defun org-clock-display (&optional total-only)
6747 "Show subtree times in the entire buffer.
6748 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6749 in the echo area."
6750 (interactive)
6751 (org-remove-clock-overlays)
6752 (let (time h m p)
6753 (org-clock-sum)
6754 (unless total-only
6755 (save-excursion
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 (org-put-clock-overlay time (funcall outline-level))))
6761 (setq h (/ org-clock-file-total-minutes 60)
6762 m (- org-clock-file-total-minutes (* 60 h)))
6763 ;; Arrange to remove the overlays upon next change.
6764 (when org-remove-highlights-with-change
6765 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6766 nil 'local))))
6767 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6769 (defvar org-clock-overlays nil)
6770 (make-variable-buffer-local 'org-clock-overlays)
6772 (defun org-put-clock-overlay (time &optional level)
6773 "Put an overlays on the current line, displaying TIME.
6774 If LEVEL is given, prefix time with a corresponding number of stars.
6775 This creates a new overlay and stores it in `org-clock-overlays', so that it
6776 will be easy to remove."
6777 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6778 (l (if level (org-get-legal-level level 0) 0))
6779 (off 0)
6780 ov tx)
6781 (move-to-column c)
6782 (unless (eolp) (skip-chars-backward "^ \t"))
6783 (skip-chars-backward " \t")
6784 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6785 tx (concat (buffer-substring (1- (point)) (point))
6786 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6787 (org-add-props (format "%s %2d:%02d%s"
6788 (make-string l ?*) h m
6789 (make-string (- 10 l) ?\ ))
6790 '(face secondary-selection))
6791 ""))
6792 (if (not (featurep 'xemacs))
6793 (org-overlay-put ov 'display tx)
6794 (org-overlay-put ov 'invisible t)
6795 (org-overlay-put ov 'end-glyph (make-glyph tx)))
6796 (push ov org-clock-overlays)))
6798 (defun org-remove-clock-overlays (&optional beg end noremove)
6799 "Remove the occur highlights from the buffer.
6800 BEG and END are ignored. If NOREMOVE is nil, remove this function
6801 from the `before-change-functions' in the current buffer."
6802 (interactive)
6803 (unless org-inhibit-highlight-removal
6804 (mapc 'org-delete-overlay org-clock-overlays)
6805 (setq org-clock-overlays nil)
6806 (unless noremove
6807 (remove-hook 'before-change-functions
6808 'org-remove-clock-overlays 'local))))
6810 (defun org-clock-out-if-current ()
6811 "Clock out if the current entry contains the running clock.
6812 This is used to stop the clock after a TODO entry is marked DONE."
6813 (when (and (equal state org-done-string)
6814 (equal (marker-buffer org-clock-marker) (current-buffer))
6815 (< (point) org-clock-marker)
6816 (> (save-excursion (outline-next-heading) (point))
6817 org-clock-marker))
6818 ;; Clock out, but don't accept a logging message for this.
6819 (let ((org-log-done (if (and (listp org-log-done)
6820 (member 'clock-out org-log-done))
6821 '(done)
6822 org-log-done)))
6823 (org-clock-out))))
6825 (add-hook 'org-after-todo-state-change-hook
6826 'org-clock-out-if-current)
6828 (defun org-check-running-clock ()
6829 "Check if the current buffer contains the running clock.
6830 If yes, offer to stop it and to save the buffer with the changes."
6831 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6832 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6833 (buffer-name))))
6834 (org-clock-out)
6835 (when (y-or-n-p "Save changed buffer?")
6836 (save-buffer))))
6838 (defun org-clock-report ()
6839 "Create a table containing a report about clocked time.
6840 If the buffer contains lines
6841 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6843 #+END: clocktable
6844 then the table will be inserted between these lines, replacing whatever
6845 is was there before. If these lines are not in the buffer, the table
6846 is inserted at point, surrounded by the special lines.
6847 The BEGIN line can contain parameters. Allowed are:
6848 :maxlevel The maximum level to be included in the table. Default is 3.
6849 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6850 (interactive)
6851 (org-remove-clock-overlays)
6852 (unless (org-find-dblock "clocktable")
6853 (org-create-dblock (list :name "clocktable"
6854 :maxlevel 2 :emphasize nil)))
6855 (org-update-dblock))
6857 (defun org-clock-update-time-maybe ()
6858 "If this is a CLOCK line, update it and return t.
6859 Otherwise, return nil."
6860 (interactive)
6861 (save-excursion
6862 (beginning-of-line 1)
6863 (skip-chars-forward " \t")
6864 (when (looking-at org-clock-string)
6865 (let ((re (concat "[ \t]*" org-clock-string
6866 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6867 "\\([ \t]*=>.*\\)?"))
6868 ts te h m s)
6869 (if (not (looking-at re))
6871 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6872 (end-of-line 1)
6873 (setq ts (match-string 1)
6874 te (match-string 2))
6875 (setq s (- (time-to-seconds
6876 (apply 'encode-time (org-parse-time-string te)))
6877 (time-to-seconds
6878 (apply 'encode-time (org-parse-time-string ts))))
6879 h (floor (/ s 3600))
6880 s (- s (* 3600 h))
6881 m (floor (/ s 60))
6882 s (- s (* 60 s)))
6883 (insert " => " (format "%2d:%02d" h m))
6884 t)))))
6886 (defun org-clock-special-range (key &optional time as-strings)
6887 "Return two times bordering a special time range.
6888 Key is a symbol specifying the range and can be one of `today', `yesterday',
6889 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6890 A week starts Monday 0:00 and ends Sunday 24:00.
6891 The range is determined relative to TIME. TIME defaults to the current time.
6892 The return value is a cons cell with two internal times like the ones
6893 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6894 the returned times will be formatted strings."
6895 (let* ((tm (decode-time (or time (current-time))))
6896 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6897 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6898 (dow (nth 6 tm))
6899 s1 m1 h1 d1 month1 y1 diff ts te fm)
6900 (cond
6901 ((eq key 'today)
6902 (setq h 0 m 0 h1 24 m1 0))
6903 ((eq key 'yesterday)
6904 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6905 ((eq key 'thisweek)
6906 (setq diff (if (= dow 0) 6 (1- dow))
6907 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6908 ((eq key 'lastweek)
6909 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6910 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6911 ((eq key 'thismonth)
6912 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6913 ((eq key 'lastmonth)
6914 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6915 ((eq key 'thisyear)
6916 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6917 ((eq key 'lastyear)
6918 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6919 (t (error "No such time block %s" key)))
6920 (setq ts (encode-time s m h d month y)
6921 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6922 (or d1 d) (or month1 month) (or y1 y)))
6923 (setq fm (cdr org-time-stamp-formats))
6924 (if as-strings
6925 (cons (format-time-string fm ts) (format-time-string fm te))
6926 (cons ts te))))
6928 (defun org-dblock-write:clocktable (params)
6929 "Write the standard clocktable."
6930 (let ((hlchars '((1 . "*") (2 . ?/)))
6931 (emph nil)
6932 (ins (make-marker))
6933 ipos time h m p level hlc hdl maxlevel
6934 ts te cc block)
6935 (setq maxlevel (or (plist-get params :maxlevel) 3)
6936 emph (plist-get params :emphasize)
6937 ts (plist-get params :tstart)
6938 te (plist-get params :tend)
6939 block (plist-get params :block))
6940 (when block
6941 (setq cc (org-clock-special-range block nil t)
6942 ts (car cc) te (cdr cc)))
6943 (if ts (setq ts (time-to-seconds
6944 (apply 'encode-time (org-parse-time-string ts)))))
6945 (if te (setq te (time-to-seconds
6946 (apply 'encode-time (org-parse-time-string te)))))
6947 (move-marker ins (point))
6948 (setq ipos (point))
6949 ;; FIXME: does not yet use org-insert-time-stamp
6950 (insert-before-markers "Clock summary at ["
6951 (substring
6952 (format-time-string (cdr org-time-stamp-formats))
6953 1 -1)
6954 "]."
6955 (if block
6956 (format " Considered range is /%s/." block)
6958 "\n\n|L|Headline|Time|\n")
6959 (org-clock-sum ts te)
6960 (setq h (/ org-clock-file-total-minutes 60)
6961 m (- org-clock-file-total-minutes (* 60 h)))
6962 (insert-before-markers "|-\n|0|" "*Total file time*| "
6963 (format "*%d:%02d*" h m)
6964 "|\n")
6965 (goto-char (point-min))
6966 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6967 (goto-char p)
6968 (when (setq time (get-text-property p :org-clock-minutes))
6969 (save-excursion
6970 (beginning-of-line 1)
6971 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6972 (setq level (- (match-end 1) (match-beginning 1)))
6973 (<= level maxlevel))
6974 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6975 hdl (match-string 2)
6976 h (/ time 60)
6977 m (- time (* 60 h)))
6978 (goto-char ins)
6979 (if (= level 1) (insert-before-markers "|-\n"))
6980 (insert-before-markers
6981 "| " (int-to-string level) "|" hlc hdl hlc " |"
6982 (make-string (1- level) ?|)
6984 (format "%d:%02d" h m)
6986 " |\n")))))
6987 (goto-char ins)
6988 (backward-delete-char 1)
6989 (goto-char ipos)
6990 (skip-chars-forward "^|")
6991 (org-table-align)))
6993 (defun org-collect-clock-time-entries ()
6994 "Return an internal list with clocking information.
6995 This list has one entry for each CLOCK interval.
6996 FIXME: describe the elements."
6997 (interactive)
6998 (let ((re (concat "^[ \t]*" org-clock-string
6999 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
7000 rtn beg end next cont level title total closedp leafp
7001 clockpos titlepos h m donep)
7002 (save-excursion
7003 (org-clock-sum)
7004 (goto-char (point-min))
7005 (while (re-search-forward re nil t)
7006 (setq clockpos (match-beginning 0)
7007 beg (match-string 1) end (match-string 2)
7008 cont (match-end 0))
7009 (setq beg (apply 'encode-time (org-parse-time-string beg))
7010 end (apply 'encode-time (org-parse-time-string end)))
7011 (org-back-to-heading t)
7012 (setq donep (org-entry-is-done-p))
7013 (setq titlepos (point)
7014 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
7015 h (/ total 60) m (- total (* 60 h))
7016 total (cons h m))
7017 (looking-at "\\(\\*+\\) +\\(.*\\)")
7018 (setq level (- (match-end 1) (match-beginning 1))
7019 title (org-match-string-no-properties 2))
7020 (save-excursion (outline-next-heading) (setq next (point)))
7021 (setq closedp (re-search-forward org-closed-time-regexp next t))
7022 (goto-char next)
7023 (setq leafp (and (looking-at "^\\*+ ")
7024 (<= (- (match-end 0) (point)) level)))
7025 (push (list beg end clockpos closedp donep
7026 total title titlepos level leafp)
7027 rtn)
7028 (goto-char cont)))
7029 (nreverse rtn)))
7031 ;;; Agenda, and Diary Integration
7033 ;;; Define the mode
7035 (defvar org-agenda-mode-map (make-sparse-keymap)
7036 "Keymap for `org-agenda-mode'.")
7038 (defvar org-agenda-menu) ; defined later in this file.
7039 (defvar org-agenda-follow-mode nil)
7040 (defvar org-agenda-show-log nil)
7041 (defvar org-agenda-redo-command nil)
7042 (defvar org-agenda-mode-hook nil)
7043 (defvar org-agenda-type nil)
7044 (defvar org-agenda-force-single-file nil)
7046 (defun org-agenda-mode ()
7047 "Mode for time-sorted view on action items in Org-mode files.
7049 The following commands are available:
7051 \\{org-agenda-mode-map}"
7052 (interactive)
7053 (kill-all-local-variables)
7054 (setq major-mode 'org-agenda-mode)
7055 (setq mode-name "Org-Agenda")
7056 (use-local-map org-agenda-mode-map)
7057 (easy-menu-add org-agenda-menu)
7058 (if org-startup-truncated (setq truncate-lines t))
7059 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
7060 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
7061 (unless org-agenda-keep-modes
7062 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
7063 org-agenda-show-log nil))
7064 (easy-menu-change
7065 '("Agenda") "Agenda Files"
7066 (append
7067 (list
7068 (vector
7069 (if (get 'org-agenda-files 'org-restrict)
7070 "Restricted to single file"
7071 "Edit File List")
7072 '(org-edit-agenda-file-list)
7073 (not (get 'org-agenda-files 'org-restrict)))
7074 "--")
7075 (mapcar 'org-file-menu-entry (org-agenda-files))))
7076 (org-agenda-set-mode-name)
7077 (apply
7078 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
7079 (list 'org-agenda-mode-hook)))
7081 ;(substitute-key-definition 'undo 'org-agenda-undo
7082 ; org-agenda-mode-map global-map)
7083 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
7084 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
7085 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
7086 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
7087 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
7088 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
7089 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
7090 (define-key org-agenda-mode-map " " 'org-agenda-show)
7091 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
7092 (define-key org-agenda-mode-map "o" 'delete-other-windows)
7093 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
7094 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
7095 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
7096 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
7097 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
7098 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
7099 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
7100 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
7101 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
7102 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
7103 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
7105 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
7106 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
7107 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
7108 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
7109 (while l (define-key org-agenda-mode-map
7110 (int-to-string (pop l)) 'digit-argument)))
7112 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
7113 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
7114 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
7115 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
7116 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
7117 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
7118 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
7119 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
7120 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
7121 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
7122 (define-key org-agenda-mode-map "n" 'next-line)
7123 (define-key org-agenda-mode-map "p" 'previous-line)
7124 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
7125 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
7126 (define-key org-agenda-mode-map "," 'org-agenda-priority)
7127 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
7128 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
7129 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
7130 (eval-after-load "calendar"
7131 '(define-key calendar-mode-map org-calendar-to-agenda-key
7132 'org-calendar-goto-agenda))
7133 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
7134 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
7135 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
7136 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
7137 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
7138 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
7139 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
7140 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
7141 (define-key org-agenda-mode-map "O" 'org-clock-out)
7142 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
7143 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
7144 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
7145 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
7146 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
7147 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
7148 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
7149 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
7150 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
7151 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
7152 "Local keymap for agenda entries from Org-mode.")
7154 (define-key org-agenda-keymap
7155 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
7156 (define-key org-agenda-keymap
7157 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
7158 (when org-agenda-mouse-1-follows-link
7159 (define-key org-agenda-keymap [follow-link] 'mouse-face))
7160 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
7161 '("Agenda"
7162 ("Agenda Files")
7163 "--"
7164 ["Show" org-agenda-show t]
7165 ["Go To (other window)" org-agenda-goto t]
7166 ["Go To (this window)" org-agenda-switch-to t]
7167 ["Follow Mode" org-agenda-follow-mode
7168 :style toggle :selected org-agenda-follow-mode :active t]
7169 "--"
7170 ["Cycle TODO" org-agenda-todo t]
7171 ["Archive subtree" org-agenda-archive t]
7172 ["Delete subtree" org-agenda-kill t]
7173 "--"
7174 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
7175 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
7176 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
7177 "--"
7178 ("Tags"
7179 ["Show all Tags" org-agenda-show-tags t]
7180 ["Set Tags" org-agenda-set-tags t])
7181 ("Date/Schedule"
7182 ["Schedule" org-agenda-schedule t]
7183 ["Set Deadline" org-agenda-deadline t]
7184 "--"
7185 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
7186 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
7187 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
7188 ("Priority"
7189 ["Set Priority" org-agenda-priority t]
7190 ["Increase Priority" org-agenda-priority-up t]
7191 ["Decrease Priority" org-agenda-priority-down t]
7192 ["Show Priority" org-agenda-show-priority t])
7193 ("Calendar/Diary"
7194 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
7195 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
7196 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
7197 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
7198 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
7199 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
7200 "--"
7201 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
7202 "--"
7203 ("View"
7204 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
7205 :style radio :selected (equal org-agenda-ndays 1)]
7206 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
7207 :style radio :selected (equal org-agenda-ndays 7)]
7208 "--"
7209 ["Show Logbook entries" org-agenda-log-mode
7210 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
7211 ["Include Diary" org-agenda-toggle-diary
7212 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
7213 ["Use Time Grid" org-agenda-toggle-time-grid
7214 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
7215 ["Rebuild buffer" org-agenda-redo t]
7216 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
7217 "--"
7218 ; ["Undo Remote Editing" org-agenda-undo org-agenda-multi-buffer-undo-list]
7219 ; "--"
7220 ["Quit" org-agenda-quit t]
7221 ["Exit and Release Buffers" org-agenda-exit t]
7224 (defvar org-agenda-restrict nil)
7225 (defvar org-agenda-restrict-begin (make-marker))
7226 (defvar org-agenda-restrict-end (make-marker))
7227 (defvar org-agenda-last-dispatch-buffer nil)
7229 ;;;###autoload
7230 (defun org-agenda (arg)
7231 "Dispatch agenda commands to collect entries to the agenda buffer.
7232 Prompts for a character to select a command. Any prefix arg will be passed
7233 on to the selected command. The default selections are:
7235 a Call `org-agenda-list' to display the agenda for current day or week.
7236 t Call `org-todo-list' to display the global todo list.
7237 T Call `org-todo-list' to display the global todo list, select only
7238 entries with a specific TODO keyword (the user gets a prompt).
7239 m Call `org-tags-view' to display headlines with tags matching
7240 a condition (the user is prompted for the condition).
7241 M Like `m', but select only TODO entries, no ordinary headlines.
7242 l Create a timeeline for the current buffer.
7244 More commands can be added by configuring the variable
7245 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
7246 searches can be pre-defined in this way.
7248 If the current buffer is in Org-mode and visiting a file, you can also
7249 first press `1' to indicate that the agenda should be temporarily (until the
7250 next use of \\[org-agenda]) restricted to the current file."
7251 (interactive "P")
7252 (catch 'exit
7253 (let* ((buf (current-buffer))
7254 (bfn (buffer-file-name (buffer-base-buffer)))
7255 (restrict-ok (and bfn (org-mode-p)))
7256 (custom org-agenda-custom-commands)
7257 c entry key type match lprops)
7258 ;; Turn off restriction
7259 (put 'org-agenda-files 'org-restrict nil)
7260 (setq org-agenda-restrict nil)
7261 (move-marker org-agenda-restrict-begin nil)
7262 (move-marker org-agenda-restrict-end nil)
7263 ;; Remember where this call originated
7264 (setq org-agenda-last-dispatch-buffer (current-buffer))
7265 (save-window-excursion
7266 (delete-other-windows)
7267 (switch-to-buffer-other-window " *Agenda Commands*")
7268 (erase-buffer)
7269 (insert
7270 "Press key for an agenda command:
7271 --------------------------------
7272 a Agenda for current week or day
7273 t List of all TODO entries T Entries with special TODO kwd
7274 m Match a TAGS query M Like m, but only TODO entries
7275 L Timeline for current buffer C Configure custom agenda commands")
7276 (while (setq entry (pop custom))
7277 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
7278 (insert (format "\n%-4s%-14s: %s"
7280 (cond
7281 ((stringp type) type)
7282 ((eq type 'tags) "Tags query")
7283 ((eq type 'todo) "TODO keyword")
7284 ((eq type 'tags-tree) "Tags tree")
7285 ((eq type 'todo-tree) "TODO kwd tree")
7286 ((eq type 'occur-tree) "Occur tree")
7287 (t "???"))
7288 (if (stringp match)
7289 (org-add-props match nil 'face 'org-warning)
7290 (format "set of %d commands" (+ -2 (length entry)))))))
7291 (if restrict-ok
7292 (insert "\n"
7293 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
7295 (goto-char (point-min))
7296 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
7297 (message "Press key for agenda command%s"
7298 (if restrict-ok ", or [1] or [0] to restrict" ""))
7299 (setq c (read-char-exclusive))
7300 (message "")
7301 (when (memq c '(?L ?1 ?0))
7302 (if restrict-ok
7303 (put 'org-agenda-files 'org-restrict (list bfn))
7304 (error "Cannot restrict agenda to current buffer"))
7305 (with-current-buffer " *Agenda Commands*"
7306 (goto-char (point-max))
7307 (delete-region (point-at-bol) (point))
7308 (goto-char (point-min)))
7309 (when (eq c ?0)
7310 (setq org-agenda-restrict t)
7311 (with-current-buffer buf
7312 (if (org-region-active-p)
7313 (progn
7314 (move-marker org-agenda-restrict-begin (region-beginning))
7315 (move-marker org-agenda-restrict-end (region-end)))
7316 (save-excursion
7317 (org-back-to-heading t)
7318 (move-marker org-agenda-restrict-begin (point))
7319 (move-marker org-agenda-restrict-end
7320 (progn (org-end-of-subtree t)))))))
7321 (unless (eq c ?L)
7322 (message "Press key for agenda command%s"
7323 (if restrict-ok " (restricted to current file)" ""))
7324 (setq c (read-char-exclusive)))
7325 (message "")))
7326 (require 'calendar) ; FIXME: can we avoid this for some commands?
7327 ;; For example the todo list should not need it (but does...)
7328 (cond
7329 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
7330 ((equal c ?a) (call-interactively 'org-agenda-list))
7331 ((equal c ?t) (call-interactively 'org-todo-list))
7332 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
7333 ((equal c ?m) (call-interactively 'org-tags-view))
7334 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
7335 ((equal c ?L)
7336 (unless restrict-ok
7337 (error "This is not an Org-mode file"))
7338 (org-call-with-arg 'org-timeline arg))
7339 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
7340 (if (symbolp (nth 1 entry))
7341 (progn
7342 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
7343 lprops (nth 3 entry))
7344 (cond
7345 ((eq type 'tags)
7346 (org-let lprops '(org-tags-view current-prefix-arg match)))
7347 ((eq type 'tags-todo)
7348 (org-let lprops '(org-tags-view '(4) match)))
7349 ((eq type 'todo)
7350 (org-let lprops '(org-todo-list match)))
7351 ((eq type 'tags-tree)
7352 (org-check-for-org-mode)
7353 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
7354 ((eq type 'todo-tree)
7355 (org-check-for-org-mode)
7356 (org-let lprops
7357 '(org-occur (concat "^" outline-regexp "[ \t]*"
7358 (regexp-quote match) "\\>"))))
7359 ((eq type 'occur-tree)
7360 (org-check-for-org-mode)
7361 (org-let lprops '(org-occur match)))
7362 (t (error "Invalid custom agenda command type %s" type))))
7363 (org-run-agenda-series (cddr entry))))
7364 (t (error "Invalid key"))))))
7366 ;; FIXME: what is the meaning of WINDOW?????
7367 (defun org-run-agenda-series (series &optional window)
7368 (org-prepare-agenda)
7369 (let* ((org-agenda-multi t)
7370 (redo (list 'org-run-agenda-series (list 'quote series)))
7371 (org-select-agenda-window t)
7372 (cmds (car series))
7373 (gprops (nth 1 series))
7374 match ;; The byte compiler incorrectly complains about this. Keep it!
7375 cmd type lprops)
7376 (while (setq cmd (pop cmds))
7377 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
7378 (cond
7379 ((eq type 'agenda)
7380 (call-interactively 'org-agenda-list))
7381 ((eq type 'alltodo)
7382 (call-interactively 'org-todo-list))
7383 ((eq type 'tags)
7384 (org-let2 gprops lprops
7385 '(org-tags-view current-prefix-arg match)))
7386 ((eq type 'tags-todo)
7387 (org-let2 gprops lprops
7388 '(org-tags-view '(4) match)))
7389 ((eq type 'todo)
7390 (org-let2 gprops lprops
7391 '(org-todo-list match)))
7392 (t (error "Invalid type in command series"))))
7393 (widen)
7394 (setq org-agenda-redo-command redo)
7395 (goto-char (point-min)))
7396 (org-finalize-agenda))
7398 ;;;###autoload
7399 (defmacro org-batch-agenda (cmd-key &rest parameters)
7400 "Run an agenda command in batch mode, send result to STDOUT.
7401 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
7402 Paramters are alternating variable names and values that will be bound
7403 before running the agenda command."
7404 (let (pars)
7405 (while parameters
7406 (push (list (pop parameters) (if parameters (pop parameters))) pars))
7407 (flet ((read-char-exclusive () (string-to-char cmd-key)))
7408 (eval (list 'let (nreverse pars) '(org-agenda nil))))
7409 (set-buffer "*Org Agenda*")
7410 (princ (buffer-string))))
7412 (defmacro org-no-read-only (&rest body)
7413 "Inhibit read-only for BODY."
7414 `(let ((inhibit-read-only t)) ,@body))
7416 (defun org-check-for-org-mode ()
7417 "Make sure current buffer is in org-mode. Error if not."
7418 (or (org-mode-p)
7419 (error "Cannot execute org-mode agenda command on buffer in %s."
7420 major-mode)))
7422 (defun org-fit-agenda-window ()
7423 "Fit the window to the buffer size."
7424 (and org-fit-agenda-window
7425 (memq org-agenda-window-setup '(reorganize-frame))
7426 (fboundp 'fit-window-to-buffer)
7427 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
7428 (/ (frame-height) 2))))
7430 (defun org-agenda-files (&optional unrestricted)
7431 "Get the list of agenda files.
7432 Optional UNRESTRICTED means return the full list even if a restriction
7433 is currently in place."
7434 (cond
7435 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
7436 ((stringp org-agenda-files) (org-read-agenda-file-list))
7437 ((listp org-agenda-files) org-agenda-files)
7438 (t (error "Invalid value of `org-agenda-files'"))))
7440 (defvar org-window-configuration)
7442 (defun org-edit-agenda-file-list ()
7443 "Edit the list of agenda files.
7444 Depending on setup, this either uses customize to edit the variable
7445 `org-agenda-files', or it visits the file that is holding the list. In the
7446 latter case, the buffer is set up in a way that saving it automatically kills
7447 the buffer and restores the previous window configuration."
7448 (interactive)
7449 (if (stringp org-agenda-files)
7450 (let ((cw (current-window-configuration)))
7451 (find-file org-agenda-files)
7452 (org-set-local 'org-window-configuration cw)
7453 (org-add-hook 'after-save-hook
7454 (lambda ()
7455 (set-window-configuration
7456 (prog1 org-window-configuration
7457 (kill-buffer (current-buffer))))
7458 (org-install-agenda-files-menu)
7459 (message "New agenda file list installed"))
7460 nil 'local)
7461 (message (substitute-command-keys
7462 "Edit list and finish with \\[save-buffer]")))
7463 (customize-variable 'org-agenda-files)))
7465 (defun org-store-new-agenda-file-list (list)
7466 "Set new value for the agenda file list and save it correcly."
7467 (if (stringp org-agenda-files)
7468 (let ((f org-agenda-files) b)
7469 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
7470 (with-temp-file f
7471 (insert (mapconcat 'identity list "\n") "\n")))
7472 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
7473 (setq org-agenda-files list)
7474 (customize-save-variable 'org-agenda-files org-agenda-files))))
7476 (defun org-read-agenda-file-list ()
7477 "Read the list of agenda files from a file."
7478 (when (stringp org-agenda-files)
7479 (with-temp-buffer
7480 (insert-file-contents org-agenda-files)
7481 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
7483 (defvar org-agenda-markers nil
7484 "List of all currently active markers created by `org-agenda'.")
7485 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
7486 "Creation time of the last agenda marker.")
7488 (defun org-agenda-new-marker (&optional pos)
7489 "Return a new agenda marker.
7490 Org-mode keeps a list of these markers and resets them when they are
7491 no longer in use."
7492 (let ((m (copy-marker (or pos (point)))))
7493 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
7494 (push m org-agenda-markers)
7497 (defun org-agenda-maybe-reset-markers (&optional force)
7498 "Reset markers created by `org-agenda'. But only if they are old enough."
7499 (if (or (and force (not org-agenda-multi))
7500 (> (- (time-to-seconds (current-time))
7501 org-agenda-last-marker-time)
7503 (while org-agenda-markers
7504 (move-marker (pop org-agenda-markers) nil))))
7506 (defvar org-agenda-new-buffers nil
7507 "Buffers created to visit agenda files.")
7509 (defun org-get-agenda-file-buffer (file)
7510 "Get a buffer visiting FILE. If the buffer needs to be created, add
7511 it to the list of buffers which might be released later."
7512 (let ((buf (find-buffer-visiting file)))
7513 (if buf
7514 buf ; just return it
7515 ;; Make a new buffer and remember it
7516 (setq buf (find-file-noselect file))
7517 (if buf (push buf org-agenda-new-buffers))
7518 buf)))
7520 (defun org-release-buffers (blist)
7521 "Release all buffers in list, asking the user for confirmation when needed.
7522 When a buffer is unmodified, it is just killed. When modified, it is saved
7523 \(if the user agrees) and then killed."
7524 (let (buf file)
7525 (while (setq buf (pop blist))
7526 (setq file (buffer-file-name buf))
7527 (when (and (buffer-modified-p buf)
7528 file
7529 (y-or-n-p (format "Save file %s? " file)))
7530 (with-current-buffer buf (save-buffer)))
7531 (kill-buffer buf))))
7533 (defun org-timeline (&optional include-all)
7534 "Show a time-sorted view of the entries in the current org file.
7535 Only entries with a time stamp of today or later will be listed. With
7536 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
7537 under the current date.
7538 If the buffer contains an active region, only check the region for
7539 dates."
7540 (interactive "P")
7541 (require 'calendar)
7542 (org-compile-prefix-format 'timeline)
7543 (org-set-sorting-strategy 'timeline)
7544 (let* ((dopast t)
7545 (dotodo include-all)
7546 (doclosed org-agenda-show-log)
7547 (entry buffer-file-name)
7548 (date (calendar-current-date))
7549 (win (selected-window))
7550 (pos1 (point))
7551 (beg (if (org-region-active-p) (region-beginning) (point-min)))
7552 (end (if (org-region-active-p) (region-end) (point-max)))
7553 (day-numbers (org-get-all-dates beg end 'no-ranges
7554 t doclosed ; always include today
7555 org-timeline-show-empty-dates))
7556 (today (time-to-days (current-time)))
7557 (past t)
7558 args
7559 s e rtn d emptyp)
7560 (setq org-agenda-redo-command
7561 (list 'progn
7562 (list 'switch-to-buffer-other-window (current-buffer))
7563 (list 'org-timeline (list 'quote include-all))))
7564 (if (not dopast)
7565 ;; Remove past dates from the list of dates.
7566 (setq day-numbers (delq nil (mapcar (lambda(x)
7567 (if (>= x today) x nil))
7568 day-numbers))))
7569 (org-prepare-agenda)
7570 (if doclosed (push :closed args))
7571 (push :timestamp args)
7572 (if dotodo (push :todo args))
7573 (while (setq d (pop day-numbers))
7574 (if (and (listp d) (eq (car d) :omitted))
7575 (progn
7576 (setq s (point))
7577 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
7578 (put-text-property s (1- (point)) 'face 'org-level-3))
7579 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
7580 (if (and (>= d today)
7581 dopast
7582 past)
7583 (progn
7584 (setq past nil)
7585 (insert (make-string 79 ?-) "\n")))
7586 (setq date (calendar-gregorian-from-absolute d))
7587 (setq s (point))
7588 (setq rtn (and (not emptyp)
7589 (apply 'org-agenda-get-day-entries
7590 entry date args)))
7591 (if (or rtn (equal d today) org-timeline-show-empty-dates)
7592 (progn
7593 (insert (calendar-day-name date) " "
7594 (number-to-string (extract-calendar-day date)) " "
7595 (calendar-month-name (extract-calendar-month date)) " "
7596 (number-to-string (extract-calendar-year date)) "\n")
7597 (put-text-property s (1- (point)) 'face
7598 'org-level-3)
7599 (if (equal d today)
7600 (put-text-property s (1- (point)) 'org-today t))
7601 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
7602 (put-text-property s (1- (point)) 'day d)))))
7603 (goto-char (point-min))
7604 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7605 (point-min)))
7606 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
7607 (org-finalize-agenda)
7608 (setq buffer-read-only t)
7609 (when (not org-select-agenda-window)
7610 (select-window win)
7611 (goto-char pos1))))
7613 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
7614 (defvar org-agenda-last-arguments nil
7615 "The arguments of the previous call to org-agenda")
7617 ;;;###autoload
7618 (defun org-agenda-list (&optional include-all start-day ndays)
7619 "Produce a weekly view from all files in variable `org-agenda-files'.
7620 The view will be for the current week, but from the overview buffer you
7621 will be able to go to other weeks.
7622 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
7623 also be shown, under the current date.
7624 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
7625 on the days are also shown. See the variable `org-log-done' for how
7626 to turn on logging.
7627 START-DAY defaults to TODAY, or to the most recent match for the weekday
7628 given in `org-agenda-start-on-weekday'.
7629 NDAYS defaults to `org-agenda-ndays'."
7630 (interactive "P")
7631 (if org-agenda-overriding-arguments
7632 (setq include-all (car org-agenda-overriding-arguments)
7633 start-day (nth 1 org-agenda-overriding-arguments)
7634 ndays (nth 2 org-agenda-overriding-arguments)))
7635 (setq org-agenda-last-arguments (list include-all start-day ndays))
7636 (org-compile-prefix-format 'agenda)
7637 (org-set-sorting-strategy 'agenda)
7638 (require 'calendar)
7639 (let* ((org-agenda-start-on-weekday
7640 (if (or (equal ndays 1)
7641 (and (null ndays) (equal 1 org-agenda-ndays)))
7642 nil org-agenda-start-on-weekday))
7643 (thefiles (org-agenda-files))
7644 (files thefiles)
7645 (win (selected-window))
7646 (today (time-to-days (current-time)))
7647 (sd (or start-day today))
7648 (start (if (or (null org-agenda-start-on-weekday)
7649 (< org-agenda-ndays 7))
7651 (let* ((nt (calendar-day-of-week
7652 (calendar-gregorian-from-absolute sd)))
7653 (n1 org-agenda-start-on-weekday)
7654 (d (- nt n1)))
7655 (- sd (+ (if (< d 0) 7 0) d)))))
7656 (day-numbers (list start))
7657 (inhibit-redisplay t)
7658 s e rtn rtnall file date d start-pos end-pos todayp nd)
7659 (setq org-agenda-redo-command
7660 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
7661 ;; Make the list of days
7662 (setq ndays (or ndays org-agenda-ndays)
7663 nd ndays)
7664 (while (> ndays 1)
7665 (push (1+ (car day-numbers)) day-numbers)
7666 (setq ndays (1- ndays)))
7667 (setq day-numbers (nreverse day-numbers))
7668 (org-prepare-agenda)
7669 (org-set-local 'starting-day (car day-numbers))
7670 (org-set-local 'include-all-loc include-all)
7671 (when (and (or include-all org-agenda-include-all-todo)
7672 (member today day-numbers))
7673 (setq files thefiles
7674 rtnall nil)
7675 (while (setq file (pop files))
7676 (catch 'nextfile
7677 (org-check-agenda-file file)
7678 (setq date (calendar-gregorian-from-absolute today)
7679 rtn (org-agenda-get-day-entries
7680 file date :todo))
7681 (setq rtnall (append rtnall rtn))))
7682 (when rtnall
7683 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
7684 (add-text-properties (point-min) (1- (point))
7685 (list 'face 'org-level-3))
7686 (insert (org-finalize-agenda-entries rtnall) "\n")))
7687 (setq s (point))
7688 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
7689 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
7690 (while (setq d (pop day-numbers))
7691 (setq date (calendar-gregorian-from-absolute d)
7692 s (point))
7693 (if (or (setq todayp (= d today))
7694 (and (not start-pos) (= d sd)))
7695 (setq start-pos (point))
7696 (if (and start-pos (not end-pos))
7697 (setq end-pos (point))))
7698 (setq files thefiles
7699 rtnall nil)
7700 (while (setq file (pop files))
7701 (catch 'nextfile
7702 (org-check-agenda-file file)
7703 (if org-agenda-show-log
7704 (setq rtn (org-agenda-get-day-entries
7705 file date
7706 :deadline :scheduled :timestamp :closed))
7707 (setq rtn (org-agenda-get-day-entries
7708 file date
7709 :deadline :scheduled :timestamp)))
7710 (setq rtnall (append rtnall rtn))))
7711 (if org-agenda-include-diary
7712 (progn
7713 (require 'diary-lib)
7714 (setq rtn (org-get-entries-from-diary date))
7715 (setq rtnall (append rtnall rtn))))
7716 (if (or rtnall org-agenda-show-all-dates)
7717 (progn
7718 (insert (format "%-9s %2d %s %4d\n"
7719 (calendar-day-name date)
7720 (extract-calendar-day date)
7721 (calendar-month-name (extract-calendar-month date))
7722 (extract-calendar-year date)))
7723 (put-text-property s (1- (point)) 'face
7724 'org-level-3)
7725 (if todayp (put-text-property s (1- (point)) 'org-today t))
7727 (if rtnall (insert
7728 (org-finalize-agenda-entries
7729 (org-agenda-add-time-grid-maybe
7730 rtnall nd todayp))
7731 "\n"))
7732 (put-text-property s (1- (point)) 'day d))))
7733 (goto-char (point-min))
7734 (org-fit-agenda-window)
7735 (unless (and (pos-visible-in-window-p (point-min))
7736 (pos-visible-in-window-p (point-max)))
7737 (goto-char (1- (point-max)))
7738 (recenter -1)
7739 (if (not (pos-visible-in-window-p (or start-pos 1)))
7740 (progn
7741 (goto-char (or start-pos 1))
7742 (recenter 1))))
7743 (goto-char (or start-pos 1))
7744 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
7745 (org-finalize-agenda)
7746 (setq buffer-read-only t)
7747 (if (not org-select-agenda-window) (select-window win))
7748 (message "")))
7750 (defvar org-select-this-todo-keyword nil)
7752 ;;;###autoload
7753 (defun org-todo-list (arg)
7754 "Show all TODO entries from all agenda file in a single list.
7755 The prefix arg can be used to select a specific TODO keyword and limit
7756 the list to these. When using \\[universal-argument], you will be prompted
7757 for a keyword. A numeric prefix directly selects the Nth keyword in
7758 `org-todo-keywords'."
7759 (interactive "P")
7760 (require 'calendar)
7761 (org-compile-prefix-format 'todo)
7762 (org-set-sorting-strategy 'todo)
7763 (let* ((today (time-to-days (current-time)))
7764 (date (calendar-gregorian-from-absolute today))
7765 (win (selected-window))
7766 (kwds org-todo-keywords)
7767 (completion-ignore-case t)
7768 (org-select-this-todo-keyword
7769 (if (stringp arg) arg
7770 (and arg (integerp arg) (> arg 0)
7771 (nth (1- arg) org-todo-keywords))))
7772 rtn rtnall files file pos)
7773 (when (equal arg '(4))
7774 (setq org-select-this-todo-keyword
7775 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
7776 nil t)))
7777 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
7778 (org-prepare-agenda)
7779 (org-set-local 'last-arg arg)
7780 (org-set-local 'org-todo-keywords kwds)
7781 (setq org-agenda-redo-command
7782 '(org-todo-list (or current-prefix-arg last-arg)))
7783 (setq files (org-agenda-files)
7784 rtnall nil)
7785 (while (setq file (pop files))
7786 (catch 'nextfile
7787 (org-check-agenda-file file)
7788 (setq rtn (org-agenda-get-day-entries file date :todo))
7789 (setq rtnall (append rtnall rtn))))
7790 (insert "Global list of TODO items of type: ")
7791 (add-text-properties (point-min) (1- (point))
7792 (list 'face 'org-level-3))
7793 (setq pos (point))
7794 (insert (or org-select-this-todo-keyword "ALL") "\n")
7795 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7796 (setq pos (point))
7797 (unless org-agenda-multi
7798 (insert
7799 "Available with `N r': (0)ALL "
7800 (let ((n 0))
7801 (mapconcat (lambda (x)
7802 (format "(%d)%s" (setq n (1+ n)) x))
7803 org-todo-keywords " "))
7804 "\n"))
7805 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7806 (when rtnall
7807 (insert (org-finalize-agenda-entries rtnall) "\n"))
7808 (goto-char (point-min))
7809 (org-fit-agenda-window)
7810 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
7811 (org-finalize-agenda)
7812 (setq buffer-read-only t)
7813 (if (not org-select-agenda-window) (select-window win))))
7815 (defun org-check-agenda-file (file)
7816 "Make sure FILE exists. If not, ask user what to do."
7817 (when (not (file-exists-p file))
7818 (message "non-existent file %s. [R]emove from list or [A]bort?"
7819 (abbreviate-file-name file))
7820 (let ((r (downcase (read-char-exclusive))))
7821 (cond
7822 ((equal r ?r)
7823 (org-remove-file file)
7824 (throw 'nextfile t))
7825 (t (error "Abort"))))))
7827 (defun org-agenda-check-type (error &rest types)
7828 "Check if agenda buffer is of allowed type.
7829 If ERROR is non-nil, throw an error, otherwise just return nil."
7830 (if (memq org-agenda-type types)
7832 (if error
7833 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
7834 nil)))
7836 (defun org-agenda-quit ()
7837 "Exit agenda by removing the window or the buffer."
7838 (interactive)
7839 (let ((buf (current-buffer)))
7840 (if (not (one-window-p)) (delete-window))
7841 (kill-buffer buf)
7842 (org-agenda-maybe-reset-markers 'force))
7843 ;; Maybe restore the pre-agenda window configuration.
7844 (and org-agenda-restore-windows-after-quit
7845 (not (eq org-agenda-window-setup 'other-frame))
7846 org-pre-agenda-window-conf
7847 (set-window-configuration org-pre-agenda-window-conf)))
7849 (defun org-agenda-exit ()
7850 "Exit agenda by removing the window or the buffer.
7851 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
7852 Org-mode buffers visited directly by the user will not be touched."
7853 (interactive)
7854 (org-release-buffers org-agenda-new-buffers)
7855 (setq org-agenda-new-buffers nil)
7856 (org-agenda-quit))
7858 (defun org-save-all-org-buffers ()
7859 "Save all Org-mode buffers without user confirmation."
7860 (interactive)
7861 (message "Saving all Org-mode buffers...")
7862 (save-some-buffers t 'org-mode-p)
7863 (message "Saving all Org-mode buffers... done"))
7865 (defun org-agenda-redo ()
7866 "Rebuild Agenda.
7867 When this is the global TODO list, a prefix argument will be interpreted."
7868 (interactive)
7869 (let* ((org-agenda-keep-modes t)
7870 (line (org-current-line))
7871 (window-line (- line (org-current-line (window-start)))))
7872 (message "Rebuilding agenda buffer...")
7873 (eval org-agenda-redo-command)
7874 (message "Rebuilding agenda buffer...done")
7875 (goto-line line)
7876 (recenter window-line)))
7878 (defun org-agenda-goto-today ()
7879 "Go to today."
7880 (interactive)
7881 (org-agenda-check-type t 'timeline 'agenda)
7882 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
7883 (cond
7884 (tdpos (goto-char tdpos))
7885 ((eq org-agenda-type 'agenda)
7886 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
7887 (setf (nth 1 org-agenda-overriding-arguments) nil)
7888 (org-agenda-redo)
7889 (org-agenda-find-today-or-agenda)))
7890 (t (error "Cannot find today")))))
7892 (defun org-agenda-find-today-or-agenda ()
7893 (goto-char
7894 (or (text-property-any (point-min) (point-max) 'org-today t)
7895 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
7896 (point-min))))
7898 (defun org-agenda-later (arg)
7899 "Go forward in time by `org-agenda-ndays' days.
7900 With prefix ARG, go forward that many times `org-agenda-ndays'."
7901 (interactive "p")
7902 (org-agenda-check-type t 'agenda)
7903 (let ((org-agenda-overriding-arguments
7904 (list (car org-agenda-last-arguments)
7905 (+ starting-day (* arg org-agenda-ndays))
7906 nil t)))
7907 (org-agenda-redo)
7908 (org-agenda-find-today-or-agenda)))
7910 (defun org-agenda-earlier (arg)
7911 "Go back in time by `org-agenda-ndays' days.
7912 With prefix ARG, go back that many times `org-agenda-ndays'."
7913 (interactive "p")
7914 (org-agenda-check-type t 'agenda)
7915 (let ((org-agenda-overriding-arguments
7916 (list (car org-agenda-last-arguments)
7917 (- starting-day (* arg org-agenda-ndays))
7918 nil t)))
7919 (org-agenda-redo)
7920 (org-agenda-find-today-or-agenda)))
7922 (defun org-agenda-week-view ()
7923 "Switch to weekly view for agenda."
7924 (interactive)
7925 (org-agenda-check-type t 'agenda)
7926 (if (= org-agenda-ndays 7)
7927 (error "This is already the week view"))
7928 (setq org-agenda-ndays 7)
7929 (let ((org-agenda-overriding-arguments
7930 (list (car org-agenda-last-arguments)
7931 (or (get-text-property (point) 'day)
7932 starting-day)
7933 nil t)))
7934 (org-agenda-redo)
7935 (org-agenda-find-today-or-agenda))
7936 (org-agenda-set-mode-name)
7937 (message "Switched to week view"))
7939 (defun org-agenda-day-view ()
7940 "Switch to daily view for agenda."
7941 (interactive)
7942 (org-agenda-check-type t 'agenda)
7943 (if (= org-agenda-ndays 1)
7944 (error "This is already the day view"))
7945 (setq org-agenda-ndays 1)
7946 (let ((org-agenda-overriding-arguments
7947 (list (car org-agenda-last-arguments)
7948 (or (get-text-property (point) 'day)
7949 starting-day)
7950 nil t)))
7951 (org-agenda-redo)
7952 (org-agenda-find-today-or-agenda))
7953 (org-agenda-set-mode-name)
7954 (message "Switched to day view"))
7956 (defun org-agenda-next-date-line (&optional arg)
7957 "Jump to the next line indicating a date in agenda buffer."
7958 (interactive "p")
7959 (org-agenda-check-type t 'agenda 'timeline)
7960 (beginning-of-line 1)
7961 (if (looking-at "^\\S-") (forward-char 1))
7962 (if (not (re-search-forward "^\\S-" nil t arg))
7963 (progn
7964 (backward-char 1)
7965 (error "No next date after this line in this buffer")))
7966 (goto-char (match-beginning 0)))
7968 (defun org-agenda-previous-date-line (&optional arg)
7969 "Jump to the previous line indicating a date in agenda buffer."
7970 (interactive "p")
7971 (org-agenda-check-type t 'agenda 'timeline)
7972 (beginning-of-line 1)
7973 (if (not (re-search-backward "^\\S-" nil t arg))
7974 (error "No previous date before this line in this buffer")))
7976 ;; Initialize the highlight
7977 (defvar org-hl (org-make-overlay 1 1))
7978 (org-overlay-put org-hl 'face 'highlight)
7980 (defun org-highlight (begin end &optional buffer)
7981 "Highlight a region with overlay."
7982 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7983 org-hl begin end (or buffer (current-buffer))))
7985 (defun org-unhighlight ()
7986 "Detach overlay INDEX."
7987 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7990 (defun org-agenda-follow-mode ()
7991 "Toggle follow mode in an agenda buffer."
7992 (interactive)
7993 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7994 (org-agenda-set-mode-name)
7995 (message "Follow mode is %s"
7996 (if org-agenda-follow-mode "on" "off")))
7998 (defun org-agenda-log-mode ()
7999 "Toggle log mode in an agenda buffer."
8000 (interactive)
8001 (org-agenda-check-type t 'agenda 'timeline)
8002 (setq org-agenda-show-log (not org-agenda-show-log))
8003 (org-agenda-set-mode-name)
8004 (org-agenda-redo)
8005 (message "Log mode is %s"
8006 (if org-agenda-show-log "on" "off")))
8008 (defun org-agenda-toggle-diary ()
8009 "Toggle diary inclusion in an agenda buffer."
8010 (interactive)
8011 (org-agenda-check-type t 'agenda)
8012 (setq org-agenda-include-diary (not org-agenda-include-diary))
8013 (org-agenda-redo)
8014 (org-agenda-set-mode-name)
8015 (message "Diary inclusion turned %s"
8016 (if org-agenda-include-diary "on" "off")))
8018 (defun org-agenda-toggle-time-grid ()
8019 "Toggle time grid in an agenda buffer."
8020 (interactive)
8021 (org-agenda-check-type t 'agenda)
8022 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
8023 (org-agenda-redo)
8024 (org-agenda-set-mode-name)
8025 (message "Time-grid turned %s"
8026 (if org-agenda-use-time-grid "on" "off")))
8028 (defun org-agenda-set-mode-name ()
8029 "Set the mode name to indicate all the small mode settings."
8030 (setq mode-name
8031 (concat "Org-Agenda"
8032 (if (equal org-agenda-ndays 1) " Day" "")
8033 (if (equal org-agenda-ndays 7) " Week" "")
8034 (if org-agenda-follow-mode " Follow" "")
8035 (if org-agenda-include-diary " Diary" "")
8036 (if org-agenda-use-time-grid " Grid" "")
8037 (if org-agenda-show-log " Log" "")))
8038 (force-mode-line-update))
8040 (defun org-agenda-post-command-hook ()
8041 (and (eolp) (not (bolp)) (backward-char 1))
8042 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
8043 (if (and org-agenda-follow-mode
8044 (get-text-property (point) 'org-marker))
8045 (org-agenda-show)))
8047 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
8049 (defun org-get-entries-from-diary (date)
8050 "Get the (Emacs Calendar) diary entries for DATE."
8051 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
8052 (diary-display-hook '(fancy-diary-display))
8053 (list-diary-entries-hook
8054 (cons 'org-diary-default-entry list-diary-entries-hook))
8055 (diary-file-name-prefix-function nil) ; turn this feature off
8056 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
8057 entries
8058 (org-disable-agenda-to-diary t))
8059 (save-excursion
8060 (save-window-excursion
8061 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
8062 (if (not (get-buffer fancy-diary-buffer))
8063 (setq entries nil)
8064 (with-current-buffer fancy-diary-buffer
8065 (setq buffer-read-only nil)
8066 (if (= (point-max) 1)
8067 ;; No entries
8068 (setq entries nil)
8069 ;; Omit the date and other unnecessary stuff
8070 (org-agenda-cleanup-fancy-diary)
8071 ;; Add prefix to each line and extend the text properties
8072 (if (= (point-max) 1)
8073 (setq entries nil)
8074 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
8075 (set-buffer-modified-p nil)
8076 (kill-buffer fancy-diary-buffer)))
8077 (when entries
8078 (setq entries (org-split-string entries "\n"))
8079 (setq entries
8080 (mapcar
8081 (lambda (x)
8082 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
8083 ;; Extend the text properties to the beginning of the line
8084 (org-add-props x (text-properties-at (1- (length x)) x)))
8085 entries)))))
8087 (defun org-agenda-cleanup-fancy-diary ()
8088 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
8089 This gets rid of the date, the underline under the date, and
8090 the dummy entry installed by `org-mode' to ensure non-empty diary for each
8091 date. It also removes lines that contain only whitespace."
8092 (goto-char (point-min))
8093 (if (looking-at ".*?:[ \t]*")
8094 (progn
8095 (replace-match "")
8096 (re-search-forward "\n=+$" nil t)
8097 (replace-match "")
8098 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
8099 (re-search-forward "\n=+$" nil t)
8100 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
8101 (goto-char (point-min))
8102 (while (re-search-forward "^ +\n" nil t)
8103 (replace-match ""))
8104 (goto-char (point-min))
8105 (if (re-search-forward "^Org-mode dummy\n?" nil t)
8106 (replace-match "")))
8108 ;; Make sure entries from the diary have the right text properties.
8109 (eval-after-load "diary-lib"
8110 '(if (boundp 'diary-modify-entry-list-string-function)
8111 ;; We can rely on the hook, nothing to do
8113 ;; Hook not avaiable, must use advice to make this work
8114 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
8115 "Make the position visible."
8116 (if (and org-disable-agenda-to-diary ;; called from org-agenda
8117 (stringp string)
8118 buffer-file-name)
8119 (setq string (org-modify-diary-entry-string string))))))
8121 (defun org-modify-diary-entry-string (string)
8122 "Add text properties to string, allowing org-mode to act on it."
8123 (org-add-props string nil
8124 'mouse-face 'highlight
8125 'keymap org-agenda-keymap
8126 'help-echo (format "mouse-2 or RET jump to diary file %s"
8127 (abbreviate-file-name buffer-file-name))
8128 'org-agenda-diary-link t
8129 'org-marker (org-agenda-new-marker (point-at-bol))))
8131 (defun org-diary-default-entry ()
8132 "Add a dummy entry to the diary.
8133 Needed to avoid empty dates which mess up holiday display."
8134 ;; Catch the error if dealing with the new add-to-diary-alist
8135 (when org-disable-agenda-to-diary
8136 (condition-case nil
8137 (add-to-diary-list original-date "Org-mode dummy" "")
8138 (error
8139 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
8141 ;;;###autoload
8142 (defun org-cycle-agenda-files ()
8143 "Cycle through the files in `org-agenda-files'.
8144 If the current buffer visits an agenda file, find the next one in the list.
8145 If the current buffer does not, find the first agenda file."
8146 (interactive)
8147 (let* ((fs (org-agenda-files t))
8148 (files (append fs (list (car fs))))
8149 (tcf (if buffer-file-name (file-truename buffer-file-name)))
8150 file)
8151 (unless files (error "No agenda files"))
8152 (catch 'exit
8153 (while (setq file (pop files))
8154 (if (equal (file-truename file) tcf)
8155 (when (car files)
8156 (find-file (car files))
8157 (throw 'exit t))))
8158 (find-file (car fs)))))
8160 (defun org-agenda-file-to-end ()
8161 "Move/add the current file to the end of the agenda file list.
8162 If the file is not present in the list, it is appended to the list. If it is
8163 present, it is moved there."
8164 (interactive)
8165 (org-agenda-file-to-front 'to-end))
8167 (defun org-agenda-file-to-front (&optional to-end)
8168 "Move/add the current file to the top of the agenda file list.
8169 If the file is not present in the list, it is added to the front. If it is
8170 present, it is moved there. With optional argument TO-END, add/move to the
8171 end of the list."
8172 (interactive "P")
8173 (let ((file-alist (mapcar (lambda (x)
8174 (cons (file-truename x) x))
8175 (org-agenda-files t)))
8176 (ctf (file-truename buffer-file-name))
8177 x had)
8178 (setq x (assoc ctf file-alist) had x)
8180 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
8181 (if to-end
8182 (setq file-alist (append (delq x file-alist) (list x)))
8183 (setq file-alist (cons x (delq x file-alist))))
8184 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
8185 (org-install-agenda-files-menu)
8186 (message "File %s to %s of agenda file list"
8187 (if had "moved" "added") (if to-end "end" "front"))))
8189 (defun org-remove-file (&optional file)
8190 "Remove current file from the list of files in variable `org-agenda-files'.
8191 These are the files which are being checked for agenda entries.
8192 Optional argument FILE means, use this file instead of the current."
8193 (interactive)
8194 (let* ((file (or file buffer-file-name))
8195 (true-file (file-truename file))
8196 (afile (abbreviate-file-name file))
8197 (files (delq nil (mapcar
8198 (lambda (x)
8199 (if (equal true-file
8200 (file-truename x))
8201 nil x))
8202 (org-agenda-files t)))))
8203 (if (not (= (length files) (length (org-agenda-files t))))
8204 (progn
8205 (org-store-new-agenda-file-list files)
8206 (org-install-agenda-files-menu)
8207 (message "Removed file: %s" afile))
8208 (message "File was not in list: %s" afile))))
8210 (defun org-file-menu-entry (file)
8211 (vector file (list 'find-file file) t))
8213 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
8214 "Return a list of all relevant day numbers from BEG to END buffer positions.
8215 If NO-RANGES is non-nil, include only the start and end dates of a range,
8216 not every single day in the range. If FORCE-TODAY is non-nil, make
8217 sure that TODAY is included in the list. If INACTIVE is non-nil, also
8218 inactive time stamps (those in square brackets) are included.
8219 When EMPTY is non-nil, also include days without any entries."
8220 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
8221 dates dates1 date day day1 day2 ts1 ts2)
8222 (if force-today
8223 (setq dates (list (time-to-days (current-time)))))
8224 (save-excursion
8225 (goto-char beg)
8226 (while (re-search-forward re end t)
8227 (setq day (time-to-days (org-time-string-to-time
8228 (substring (match-string 1) 0 10))))
8229 (or (memq day dates) (push day dates)))
8230 (unless no-ranges
8231 (goto-char beg)
8232 (while (re-search-forward org-tr-regexp end t)
8233 (setq ts1 (substring (match-string 1) 0 10)
8234 ts2 (substring (match-string 2) 0 10)
8235 day1 (time-to-days (org-time-string-to-time ts1))
8236 day2 (time-to-days (org-time-string-to-time ts2)))
8237 (while (< (setq day1 (1+ day1)) day2)
8238 (or (memq day1 dates) (push day1 dates)))))
8239 (setq dates (sort dates '<))
8240 (when empty
8241 (while (setq day (pop dates))
8242 (setq day2 (car dates))
8243 (push day dates1)
8244 (when (and day2 empty)
8245 (if (or (eq empty t)
8246 (and (numberp empty) (<= (- day2 day) empty)))
8247 (while (< (setq day (1+ day)) day2)
8248 (push (list day) dates1))
8249 (push (cons :omitted (- day2 day)) dates1))))
8250 (setq dates (nreverse dates1)))
8251 dates)))
8253 ;;;###autoload
8254 (defun org-diary (&rest args)
8255 "Return diary information from org-files.
8256 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
8257 It accesses org files and extracts information from those files to be
8258 listed in the diary. The function accepts arguments specifying what
8259 items should be listed. The following arguments are allowed:
8261 :timestamp List the headlines of items containing a date stamp or
8262 date range matching the selected date. Deadlines will
8263 also be listed, on the expiration day.
8265 :deadline List any deadlines past due, or due within
8266 `org-deadline-warning-days'. The listing occurs only
8267 in the diary for *today*, not at any other date. If
8268 an entry is marked DONE, it is no longer listed.
8270 :scheduled List all items which are scheduled for the given date.
8271 The diary for *today* also contains items which were
8272 scheduled earlier and are not yet marked DONE.
8274 :todo List all TODO items from the org-file. This may be a
8275 long list - so this is not turned on by default.
8276 Like deadlines, these entries only show up in the
8277 diary for *today*, not at any other date.
8279 The call in the diary file should look like this:
8281 &%%(org-diary) ~/path/to/some/orgfile.org
8283 Use a separate line for each org file to check. Or, if you omit the file name,
8284 all files listed in `org-agenda-files' will be checked automatically:
8286 &%%(org-diary)
8288 If you don't give any arguments (as in the example above), the default
8289 arguments (:deadline :scheduled :timestamp) are used. So the example above may
8290 also be written as
8292 &%%(org-diary :deadline :timestamp :scheduled)
8294 The function expects the lisp variables `entry' and `date' to be provided
8295 by the caller, because this is how the calendar works. Don't use this
8296 function from a program - use `org-agenda-get-day-entries' instead."
8297 (org-agenda-maybe-reset-markers)
8298 (org-compile-prefix-format 'agenda)
8299 (org-set-sorting-strategy 'agenda)
8300 (setq args (or args '(:deadline :scheduled :timestamp)))
8301 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
8302 (list entry)
8303 (org-agenda-files t)))
8304 file rtn results)
8305 ;; If this is called during org-agenda, don't return any entries to
8306 ;; the calendar. Org Agenda will list these entries itself.
8307 (if org-disable-agenda-to-diary (setq files nil))
8308 (while (setq file (pop files))
8309 (setq rtn (apply 'org-agenda-get-day-entries file date args))
8310 (setq results (append results rtn)))
8311 (if results
8312 (concat (org-finalize-agenda-entries results) "\n"))))
8313 (defvar org-category-table nil)
8314 (defun org-get-category-table ()
8315 "Get the table of categories and positions in current buffer."
8316 (let (tbl)
8317 (save-excursion
8318 (goto-char (point-min))
8319 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
8320 (push (cons (point) (org-trim (match-string 2))) tbl)))
8321 tbl))
8322 (defun org-get-category (&optional pos)
8323 "Get the category applying to position POS."
8324 (if (not org-category-table)
8325 (cond
8326 ((null org-category)
8327 (setq org-category
8328 (if buffer-file-name
8329 (file-name-sans-extension
8330 (file-name-nondirectory buffer-file-name))
8331 "???")))
8332 ((symbolp org-category) (symbol-name org-category))
8333 (t org-category))
8334 (let ((tbl org-category-table)
8335 (pos (or pos (point))))
8336 (while (and tbl (> (caar tbl) pos))
8337 (pop tbl))
8338 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
8339 org-category-table))))))
8341 (defun org-agenda-get-day-entries (file date &rest args)
8342 "Does the work for `org-diary' and `org-agenda'.
8343 FILE is the path to a file to be checked for entries. DATE is date like
8344 the one returned by `calendar-current-date'. ARGS are symbols indicating
8345 which kind of entries should be extracted. For details about these, see
8346 the documentation of `org-diary'."
8347 (setq args (or args '(:deadline :scheduled :timestamp)))
8348 (let* ((org-startup-with-deadline-check nil)
8349 (org-startup-folded nil)
8350 (org-startup-align-all-tables nil)
8351 (buffer (if (file-exists-p file)
8352 (org-get-agenda-file-buffer file)
8353 (error "No such file %s" file)))
8354 arg results rtn)
8355 (if (not buffer)
8356 ;; If file does not exist, make sure an error message ends up in diary
8357 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8358 (with-current-buffer buffer
8359 (unless (org-mode-p)
8360 (error "Agenda file %s is not in `org-mode'" file))
8361 (setq org-category-table (org-get-category-table))
8362 (let ((case-fold-search nil))
8363 (save-excursion
8364 (save-restriction
8365 (if org-agenda-restrict
8366 (narrow-to-region org-agenda-restrict-begin
8367 org-agenda-restrict-end)
8368 (widen))
8369 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
8370 (while (setq arg (pop args))
8371 (cond
8372 ((and (eq arg :todo)
8373 (equal date (calendar-current-date)))
8374 (setq rtn (org-agenda-get-todos))
8375 (setq results (append results rtn)))
8376 ((eq arg :timestamp)
8377 (setq rtn (org-agenda-get-blocks))
8378 (setq results (append results rtn))
8379 (setq rtn (org-agenda-get-timestamps))
8380 (setq results (append results rtn)))
8381 ((eq arg :scheduled)
8382 (setq rtn (org-agenda-get-scheduled))
8383 (setq results (append results rtn)))
8384 ((eq arg :closed)
8385 (setq rtn (org-agenda-get-closed))
8386 (setq results (append results rtn)))
8387 ((and (eq arg :deadline)
8388 (equal date (calendar-current-date)))
8389 (setq rtn (org-agenda-get-deadlines))
8390 (setq results (append results rtn))))))))
8391 results))))
8393 (defun org-entry-is-done-p ()
8394 "Is the current entry marked DONE?"
8395 (save-excursion
8396 (and (re-search-backward "[\r\n]\\*" nil t)
8397 (looking-at org-nl-done-regexp))))
8399 (defun org-at-date-range-p (&optional inactive-ok)
8400 "Is the cursor inside a date range?"
8401 (interactive)
8402 (save-excursion
8403 (catch 'exit
8404 (let ((pos (point)))
8405 (skip-chars-backward "^[<\r\n")
8406 (skip-chars-backward "<[")
8407 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8408 (>= (match-end 0) pos)
8409 (throw 'exit t))
8410 (skip-chars-backward "^<[\r\n")
8411 (skip-chars-backward "<[")
8412 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8413 (>= (match-end 0) pos)
8414 (throw 'exit t)))
8415 nil)))
8417 (defun org-agenda-get-todos ()
8418 "Return the TODO information for agenda display."
8419 (let* ((props (list 'face nil
8420 'done-face 'org-done
8421 'org-not-done-regexp org-not-done-regexp
8422 'mouse-face 'highlight
8423 'keymap org-agenda-keymap
8424 'help-echo
8425 (format "mouse-2 or RET jump to org file %s"
8426 (abbreviate-file-name buffer-file-name))))
8427 (regexp (concat "[\n\r]\\*+ *\\("
8428 (if org-select-this-todo-keyword
8429 (concat "\\<\\(" org-select-this-todo-keyword
8430 "\\)\\>")
8431 org-not-done-regexp)
8432 "[^\n\r]*\\)"))
8433 (deadline-re (concat ".*\\(\n[^*].*\\)?" org-deadline-time-regexp))
8434 (sched-re (concat ".*\\(\n[^*].*\\)?" org-scheduled-time-regexp))
8435 ; FIXME why was this wrong? (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
8436 marker priority category tags
8437 ee txt)
8438 (goto-char (point-min))
8439 (while (re-search-forward regexp nil t)
8440 (catch :skip
8441 (save-match-data
8442 (beginning-of-line)
8443 (when (or (and org-agenda-todo-ignore-scheduled
8444 (looking-at sched-re))
8445 (and org-agenda-todo-ignore-deadlines
8446 (looking-at deadline-re)
8447 (org-deadline-close (match-string 2))))
8449 ;; FIXME: the following test also happens below, but we need it here
8450 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
8451 (throw :skip nil)))
8452 (org-agenda-skip)
8453 (goto-char (match-beginning 1))
8454 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
8455 category (org-get-category)
8456 tags (org-get-tags-at (point))
8457 txt (org-format-agenda-item "" (match-string 1) category tags)
8458 priority
8459 (+ (org-get-priority txt)
8460 (if org-todo-kwd-priority-p
8461 (- org-todo-kwd-max-priority -2
8462 (length
8463 (member (match-string 2) org-todo-keywords)))
8464 1)))
8465 (org-add-props txt props
8466 'org-marker marker 'org-hd-marker marker
8467 'priority priority 'category category)
8468 (push txt ee)
8469 (if org-agenda-todo-list-sublevels
8470 (goto-char (match-end 1))
8471 (org-end-of-subtree 'invisible))))
8472 (nreverse ee)))
8474 (defconst org-agenda-no-heading-message
8475 "No heading for this item in buffer or region.")
8477 (defun org-agenda-get-timestamps ()
8478 "Return the date stamp information for agenda display."
8479 (let* ((props (list 'face nil
8480 'org-not-done-regexp org-not-done-regexp
8481 'mouse-face 'highlight
8482 'keymap org-agenda-keymap
8483 'help-echo
8484 (format "mouse-2 or RET jump to org file %s"
8485 (abbreviate-file-name buffer-file-name))))
8486 (regexp (regexp-quote
8487 (substring
8488 (format-time-string
8489 (car org-time-stamp-formats)
8490 (apply 'encode-time ; DATE bound by calendar
8491 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8492 0 11)))
8493 marker hdmarker deadlinep scheduledp donep tmp priority category
8494 ee txt timestr tags)
8495 (goto-char (point-min))
8496 (while (re-search-forward regexp nil t)
8497 (catch :skip
8498 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
8499 (org-agenda-skip)
8500 (setq marker (org-agenda-new-marker (match-beginning 0))
8501 category (org-get-category (match-beginning 0))
8502 tmp (buffer-substring (max (point-min)
8503 (- (match-beginning 0)
8504 org-ds-keyword-length))
8505 (match-beginning 0))
8506 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8507 deadlinep (string-match org-deadline-regexp tmp)
8508 scheduledp (string-match org-scheduled-regexp tmp)
8509 donep (org-entry-is-done-p))
8510 (and org-agenda-skip-scheduled-if-done
8511 scheduledp donep
8512 (throw :skip t))
8513 (if (string-match ">" timestr)
8514 ;; substring should only run to end of time stamp
8515 (setq timestr (substring timestr 0 (match-end 0))))
8516 (save-excursion
8517 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8518 (progn
8519 (goto-char (match-end 1))
8520 (setq hdmarker (org-agenda-new-marker)
8521 tags (org-get-tags-at))
8522 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8523 (setq txt (org-format-agenda-item
8524 (format "%s%s"
8525 (if deadlinep "Deadline: " "")
8526 (if scheduledp "Scheduled: " ""))
8527 (match-string 1) category tags timestr)))
8528 (setq txt org-agenda-no-heading-message))
8529 (setq priority (org-get-priority txt))
8530 (org-add-props txt props
8531 'org-marker marker 'org-hd-marker hdmarker)
8532 (if deadlinep
8533 (org-add-props txt nil
8534 'face (if donep 'org-done 'org-warning)
8535 'undone-face 'org-warning 'done-face 'org-done
8536 'category category 'priority (+ 100 priority))
8537 (if scheduledp
8538 (org-add-props txt nil
8539 'face 'org-scheduled-today
8540 'undone-face 'org-scheduled-today 'done-face 'org-done
8541 'category category 'priority (+ 99 priority))
8542 (org-add-props txt nil 'priority priority 'category category)))
8543 (push txt ee))
8544 (outline-next-heading)))
8545 (nreverse ee)))
8547 (defun org-agenda-get-closed ()
8548 "Return the logged TODO entries for agenda display."
8549 (let* ((props (list 'mouse-face 'highlight
8550 'org-not-done-regexp org-not-done-regexp
8551 'keymap org-agenda-keymap
8552 'help-echo
8553 (format "mouse-2 or RET jump to org file %s"
8554 (abbreviate-file-name buffer-file-name))))
8555 (regexp (concat
8556 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
8557 (regexp-quote
8558 (substring
8559 (format-time-string
8560 (car org-time-stamp-formats)
8561 (apply 'encode-time ; DATE bound by calendar
8562 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
8563 1 11))))
8564 marker hdmarker priority category tags closedp
8565 ee txt timestr)
8566 (goto-char (point-min))
8567 (while (re-search-forward regexp nil t)
8568 (catch :skip
8569 (org-agenda-skip)
8570 (setq marker (org-agenda-new-marker (match-beginning 0))
8571 closedp (equal (match-string 1) org-closed-string)
8572 category (org-get-category (match-beginning 0))
8573 timestr (buffer-substring (match-beginning 0) (point-at-eol))
8574 ;; donep (org-entry-is-done-p)
8576 (if (string-match "\\]" timestr)
8577 ;; substring should only run to end of time stamp
8578 (setq timestr (substring timestr 0 (match-end 0))))
8579 (save-excursion
8580 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8581 (progn
8582 (goto-char (match-end 1))
8583 (setq hdmarker (org-agenda-new-marker)
8584 tags (org-get-tags-at))
8585 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8586 (setq txt (org-format-agenda-item
8587 (if closedp "Closed: " "Clocked: ")
8588 (match-string 1) category tags timestr)))
8589 (setq txt org-agenda-no-heading-message))
8590 (setq priority 100000)
8591 (org-add-props txt props
8592 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
8593 'priority priority 'category category
8594 'undone-face 'org-warning 'done-face 'org-done)
8595 (push txt ee))
8596 (outline-next-heading)))
8597 (nreverse ee)))
8599 (defun org-agenda-get-deadlines ()
8600 "Return the deadline information for agenda display."
8601 (let* ((wdays org-deadline-warning-days)
8602 (props (list 'mouse-face 'highlight
8603 'org-not-done-regexp org-not-done-regexp
8604 'keymap org-agenda-keymap
8605 'help-echo
8606 (format "mouse-2 or RET jump to org file %s"
8607 (abbreviate-file-name buffer-file-name))))
8608 (regexp org-deadline-time-regexp)
8609 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8610 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8611 d2 diff pos pos1 category tags
8612 ee txt head face)
8613 (goto-char (point-min))
8614 (while (re-search-forward regexp nil t)
8615 (catch :skip
8616 (org-agenda-skip)
8617 (setq pos (1- (match-beginning 1))
8618 d2 (time-to-days
8619 (org-time-string-to-time (match-string 1)))
8620 diff (- d2 d1))
8621 ;; When to show a deadline in the calendar:
8622 ;; If the expiration is within wdays warning time.
8623 ;; Past-due deadlines are only shown on the current date
8624 (if (and (< diff wdays) todayp (not (= diff 0)))
8625 (save-excursion
8626 (setq category (org-get-category))
8627 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8628 (progn
8629 (goto-char (match-end 0))
8630 (setq pos1 (match-end 1))
8631 (setq tags (org-get-tags-at pos1))
8632 (setq head (buffer-substring-no-properties
8633 (point)
8634 (progn (skip-chars-forward "^\r\n")
8635 (point))))
8636 (if (string-match org-looking-at-done-regexp head)
8637 (setq txt nil)
8638 (setq txt (org-format-agenda-item
8639 (format "In %3d d.: " diff) head category tags))))
8640 (setq txt org-agenda-no-heading-message))
8641 (when txt
8642 (setq face (cond ((<= diff 0) 'org-warning)
8643 ((<= diff 5) 'org-upcoming-deadline)
8644 (t nil)))
8645 (org-add-props txt props
8646 'org-marker (org-agenda-new-marker pos)
8647 'org-hd-marker (org-agenda-new-marker pos1)
8648 'priority (+ (- 10 diff) (org-get-priority txt))
8649 'category category
8650 'face face 'undone-face face 'done-face 'org-done)
8651 (push txt ee))))))
8652 ee))
8654 (defun org-agenda-get-scheduled ()
8655 "Return the scheduled information for agenda display."
8656 (let* ((props (list 'face 'org-scheduled-previously
8657 'org-not-done-regexp org-not-done-regexp
8658 'undone-face 'org-scheduled-previously
8659 'done-face 'org-done
8660 'mouse-face 'highlight
8661 'keymap org-agenda-keymap
8662 'help-echo
8663 (format "mouse-2 or RET jump to org file %s"
8664 (abbreviate-file-name buffer-file-name))))
8665 (regexp org-scheduled-time-regexp)
8666 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
8667 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
8668 d2 diff pos pos1 category tags donep
8669 ee txt head)
8670 (goto-char (point-min))
8671 (while (re-search-forward regexp nil t)
8672 (catch :skip
8673 (org-agenda-skip)
8674 (setq pos (1- (match-beginning 1))
8675 d2 (time-to-days
8676 (org-time-string-to-time (match-string 1)))
8677 diff (- d2 d1))
8678 ;; When to show a scheduled item in the calendar:
8679 ;; If it is on or past the date.
8680 (if (and (< diff 0) todayp)
8681 (save-excursion
8682 (setq category (org-get-category))
8683 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
8684 (progn
8685 (goto-char (match-end 0))
8686 (setq pos1 (match-end 1))
8687 (setq tags (org-get-tags-at))
8688 (setq head (buffer-substring-no-properties
8689 (point)
8690 (progn (skip-chars-forward "^\r\n") (point))))
8691 (if (string-match org-looking-at-done-regexp head)
8692 (setq txt nil)
8693 (setq txt (org-format-agenda-item
8694 (format "Sched.%2dx: " (- 1 diff)) head
8695 category tags))))
8696 (setq txt org-agenda-no-heading-message))
8697 (when txt
8698 (org-add-props txt props
8699 'org-marker (org-agenda-new-marker pos)
8700 'org-hd-marker (org-agenda-new-marker pos1)
8701 'priority (+ (- 5 diff) (org-get-priority txt))
8702 'category category)
8703 (push txt ee))))))
8704 ee))
8706 (defun org-agenda-get-blocks ()
8707 "Return the date-range information for agenda display."
8708 (let* ((props (list 'face nil
8709 'org-not-done-regexp org-not-done-regexp
8710 'mouse-face 'highlight
8711 'keymap org-agenda-keymap
8712 'help-echo
8713 (format "mouse-2 or RET jump to org file %s"
8714 (abbreviate-file-name buffer-file-name))))
8715 (regexp org-tr-regexp)
8716 (d0 (calendar-absolute-from-gregorian date))
8717 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
8718 (goto-char (point-min))
8719 (while (re-search-forward regexp nil t)
8720 (catch :skip
8721 (org-agenda-skip)
8722 (setq pos (point))
8723 (setq timestr (match-string 0)
8724 s1 (match-string 1)
8725 s2 (match-string 2)
8726 d1 (time-to-days (org-time-string-to-time s1))
8727 d2 (time-to-days (org-time-string-to-time s2)))
8728 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
8729 ;; Only allow days between the limits, because the normal
8730 ;; date stamps will catch the limits.
8731 (save-excursion
8732 (setq marker (org-agenda-new-marker (point)))
8733 (setq category (org-get-category))
8734 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8735 (progn
8736 (setq hdmarker (org-agenda-new-marker (match-end 1)))
8737 (goto-char (match-end 1))
8738 (setq tags (org-get-tags-at))
8739 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8740 (setq txt (org-format-agenda-item
8741 (format (if (= d1 d2) "" "(%d/%d): ")
8742 (1+ (- d0 d1)) (1+ (- d2 d1)))
8743 (match-string 1) category tags
8744 (if (= d0 d1) timestr))))
8745 (setq txt org-agenda-no-heading-message))
8746 (org-add-props txt props
8747 'org-marker marker 'org-hd-marker hdmarker
8748 'priority (org-get-priority txt) 'category category)
8749 (push txt ee)))
8750 (goto-char pos)))
8751 ;; Sort the entries by expiration date.
8752 (nreverse ee)))
8754 (defconst org-plain-time-of-day-regexp
8755 (concat
8756 "\\(\\<[012]?[0-9]"
8757 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8758 "\\(--?"
8759 "\\(\\<[012]?[0-9]"
8760 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8761 "\\)?")
8762 "Regular expression to match a plain time or time range.
8763 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
8764 groups carry important information:
8765 0 the full match
8766 1 the first time, range or not
8767 8 the second time, if it is a range.")
8769 (defconst org-stamp-time-of-day-regexp
8770 (concat
8771 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
8772 "\\([012][0-9]:[0-5][0-9]\\)>"
8773 "\\(--?"
8774 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
8775 "Regular expression to match a timestamp time or time range.
8776 After a match, the following groups carry important information:
8777 0 the full match
8778 1 date plus weekday, for backreferencing to make sure both times on same day
8779 2 the first time, range or not
8780 4 the second time, if it is a range.")
8782 (defvar org-prefix-has-time nil
8783 "A flag, set by `org-compile-prefix-format'.
8784 The flag is set if the currently compiled format contains a `%t'.")
8785 (defvar org-prefix-has-tag nil
8786 "A flag, set by `org-compile-prefix-format'.
8787 The flag is set if the currently compiled format contains a `%T'.")
8789 (defun org-format-agenda-item (extra txt &optional category tags dotime
8790 noprefix)
8791 "Format TXT to be inserted into the agenda buffer.
8792 In particular, it adds the prefix and corresponding text properties. EXTRA
8793 must be a string and replaces the `%s' specifier in the prefix format.
8794 CATEGORY (string, symbol or nil) may be used to overrule the default
8795 category taken from local variable or file name. It will replace the `%c'
8796 specifier in the format. DOTIME, when non-nil, indicates that a
8797 time-of-day should be extracted from TXT for sorting of this entry, and for
8798 the `%t' specifier in the format. When DOTIME is a string, this string is
8799 searched for a time before TXT is. NOPREFIX is a flag and indicates that
8800 only the correctly processes TXT should be returned - this is used by
8801 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
8802 (save-match-data
8803 ;; Diary entries sometimes have extra whitespace at the beginning
8804 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
8805 (let* ((category (or category
8806 org-category
8807 (if buffer-file-name
8808 (file-name-sans-extension
8809 (file-name-nondirectory buffer-file-name))
8810 "")))
8811 (tag (if tags (nth (1- (length tags)) tags) ""))
8812 time ;; needed for the eval of the prefix format
8813 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
8814 (time-of-day (and dotime (org-get-time-of-day ts)))
8815 stamp plain s0 s1 s2 rtn)
8816 (when (and dotime time-of-day org-prefix-has-time)
8817 ;; Extract starting and ending time and move them to prefix
8818 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
8819 (setq plain (string-match org-plain-time-of-day-regexp ts)))
8820 (setq s0 (match-string 0 ts)
8821 s1 (match-string (if plain 1 2) ts)
8822 s2 (match-string (if plain 8 4) ts))
8824 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
8825 ;; them, we might want to remove them there to avoid duplication.
8826 ;; The user can turn this off with a variable.
8827 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
8828 (string-match (concat (regexp-quote s0) " *") txt)
8829 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
8830 (= (match-beginning 0) 0)
8832 (setq txt (replace-match "" nil nil txt))))
8833 ;; Normalize the time(s) to 24 hour
8834 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
8835 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
8837 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
8838 ;; Tags are in the string
8839 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
8840 (and org-agenda-remove-tags-when-in-prefix
8841 org-prefix-has-tag))
8842 (setq txt (replace-match "" t t txt))
8843 (setq txt (replace-match
8844 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
8845 (match-string 2 txt))
8846 t t txt))))
8848 ;; Create the final string
8849 (if noprefix
8850 (setq rtn txt)
8851 ;; Prepare the variables needed in the eval of the compiled format
8852 (setq time (cond (s2 (concat s1 "-" s2))
8853 (s1 (concat s1 "......"))
8854 (t ""))
8855 extra (or extra "")
8856 category (if (symbolp category) (symbol-name category) category))
8857 ;; Evaluate the compiled format
8858 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
8860 ;; And finally add the text properties
8861 (org-add-props rtn nil
8862 'category (downcase category) 'tags tags
8863 'prefix-length (- (length rtn) (length txt))
8864 'time-of-day time-of-day
8865 'dotime dotime))))
8867 (defvar org-agenda-sorting-strategy)
8868 (defvar org-agenda-sorting-strategy-selected nil)
8870 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
8871 (catch 'exit
8872 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
8873 ((and todayp (member 'today (car org-agenda-time-grid))))
8874 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
8875 ((member 'weekly (car org-agenda-time-grid)))
8876 (t (throw 'exit list)))
8877 (let* ((have (delq nil (mapcar
8878 (lambda (x) (get-text-property 1 'time-of-day x))
8879 list)))
8880 (string (nth 1 org-agenda-time-grid))
8881 (gridtimes (nth 2 org-agenda-time-grid))
8882 (req (car org-agenda-time-grid))
8883 (remove (member 'remove-match req))
8884 new time)
8885 (if (and (member 'require-timed req) (not have))
8886 ;; don't show empty grid
8887 (throw 'exit list))
8888 (while (setq time (pop gridtimes))
8889 (unless (and remove (member time have))
8890 (setq time (int-to-string time))
8891 (push (org-format-agenda-item
8892 nil string "" nil
8893 (concat (substring time 0 -2) ":" (substring time -2)))
8894 new)
8895 (put-text-property
8896 1 (length (car new)) 'face 'org-time-grid (car new))))
8897 (if (member 'time-up org-agenda-sorting-strategy-selected)
8898 (append new list)
8899 (append list new)))))
8901 (defun org-compile-prefix-format (key)
8902 "Compile the prefix format into a Lisp form that can be evaluated.
8903 The resulting form is returned and stored in the variable
8904 `org-prefix-format-compiled'."
8905 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8906 (let ((s (cond
8907 ((stringp org-agenda-prefix-format)
8908 org-agenda-prefix-format)
8909 ((assq key org-agenda-prefix-format)
8910 (cdr (assq key org-agenda-prefix-format)))
8911 (t " %-12:c%?-12t% s")))
8912 (start 0)
8913 varform vars var e c f opt)
8914 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8915 s start)
8916 (setq var (cdr (assoc (match-string 4 s)
8917 '(("c" . category) ("t" . time) ("s" . extra)
8918 ("T" . tag))))
8919 c (or (match-string 3 s) "")
8920 opt (match-beginning 1)
8921 start (1+ (match-beginning 0)))
8922 (if (equal var 'time) (setq org-prefix-has-time t))
8923 (if (equal var 'tag) (setq org-prefix-has-tag t))
8924 (setq f (concat "%" (match-string 2 s) "s"))
8925 (if opt
8926 (setq varform
8927 `(if (equal "" ,var)
8929 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8930 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8931 (setq s (replace-match "%s" t nil s))
8932 (push varform vars))
8933 (setq vars (nreverse vars))
8934 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8936 (defun org-set-sorting-strategy (key)
8937 (if (symbolp (car org-agenda-sorting-strategy))
8938 ;; the old format
8939 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
8940 (setq org-agenda-sorting-strategy-selected
8941 (or (cdr (assq key org-agenda-sorting-strategy))
8942 (cdr (assq 'agenda org-agenda-sorting-strategy))
8943 '(time-up category-keep priority-down)))))
8945 (defun org-get-time-of-day (s &optional string mod24)
8946 "Check string S for a time of day.
8947 If found, return it as a military time number between 0 and 2400.
8948 If not found, return nil.
8949 The optional STRING argument forces conversion into a 5 character wide string
8950 HH:MM."
8951 (save-match-data
8952 (when
8954 (string-match
8955 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8956 (string-match
8957 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8958 (let* ((h (string-to-number (match-string 1 s)))
8959 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8960 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8961 (am-p (equal ampm "am"))
8962 (h1 (cond ((not ampm) h)
8963 ((= h 12) (if am-p 0 12))
8964 (t (+ h (if am-p 0 12)))))
8965 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8966 (mod h1 24) h1))
8967 (t0 (+ (* 100 h2) m))
8968 (t1 (concat (if (>= h1 24) "+" " ")
8969 (if (< t0 100) "0" "")
8970 (if (< t0 10) "0" "")
8971 (int-to-string t0))))
8972 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8974 (defun org-finalize-agenda-entries (list &optional nosort)
8975 "Sort and concatenate the agenda items."
8976 (setq list (mapcar 'org-agenda-highlight-todo list))
8977 (if nosort
8978 list
8979 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
8981 (defun org-agenda-highlight-todo (x)
8982 (let (re pl)
8983 (if (eq x 'line)
8984 (save-excursion
8985 (beginning-of-line 1)
8986 (setq re (get-text-property (point) 'org-not-done-regexp))
8987 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
8988 (and (looking-at (concat "[ \t]*\\.*" re))
8989 (add-text-properties (match-beginning 0) (match-end 0)
8990 '(face org-todo))))
8991 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
8992 pl (get-text-property 0 'prefix-length x))
8993 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
8994 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
8995 '(face org-todo) x))
8996 x)))
8998 (defsubst org-cmp-priority (a b)
8999 "Compare the priorities of string A and B."
9000 (let ((pa (or (get-text-property 1 'priority a) 0))
9001 (pb (or (get-text-property 1 'priority b) 0)))
9002 (cond ((> pa pb) +1)
9003 ((< pa pb) -1)
9004 (t nil))))
9006 (defsubst org-cmp-category (a b)
9007 "Compare the string values of categories of strings A and B."
9008 (let ((ca (or (get-text-property 1 'category a) ""))
9009 (cb (or (get-text-property 1 'category b) "")))
9010 (cond ((string-lessp ca cb) -1)
9011 ((string-lessp cb ca) +1)
9012 (t nil))))
9014 (defsubst org-cmp-tag (a b)
9015 "Compare the string values of categories of strings A and B."
9016 (let ((ta (car (last (get-text-property 1 'tags a))))
9017 (tb (car (last (get-text-property 1 'tags b)))))
9018 (cond ((not ta) +1)
9019 ((not tb) -1)
9020 ((string-lessp ta tb) -1)
9021 ((string-lessp tb ta) +1)
9022 (t nil))))
9024 (defsubst org-cmp-time (a b)
9025 "Compare the time-of-day values of strings A and B."
9026 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
9027 (ta (or (get-text-property 1 'time-of-day a) def))
9028 (tb (or (get-text-property 1 'time-of-day b) def)))
9029 (cond ((< ta tb) -1)
9030 ((< tb ta) +1)
9031 (t nil))))
9033 (defun org-entries-lessp (a b)
9034 "Predicate for sorting agenda entries."
9035 ;; The following variables will be used when the form is evaluated.
9036 (let* ((time-up (org-cmp-time a b))
9037 (time-down (if time-up (- time-up) nil))
9038 (priority-up (org-cmp-priority a b))
9039 (priority-down (if priority-up (- priority-up) nil))
9040 (category-up (org-cmp-category a b))
9041 (category-down (if category-up (- category-up) nil))
9042 (category-keep (if category-up +1 nil))
9043 (tag-up (org-cmp-tag a b))
9044 (tag-down (if tag-up (- tag-up) nil)))
9045 (cdr (assoc
9046 (eval (cons 'or org-agenda-sorting-strategy-selected))
9047 '((-1 . t) (1 . nil) (nil . nil))))))
9049 (defun org-agenda-show-priority ()
9050 "Show the priority of the current item.
9051 This priority is composed of the main priority given with the [#A] cookies,
9052 and by additional input from the age of a schedules or deadline entry."
9053 (interactive)
9054 (let* ((pri (get-text-property (point-at-bol) 'priority)))
9055 (message "Priority is %d" (if pri pri -1000))))
9057 (defun org-agenda-show-tags ()
9058 "Show the tags applicable to the current item."
9059 (interactive)
9060 (let* ((tags (get-text-property (point-at-bol) 'tags)))
9061 (if tags
9062 (message "Tags are :%s:"
9063 (org-no-properties (mapconcat 'identity tags ":")))
9064 (message "No tags associated with this line"))))
9066 (defun org-agenda-goto (&optional highlight)
9067 "Go to the Org-mode file which contains the item at point."
9068 (interactive)
9069 (let* ((marker (or (get-text-property (point) 'org-marker)
9070 (org-agenda-error)))
9071 (buffer (marker-buffer marker))
9072 (pos (marker-position marker)))
9073 (switch-to-buffer-other-window buffer)
9074 (widen)
9075 (goto-char pos)
9076 (when (org-mode-p)
9077 (org-show-context 'agenda)
9078 (save-excursion
9079 (and (outline-next-heading)
9080 (org-flag-heading nil)))) ; show the next heading
9081 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
9083 (defun org-agenda-kill ()
9084 "Kill the entry or subtree belonging to the current agenda entry."
9085 (interactive)
9086 (let* ((marker (or (get-text-property (point) 'org-marker)
9087 (org-agenda-error)))
9088 (hdmarker (get-text-property (point) 'org-hd-marker))
9089 (buffer (marker-buffer marker))
9090 (pos (marker-position marker))
9091 dbeg dend (n 0) conf)
9092 (with-current-buffer buffer
9093 (save-excursion
9094 (goto-char pos)
9095 (if (org-mode-p)
9096 (setq dbeg (progn (org-back-to-heading t) (point))
9097 dend (org-end-of-subtree t))
9098 (setq dbeg (point-at-bol)
9099 dend (min (point-max) (1+ (point-at-eol)))))
9100 (goto-char dbeg)
9101 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
9102 (setq conf (or (eq t org-agenda-confirm-kill)
9103 (and (numberp org-agenda-confirm-kill)
9104 (> n org-agenda-confirm-kill))))
9105 (and conf
9106 (not (y-or-n-p
9107 (format "Delete entry with %d lines in buffer \"%s\"? "
9108 n (buffer-name buffer))))
9109 (error "Abort"))
9110 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
9111 (with-current-buffer buffer (delete-region dbeg dend))
9112 (message "Agenda item and source killed")))
9114 (defun org-agenda-archive ()
9115 "Kill the entry or subtree belonging to the current agenda entry."
9116 (interactive)
9117 (let* ((marker (or (get-text-property (point) 'org-marker)
9118 (org-agenda-error)))
9119 (hdmarker (get-text-property (point) 'org-hd-marker))
9120 (buffer (marker-buffer marker))
9121 (pos (marker-position marker))
9122 dbeg dend txt n conf)
9123 (with-current-buffer buffer
9124 (if (org-mode-p)
9125 (save-excursion
9126 (goto-char pos)
9127 (org-remove-subtree-entries-from-agenda)
9128 (org-back-to-heading t)
9129 (org-archive-subtree))
9130 (error "Archiving works only in Org-mode files")))))
9132 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
9133 "Remove all lines in the agenda that correspond to a given subtree.
9134 The subtree is the one in buffer BUF, starting at BEG and ending at END.
9135 If this information is not given, the function uses the tree at point."
9136 (let ((buf (or buf (current-buffer))) m p)
9137 (save-excursion
9138 (unless (and beg end)
9139 (org-back-to-heading t)
9140 (setq beg (point))
9141 (org-end-of-subtree t)
9142 (setq end (point)))
9143 (set-buffer (get-buffer org-agenda-buffer-name))
9144 (save-excursion
9145 (goto-char (point-max))
9146 (beginning-of-line 1)
9147 (while (not (bobp))
9148 (when (and (setq m (get-text-property (point) 'org-marker))
9149 (equal buf (marker-buffer m))
9150 (setq p (marker-position m))
9151 (>= p beg)
9152 (<= p end))
9153 (let (buffer-read-only)
9154 (delete-region (point-at-bol) (1+ (point-at-eol)))))
9155 (beginning-of-line 0))))))
9157 (defun org-agenda-open-link ()
9158 "Follow the link in the current line, if any."
9159 (interactive)
9160 (let ((eol (point-at-eol)))
9161 (save-excursion
9162 (if (or (re-search-forward org-bracket-link-regexp eol t)
9163 (re-search-forward org-angle-link-re eol t)
9164 (re-search-forward org-plain-link-re eol t))
9165 (call-interactively 'org-open-at-point)
9166 (error "No link in current line")))))
9168 (defun org-agenda-switch-to (&optional delete-other-windows)
9169 "Go to the Org-mode file which contains the item at point."
9170 (interactive)
9171 (let* ((marker (or (get-text-property (point) 'org-marker)
9172 (org-agenda-error)))
9173 (buffer (marker-buffer marker))
9174 (pos (marker-position marker)))
9175 (switch-to-buffer buffer)
9176 (and delete-other-windows (delete-other-windows))
9177 (widen)
9178 (goto-char pos)
9179 (when (org-mode-p)
9180 (org-show-context 'agenda)
9181 (save-excursion
9182 (and (outline-next-heading)
9183 (org-flag-heading nil)))))) ; show the next heading
9185 (defun org-agenda-goto-mouse (ev)
9186 "Go to the Org-mode file which contains the item at the mouse click."
9187 (interactive "e")
9188 (mouse-set-point ev)
9189 (org-agenda-goto))
9191 (defun org-agenda-show ()
9192 "Display the Org-mode file which contains the item at point."
9193 (interactive)
9194 (let ((win (selected-window)))
9195 (org-agenda-goto t)
9196 (select-window win)))
9198 (defun org-agenda-recenter (arg)
9199 "Display the Org-mode file which contains the item at point and recenter."
9200 (interactive "P")
9201 (let ((win (selected-window)))
9202 (org-agenda-goto t)
9203 (recenter arg)
9204 (select-window win)))
9206 (defun org-agenda-show-mouse (ev)
9207 "Display the Org-mode file which contains the item at the mouse click."
9208 (interactive "e")
9209 (mouse-set-point ev)
9210 (org-agenda-show))
9212 (defun org-agenda-check-no-diary ()
9213 "Check if the entry is a diary link and abort if yes."
9214 (if (get-text-property (point) 'org-agenda-diary-link)
9215 (org-agenda-error)))
9217 (defun org-agenda-error ()
9218 (error "Command not allowed in this line"))
9220 (defvar org-last-heading-marker (make-marker)
9221 "Marker pointing to the headline that last changed its TODO state
9222 by a remote command from the agenda.")
9224 (defun org-agenda-todo (&optional arg)
9225 "Cycle TODO state of line at point, also in Org-mode file.
9226 This changes the line at point, all other lines in the agenda referring to
9227 the same tree node, and the headline of the tree node in the Org-mode file."
9228 (interactive "P")
9229 (org-agenda-check-no-diary)
9230 (let* ((col (current-column))
9231 (marker (or (get-text-property (point) 'org-marker)
9232 (org-agenda-error)))
9233 (buffer (marker-buffer marker))
9234 (pos (marker-position marker))
9235 (hdmarker (get-text-property (point) 'org-hd-marker))
9236 (buffer-read-only nil)
9237 newhead)
9238 (with-current-buffer buffer
9239 (widen)
9240 (goto-char pos)
9241 (org-show-context 'agenda)
9242 (save-excursion
9243 (and (outline-next-heading)
9244 (org-flag-heading nil))) ; show the next heading
9245 (org-todo arg)
9246 (and (bolp) (forward-char 1))
9247 (setq newhead (org-get-heading))
9248 (save-excursion
9249 (org-back-to-heading)
9250 (move-marker org-last-heading-marker (point))))
9251 (beginning-of-line 1)
9252 (save-excursion
9253 (org-agenda-change-all-lines newhead hdmarker 'fixface))
9254 (move-to-column col)))
9256 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
9257 "Change all lines in the agenda buffer which match HDMARKER.
9258 The new content of the line will be NEWHEAD (as modified by
9259 `org-format-agenda-item'). HDMARKER is checked with
9260 `equal' against all `org-hd-marker' text properties in the file.
9261 If FIXFACE is non-nil, the face of each item is modified acording to
9262 the new TODO state."
9263 (let* ((buffer-read-only nil)
9264 props m pl undone-face done-face finish new dotime cat tags)
9265 (save-excursion
9266 (goto-char (point-max))
9267 (beginning-of-line 1)
9268 (while (not finish)
9269 (setq finish (bobp))
9270 (when (and (setq m (get-text-property (point) 'org-hd-marker))
9271 (equal m hdmarker))
9272 (setq props (text-properties-at (point))
9273 dotime (get-text-property (point) 'dotime)
9274 cat (get-text-property (point) 'category)
9275 tags (get-text-property (point) 'tags)
9276 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
9277 pl (get-text-property (point) 'prefix-length)
9278 undone-face (get-text-property (point) 'undone-face)
9279 done-face (get-text-property (point) 'done-face))
9280 (move-to-column pl)
9281 (cond
9282 ((equal new "")
9283 (beginning-of-line 1)
9284 (and (looking-at ".*\n?") (replace-match "")))
9285 ((looking-at ".*")
9286 (replace-match new t t)
9287 (beginning-of-line 1)
9288 (add-text-properties (point-at-bol) (point-at-eol) props)
9289 (when fixface
9290 (add-text-properties
9291 (point-at-bol) (point-at-eol)
9292 (list 'face
9293 (if org-last-todo-state-is-todo
9294 undone-face done-face))))
9295 (org-agenda-highlight-todo 'line)
9296 (beginning-of-line 1))
9297 (t (error "Line update did not work"))))
9298 (beginning-of-line 0)))
9299 (org-finalize-agenda)))
9301 (defun org-agenda-align-tags (&optional line)
9302 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
9303 (let ((buffer-read-only))
9304 (save-excursion
9305 (goto-char (if line (point-at-bol) (point-min)))
9306 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
9307 (if line (point-at-eol) nil) t)
9308 (delete-region (match-beginning 1) (match-end 1))
9309 (goto-char (match-beginning 1))
9310 (insert (org-add-props
9311 (make-string (max 1 (- org-agenda-align-tags-to-column
9312 (current-column))) ?\ )
9313 (text-properties-at (point))))))))
9315 (defun org-agenda-priority-up ()
9316 "Increase the priority of line at point, also in Org-mode file."
9317 (interactive)
9318 (org-agenda-priority 'up))
9320 (defun org-agenda-priority-down ()
9321 "Decrease the priority of line at point, also in Org-mode file."
9322 (interactive)
9323 (org-agenda-priority 'down))
9325 (defun org-agenda-priority (&optional force-direction)
9326 "Set the priority of line at point, also in Org-mode file.
9327 This changes the line at point, all other lines in the agenda referring to
9328 the same tree node, and the headline of the tree node in the Org-mode file."
9329 (interactive)
9330 (org-agenda-check-no-diary)
9331 (let* ((marker (or (get-text-property (point) 'org-marker)
9332 (org-agenda-error)))
9333 (buffer (marker-buffer marker))
9334 (pos (marker-position marker))
9335 (hdmarker (get-text-property (point) 'org-hd-marker))
9336 (buffer-read-only nil)
9337 newhead)
9338 (with-current-buffer buffer
9339 (widen)
9340 (goto-char pos)
9341 (org-show-context 'agenda)
9342 (save-excursion
9343 (and (outline-next-heading)
9344 (org-flag-heading nil))) ; show the next heading
9345 (funcall 'org-priority force-direction)
9346 (end-of-line 1)
9347 (setq newhead (org-get-heading)))
9348 (org-agenda-change-all-lines newhead hdmarker)
9349 (beginning-of-line 1)))
9351 (defun org-get-tags-at (&optional pos)
9352 "Get a list of all headline tags applicable at POS.
9353 POS defaults to point. If tags are inherited, the list contains
9354 the targets in the same sequence as the headlines appear, i.e.
9355 the tags of the current headline come last."
9356 (interactive)
9357 (let (tags)
9358 (save-excursion
9359 (goto-char (or pos (point)))
9360 (save-match-data
9361 (org-back-to-heading t)
9362 (condition-case nil
9363 (while t
9364 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
9365 (setq tags (append (org-split-string
9366 (org-match-string-no-properties 1) ":")
9367 tags)))
9368 (or org-use-tag-inheritance (error ""))
9369 (org-up-heading-all 1))
9370 (error nil))))
9371 tags))
9373 ;; FIXME: should fix the tags property of the agenda line.
9374 (defun org-agenda-set-tags ()
9375 "Set tags for the current headline."
9376 (interactive)
9377 (org-agenda-check-no-diary)
9378 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
9379 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
9380 (org-agenda-error)))
9381 (buffer (marker-buffer hdmarker))
9382 (pos (marker-position hdmarker))
9383 (buffer-read-only nil)
9384 newhead)
9385 (with-current-buffer buffer
9386 (widen)
9387 (goto-char pos)
9388 (org-show-context 'agenda)
9389 (save-excursion
9390 (and (outline-next-heading)
9391 (org-flag-heading nil))) ; show the next heading
9392 (call-interactively 'org-set-tags)
9393 (end-of-line 1)
9394 (setq newhead (org-get-heading)))
9395 (org-agenda-change-all-lines newhead hdmarker)
9396 (beginning-of-line 1)))
9398 (defun org-agenda-date-later (arg &optional what)
9399 "Change the date of this item to one day later."
9400 (interactive "p")
9401 (org-agenda-check-type t 'agenda 'timeline)
9402 (org-agenda-check-no-diary)
9403 (let* ((marker (or (get-text-property (point) 'org-marker)
9404 (org-agenda-error)))
9405 (buffer (marker-buffer marker))
9406 (pos (marker-position marker)))
9407 (with-current-buffer buffer
9408 (widen)
9409 (goto-char pos)
9410 (if (not (org-at-timestamp-p))
9411 (error "Cannot find time stamp"))
9412 (org-timestamp-change arg (or what 'day)))
9413 (org-agenda-overlay-new-time marker org-last-changed-timestamp)
9414 (message "Time stamp changed to %s" org-last-changed-timestamp)))
9416 (defun org-agenda-date-earlier (arg &optional what)
9417 "Change the date of this item to one day earlier."
9418 (interactive "p")
9419 (org-agenda-date-later (- arg) what))
9422 (defun org-agenda-overlay-new-time (marker stamp)
9423 (let ((buffer-read-only nil)
9424 ovs ov)
9425 (setq stamp (concat " => " stamp))
9426 (save-excursion
9427 (goto-char (point-max))
9428 (while (not (bobp))
9429 (when (equal marker (get-text-property (point) 'org-marker))
9430 ;; remove any old overlays
9431 (org-find-overlays 'org-new-date (1- (point-at-eol)) 'delete)
9432 ;; put a new overlay
9433 (move-to-column (- (window-width) (length stamp)) t)
9434 (setq ov (org-make-overlay (1- (point)) (point-at-eol)))
9435 (org-overlay-put ov 'org-new-date t)
9436 (org-overlay-display ov stamp 'secondary-selection)
9437 (beginning-of-line 1))
9438 (beginning-of-line 0)))))
9440 (defun org-agenda-date-prompt (arg)
9441 "Change the date of this item. Date is prompted for, with default today.
9442 The prefix ARG is passed to the `org-time-stamp' command and can therefore
9443 be used to request time specification in the time stamp."
9444 (interactive "P")
9445 (org-agenda-check-type t 'agenda 'timeline)
9446 (org-agenda-check-no-diary)
9447 (let* ((marker (or (get-text-property (point) 'org-marker)
9448 (org-agenda-error)))
9449 (buffer (marker-buffer marker))
9450 (pos (marker-position marker)))
9451 (with-current-buffer buffer
9452 (widen)
9453 (goto-char pos)
9454 (if (not (org-at-timestamp-p))
9455 (error "Cannot find time stamp"))
9456 (org-time-stamp arg)
9457 (message "Time stamp changed to %s" org-last-changed-timestamp))))
9459 (defun org-agenda-schedule (arg)
9460 "Schedule the item at point."
9461 (interactive "P")
9462 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9463 (org-agenda-check-no-diary)
9464 (let* ((marker (or (get-text-property (point) 'org-marker)
9465 (org-agenda-error)))
9466 (buffer (marker-buffer marker))
9467 (pos (marker-position marker))
9468 (org-insert-labeled-timestamps-at-point nil)
9470 (with-current-buffer buffer
9471 (widen)
9472 (goto-char pos)
9473 (setq ts (org-schedule))
9474 (message "Item scheduled for %s" ts))))
9476 (defun org-agenda-deadline (arg)
9477 "Schedule the item at point."
9478 (interactive "P")
9479 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
9480 (org-agenda-check-no-diary)
9481 (let* ((marker (or (get-text-property (point) 'org-marker)
9482 (org-agenda-error)))
9483 (buffer (marker-buffer marker))
9484 (pos (marker-position marker))
9485 (org-insert-labeled-timestamps-at-point nil)
9487 (with-current-buffer buffer
9488 (widen)
9489 (goto-char pos)
9490 (setq ts (org-deadline))
9491 (message "Deadline for this item set to %s" ts))))
9493 (defun org-get-heading ()
9494 "Return the heading of the current entry, without the stars."
9495 (save-excursion
9496 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
9497 (if (and (re-search-backward "[\r\n]\\*" nil t)
9498 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
9499 (match-string 1)
9500 "")))
9502 (defun org-agenda-clock-in (&optional arg)
9503 "Start the clock on the currently selected item."
9504 (interactive "P")
9505 (org-agenda-check-no-diary)
9506 (let* ((marker (or (get-text-property (point) 'org-marker)
9507 (org-agenda-error)))
9508 (pos (marker-position marker)))
9509 (with-current-buffer (marker-buffer marker)
9510 (widen)
9511 (goto-char pos)
9512 (org-clock-in))))
9514 (defun org-agenda-diary-entry ()
9515 "Make a diary entry, like the `i' command from the calendar.
9516 All the standard commands work: block, weekly etc."
9517 (interactive)
9518 (org-agenda-check-type t 'agenda 'timeline)
9519 (require 'diary-lib)
9520 (let* ((char (progn
9521 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
9522 (read-char-exclusive)))
9523 (cmd (cdr (assoc char
9524 '((?d . insert-diary-entry)
9525 (?w . insert-weekly-diary-entry)
9526 (?m . insert-monthly-diary-entry)
9527 (?y . insert-yearly-diary-entry)
9528 (?a . insert-anniversary-diary-entry)
9529 (?b . insert-block-diary-entry)
9530 (?c . insert-cyclic-diary-entry)))))
9531 (oldf (symbol-function 'calendar-cursor-to-date))
9532 (point (point))
9533 (mark (or (mark t) (point))))
9534 (unless cmd
9535 (error "No command associated with <%c>" char))
9536 (unless (and (get-text-property point 'day)
9537 (or (not (equal ?b char))
9538 (get-text-property mark 'day)))
9539 (error "Don't know which date to use for diary entry"))
9540 ;; We implement this by hacking the `calendar-cursor-to-date' function
9541 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
9542 (let ((calendar-mark-ring
9543 (list (calendar-gregorian-from-absolute
9544 (or (get-text-property mark 'day)
9545 (get-text-property point 'day))))))
9546 (unwind-protect
9547 (progn
9548 (fset 'calendar-cursor-to-date
9549 (lambda (&optional error)
9550 (calendar-gregorian-from-absolute
9551 (get-text-property point 'day))))
9552 (call-interactively cmd))
9553 (fset 'calendar-cursor-to-date oldf)))))
9556 (defun org-agenda-execute-calendar-command (cmd)
9557 "Execute a calendar command from the agenda, with the date associated to
9558 the cursor position."
9559 (org-agenda-check-type t 'agenda 'timeline)
9560 (require 'diary-lib)
9561 (unless (get-text-property (point) 'day)
9562 (error "Don't know which date to use for calendar command"))
9563 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
9564 (point (point))
9565 (date (calendar-gregorian-from-absolute
9566 (get-text-property point 'day)))
9567 (displayed-day (extract-calendar-day date))
9568 (displayed-month (extract-calendar-month date))
9569 (displayed-year (extract-calendar-year date)))
9570 (unwind-protect
9571 (progn
9572 (fset 'calendar-cursor-to-date
9573 (lambda (&optional error)
9574 (calendar-gregorian-from-absolute
9575 (get-text-property point 'day))))
9576 (call-interactively cmd))
9577 (fset 'calendar-cursor-to-date oldf))))
9579 (defun org-agenda-phases-of-moon ()
9580 "Display the phases of the moon for the 3 months around the cursor date."
9581 (interactive)
9582 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
9584 (defun org-agenda-holidays ()
9585 "Display the holidays for the 3 months around the cursor date."
9586 (interactive)
9587 (org-agenda-execute-calendar-command 'list-calendar-holidays))
9589 (defun org-agenda-sunrise-sunset (arg)
9590 "Display sunrise and sunset for the cursor date.
9591 Latitude and longitude can be specified with the variables
9592 `calendar-latitude' and `calendar-longitude'. When called with prefix
9593 argument, latitude and longitude will be prompted for."
9594 (interactive "P")
9595 (let ((calendar-longitude (if arg nil calendar-longitude))
9596 (calendar-latitude (if arg nil calendar-latitude))
9597 (calendar-location-name
9598 (if arg "the given coordinates" calendar-location-name)))
9599 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
9601 (defun org-agenda-goto-calendar ()
9602 "Open the Emacs calendar with the date at the cursor."
9603 (interactive)
9604 (org-agenda-check-type t 'agenda 'timeline)
9605 (let* ((day (or (get-text-property (point) 'day)
9606 (error "Don't know which date to open in calendar")))
9607 (date (calendar-gregorian-from-absolute day))
9608 (calendar-move-hook nil)
9609 (view-calendar-holidays-initially nil)
9610 (view-diary-entries-initially nil))
9611 (calendar)
9612 (calendar-goto-date date)))
9614 (defun org-calendar-goto-agenda ()
9615 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
9616 This is a command that has to be installed in `calendar-mode-map'."
9617 (interactive)
9618 (org-agenda-list nil (calendar-absolute-from-gregorian
9619 (calendar-cursor-to-date))
9620 nil))
9622 (defun org-agenda-convert-date ()
9623 (interactive)
9624 (org-agenda-check-type t 'agenda 'timeline)
9625 (let ((day (get-text-property (point) 'day))
9626 date s)
9627 (unless day
9628 (error "Don't know which date to convert"))
9629 (setq date (calendar-gregorian-from-absolute day))
9630 (setq s (concat
9631 "Gregorian: " (calendar-date-string date) "\n"
9632 "ISO: " (calendar-iso-date-string date) "\n"
9633 "Day of Yr: " (calendar-day-of-year-string date) "\n"
9634 "Julian: " (calendar-julian-date-string date) "\n"
9635 "Astron. JD: " (calendar-astro-date-string date)
9636 " (Julian date number at noon UTC)\n"
9637 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
9638 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
9639 "French: " (calendar-french-date-string date) "\n"
9640 "Mayan: " (calendar-mayan-date-string date) "\n"
9641 "Coptic: " (calendar-coptic-date-string date) "\n"
9642 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
9643 "Persian: " (calendar-persian-date-string date) "\n"
9644 "Chinese: " (calendar-chinese-date-string date) "\n"))
9645 (with-output-to-temp-buffer "*Dates*"
9646 (princ s))
9647 (if (fboundp 'fit-window-to-buffer)
9648 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
9650 ;;; Tags
9652 (defun org-scan-tags (action matcher &optional todo-only)
9653 "Scan headline tags with inheritance and produce output ACTION.
9654 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9655 evaluated, testing if a given set of tags qualifies a headline for
9656 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9657 are included in the output."
9658 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9659 (mapconcat 'regexp-quote
9660 (nreverse (cdr (reverse org-todo-keywords)))
9661 "\\|")
9662 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
9663 (props (list 'face nil
9664 'done-face 'org-done
9665 'undone-face nil
9666 'mouse-face 'highlight
9667 'org-not-done-regexp org-not-done-regexp
9668 'keymap org-agenda-keymap
9669 'help-echo
9670 (format "mouse-2 or RET jump to org file %s"
9671 (abbreviate-file-name buffer-file-name))))
9672 (case-fold-search nil)
9673 lspos
9674 tags tags-list tags-alist (llast 0) rtn level category i txt
9675 todo marker)
9676 (save-excursion
9677 (goto-char (point-min))
9678 (when (eq action 'sparse-tree) (org-overview))
9679 (while (re-search-forward re nil t)
9680 (catch :skip
9681 (and (eq action 'agenda) (org-agenda-skip))
9682 (setq todo (if (match-end 1) (match-string 2))
9683 tags (if (match-end 4) (match-string 4)))
9684 (goto-char (setq lspos (1+ (match-beginning 0))))
9685 (setq level (funcall outline-level)
9686 category (org-get-category))
9687 (setq i llast llast level)
9688 ;; remove tag lists from same and sublevels
9689 (while (>= i level)
9690 (when (setq entry (assoc i tags-alist))
9691 (setq tags-alist (delete entry tags-alist)))
9692 (setq i (1- i)))
9693 ;; add the nex tags
9694 (when tags
9695 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9696 tags-alist
9697 (cons (cons level tags) tags-alist)))
9698 ;; compile tags for current headline
9699 (setq tags-list
9700 (if org-use-tag-inheritance
9701 (apply 'append (mapcar 'cdr tags-alist))
9702 tags))
9703 (when (and (or (not todo-only) todo)
9704 (eval matcher)
9705 (or (not org-agenda-skip-archived-trees)
9706 (not (member org-archive-tag tags-list))))
9707 ;; list this headline
9708 (if (eq action 'sparse-tree)
9709 (progn
9710 (org-show-context 'tags-tree))
9711 (setq txt (org-format-agenda-item
9713 (concat
9714 (if org-tags-match-list-sublevels
9715 (make-string (1- level) ?.) "")
9716 (org-get-heading))
9717 category tags-list))
9718 (goto-char lspos)
9719 (setq marker (org-agenda-new-marker))
9720 (org-add-props txt props
9721 'org-marker marker 'org-hd-marker marker 'category category)
9722 (push txt rtn))
9723 ;; if we are to skip sublevels, jump to end of subtree
9724 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9725 (when (and (eq action 'sparse-tree)
9726 (not org-sparse-tree-open-archived-trees))
9727 (org-hide-archived-subtrees (point-min) (point-max)))
9728 (nreverse rtn)))
9730 (defun org-tags-sparse-tree (&optional arg match)
9731 "Create a sparse tree according to tags string MATCH.
9732 MATCH can contain positive and negative selection of tags, like
9733 \"+WORK+URGENT-WITHBOSS\"."
9734 (interactive "P")
9735 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))))
9737 (defun org-make-tags-matcher (match)
9738 "Create the TAGS//TODO matcher form for the selection string MATCH."
9739 (unless match
9740 ;; Get a new match request, with completion
9741 (setq org-last-tags-completion-table
9742 (or org-tag-alist
9743 org-last-tags-completion-table))
9744 (setq match (completing-read
9745 "Match: " 'org-tags-completion-function nil nil nil
9746 'org-tags-history))) ; FIXME: Separate history for this?
9748 ;; Parse the string and create a lisp form
9749 (let ((match0 match)
9750 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|[A-Za-z_@0-9]+\\)")
9751 minus tag mm
9752 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9753 orterms term orlist re-p)
9754 (if (string-match "/+" match)
9755 ;; match contains also a todo-matching request
9756 (setq tagsmatch (substring match 0 (match-beginning 0))
9757 todomatch (substring match (match-end 0)))
9758 ;; only matching tags
9759 (setq tagsmatch match todomatch nil))
9761 ;; Make the tags matcher
9762 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9763 (setq tagsmatcher t)
9764 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9765 (while (setq term (pop orterms))
9766 (while (and (equal (substring term -1) "\\") orterms)
9767 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9768 (while (string-match re term)
9769 (setq minus (and (match-end 1)
9770 (equal (match-string 1 term) "-"))
9771 tag (match-string 2 term)
9772 term (substring term (match-end 0))
9773 re-p (equal (string-to-char tag) ?{)
9774 mm (if re-p
9775 `(org-match-any-p ,(substring tag 1 -1) tags-list)
9776 `(member ,(downcase tag) tags-list))
9777 mm (if minus (list 'not mm) mm))
9778 (push mm tagsmatcher))
9779 (push (if (> (length tagsmatcher) 1)
9780 (cons 'and tagsmatcher)
9781 (car tagsmatcher))
9782 orlist)
9783 (setq tagsmatcher nil))
9784 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
9786 ;; Make the todo matcher
9787 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9788 (setq todomatcher t)
9789 (setq orterms (org-split-string todomatch "|") orlist nil)
9790 (while (setq term (pop orterms))
9791 (while (string-match re term)
9792 (setq minus (and (match-end 1)
9793 (equal (match-string 1 term) "-"))
9794 kwd (match-string 2 term)
9795 re-p (equal (string-to-char kwd) ?{)
9796 term (substring term (match-end 0))
9797 mm (if re-p
9798 `(string-match ,(substring kwd 1 -1) todo)
9799 (list 'equal 'todo kwd))
9800 mm (if minus (list 'not mm) mm))
9801 (push mm todomatcher))
9802 (push (if (> (length todomatcher) 1)
9803 (cons 'and todomatcher)
9804 (car todomatcher))
9805 orlist)
9806 (setq todomatcher nil))
9807 (setq todomatcher (if (> (length orlist) 1)
9808 (cons 'or orlist) (car orlist))))
9810 ;; Return the string and lisp forms of the matcher
9811 (setq matcher (if todomatcher
9812 (list 'and tagsmatcher todomatcher)
9813 tagsmatcher))
9814 (cons match0 matcher)))
9816 (defun org-match-any-p (re list)
9817 "Does re match any element of list?"
9818 (setq list (mapcar (lambda (x) (string-match re x)) list))
9819 (delq nil list))
9821 ;;;###autoload
9822 (defun org-tags-view (&optional todo-only match)
9823 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
9824 The prefix arg TODO-ONLY limits the search to TODO entries."
9825 (interactive "P")
9826 (org-compile-prefix-format 'tags)
9827 (org-set-sorting-strategy 'tags)
9828 (let* ((org-tags-match-list-sublevels
9829 (if todo-only t org-tags-match-list-sublevels))
9830 (win (selected-window))
9831 (completion-ignore-case t)
9832 rtn rtnall files file pos matcher
9833 buffer)
9834 (setq matcher (org-make-tags-matcher match)
9835 match (car matcher) matcher (cdr matcher))
9836 (org-prepare-agenda)
9837 (setq org-agenda-redo-command
9838 (list 'org-tags-view (list 'quote todo-only)
9839 (list 'if 'current-prefix-arg nil match)))
9840 (setq files (org-agenda-files)
9841 rtnall nil)
9842 (while (setq file (pop files))
9843 (catch 'nextfile
9844 (org-check-agenda-file file)
9845 (setq buffer (if (file-exists-p file)
9846 (org-get-agenda-file-buffer file)
9847 (error "No such file %s" file)))
9848 (if (not buffer)
9849 ;; If file does not exist, merror message to agenda
9850 (setq rtn (list
9851 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
9852 rtnall (append rtnall rtn))
9853 (with-current-buffer buffer
9854 (unless (org-mode-p)
9855 (error "Agenda file %s is not in `org-mode'" file))
9856 (setq org-category-table (org-get-category-table))
9857 (save-excursion
9858 (save-restriction
9859 (if org-agenda-restrict
9860 (narrow-to-region org-agenda-restrict-begin
9861 org-agenda-restrict-end)
9862 (widen))
9863 (setq rtn (org-scan-tags 'agenda matcher todo-only))
9864 (setq rtnall (append rtnall rtn))))))))
9865 (insert "Headlines with TAGS match: ")
9866 (add-text-properties (point-min) (1- (point))
9867 (list 'face 'org-level-3))
9868 (setq pos (point))
9869 (insert match "\n")
9870 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
9871 (setq pos (point))
9872 (unless org-agenda-multi
9873 (insert "Press `C-u r' to search again with new search string\n"))
9874 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
9875 (when rtnall
9876 (insert (org-finalize-agenda-entries rtnall) "\n"))
9877 (goto-char (point-min))
9878 (org-fit-agenda-window)
9879 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
9880 (org-finalize-agenda)
9881 (setq buffer-read-only t)
9882 (if (not org-select-agenda-window) (select-window win))))
9884 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9885 (defvar org-tags-overlay (org-make-overlay 1 1))
9886 (org-detach-overlay org-tags-overlay)
9888 (defun org-set-tags (&optional arg just-align)
9889 "Set the tags for the current headline.
9890 With prefix ARG, realign all tags in headings in the current buffer."
9891 (interactive "P")
9892 (let* ((re (concat "^" outline-regexp))
9893 (current (org-get-tags))
9894 table current-tags inherited-tags ; computed below when needed
9895 tags p0 c0 c1 rpl)
9896 (if arg
9897 (save-excursion
9898 (goto-char (point-min))
9899 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
9900 (while (re-search-forward re nil t)
9901 (org-set-tags nil t)
9902 (end-of-line 1)))
9903 (message "All tags realigned to column %d" org-tags-column))
9904 (if just-align
9905 (setq tags current)
9906 ;; Get a new set of tags from the user
9907 (setq table (or org-tag-alist (org-get-buffer-tags))
9908 org-last-tags-completion-table table
9909 current-tags (org-split-string current ":")
9910 inherited-tags (nreverse
9911 (nthcdr (length current-tags)
9912 (nreverse (org-get-tags-at))))
9913 tags
9914 (if (or (eq t org-use-fast-tag-selection)
9915 (and org-use-fast-tag-selection
9916 (delq nil (mapcar 'cdr table))))
9917 (org-fast-tag-selection current-tags inherited-tags table)
9918 (let ((org-add-colon-after-tag-completion t))
9919 (org-trim
9920 (completing-read "Tags: " 'org-tags-completion-function
9921 nil nil current 'org-tags-history)))))
9922 (while (string-match "[-+&]+" tags)
9923 ;; No boolean logic, just a list
9924 (setq tags (replace-match ":" t t tags))))
9925 (if (string-match "\\`[\t ]*\\'" tags)
9926 (setq tags "")
9927 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9928 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9930 ;; Insert new tags at the correct column
9931 (beginning-of-line 1)
9932 (if (re-search-forward
9933 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9934 (point-at-eol) t)
9935 (progn
9936 (if (equal tags "")
9937 (setq rpl "")
9938 (goto-char (match-beginning 0))
9939 (setq c0 (current-column) p0 (point)
9940 c1 (max (1+ c0) (if (> org-tags-column 0)
9941 org-tags-column
9942 (- (- org-tags-column) (length tags))))
9943 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9944 (replace-match rpl)
9945 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
9946 tags)
9947 (error "Tags alignment failed")))))
9949 (defun org-tags-completion-function (string predicate &optional flag)
9950 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9951 (confirm (lambda (x) (stringp (car x)))))
9952 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9953 (setq s1 (match-string 1 string)
9954 s2 (match-string 2 string))
9955 (setq s1 "" s2 string))
9956 (cond
9957 ((eq flag nil)
9958 ;; try completion
9959 (setq rtn (try-completion s2 ctable confirm))
9960 (if (stringp rtn)
9961 (concat s1 s2 (substring rtn (length s2))
9962 (if (and org-add-colon-after-tag-completion
9963 (assoc rtn ctable))
9964 ":" "")))
9966 ((eq flag t)
9967 ;; all-completions
9968 (all-completions s2 ctable confirm)
9970 ((eq flag 'lambda)
9971 ;; exact match?
9972 (assoc s2 ctable)))
9975 (defun org-fast-tag-insert (kwd tags face &optional end)
9976 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9977 (insert (format "%-12s" (concat kwd ":"))
9978 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9979 (or end "")))
9981 (defun org-fast-tag-show-exit (flag)
9982 (save-excursion
9983 (goto-line 3)
9984 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9985 (replace-match ""))
9986 (when flag
9987 (end-of-line 1)
9988 (move-to-column (- (window-width) 19) t)
9989 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9991 (defun org-set-current-tags-overlay (current prefix)
9992 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9993 (if (featurep 'xemacs)
9994 (org-overlay-display org-tags-overlay (concat prefix s)
9995 'secondary-selection)
9996 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9997 (org-overlay-display org-tags-overlay (concat prefix s)))))
9999 (defun org-fast-tag-selection (current inherited table)
10000 "Fast tag selection with single keys.
10001 CURRENT is the current list of tags in the headline, INHERITED is the
10002 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10003 possibly with grouping information.
10004 If the keys are nil, a-z are automatically assigned.
10005 Returns the new tags string, or nil to not change the current settings."
10006 (let* ((maxlen (apply 'max (mapcar
10007 (lambda (x)
10008 (if (stringp (car x)) (string-width (car x)) 0))
10009 table)))
10010 (buf (current-buffer))
10011 (buffer-tags nil)
10012 (fwidth (+ maxlen 3 1 3))
10013 (ncol (/ (- (window-width) 4) fwidth))
10014 (i-face 'org-done)
10015 (c-face 'org-tag)
10016 tg cnt e c char c1 c2 ntable tbl rtn
10017 ov-start ov-end ov-prefix
10018 (exit-after-next org-fast-tag-selection-single-key)
10019 groups ingroup)
10020 (save-excursion
10021 (beginning-of-line 1)
10022 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10023 (setq ov-start (match-beginning 1)
10024 ov-end (match-end 1)
10025 ov-prefix "")
10026 (setq ov-start (1- (point-at-eol))
10027 ov-end (1+ ov-start))
10028 (skip-chars-forward "^\n\r")
10029 (setq ov-prefix
10030 (concat
10031 (buffer-substring (1- (point)) (point))
10032 (if (> (current-column) org-tags-column)
10034 (make-string (- org-tags-column (current-column)) ?\ ))))))
10035 (org-move-overlay org-tags-overlay ov-start ov-end)
10036 (save-window-excursion
10037 ;; FIXME: would it be better to keep the other windows?
10038 (delete-other-windows)
10039 (split-window-vertically)
10040 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
10041 (erase-buffer)
10042 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10043 (org-fast-tag-insert "Current" current c-face "\n\n")
10044 (org-fast-tag-show-exit exit-after-next)
10045 (org-set-current-tags-overlay current ov-prefix)
10046 (setq tbl table char ?a cnt 0)
10047 (while (setq e (pop tbl))
10048 (cond
10049 ((equal e '(:startgroup))
10050 (push '() groups) (setq ingroup t)
10051 (when (not (= cnt 0))
10052 (setq cnt 0)
10053 (insert "\n"))
10054 (insert "{ "))
10055 ((equal e '(:endgroup))
10056 (setq ingroup nil cnt 0)
10057 (insert "}\n"))
10059 (setq tg (car e) c2 nil)
10060 (if (cdr e)
10061 (setq c (cdr e))
10062 ;; automatically assign a character.
10063 (setq c1 (string-to-char
10064 (downcase (substring
10065 tg (if (= (string-to-char tg) ?@) 1 0)))))
10066 (if (or (rassoc c1 ntable) (rassoc c1 table))
10067 (while (or (rassoc char ntable) (rassoc char table))
10068 (setq char (1+ char)))
10069 (setq c2 c1))
10070 (setq c (or c2 char)))
10071 (if ingroup (push tg (car groups)))
10072 (setq tg (org-add-props tg nil 'face
10073 (cond
10074 ((member tg current) c-face)
10075 ((member tg inherited) i-face)
10076 (t nil))))
10077 (if (and (= cnt 0) (not ingroup)) (insert " "))
10078 (insert "[" c "] " tg (make-string
10079 (- fwidth 4 (length tg)) ?\ ))
10080 (push (cons tg c) ntable)
10081 (when (= (setq cnt (1+ cnt)) ncol)
10082 (insert "\n")
10083 (if ingroup (insert " "))
10084 (setq cnt 0)))))
10085 (setq ntable (nreverse ntable))
10086 (insert "\n")
10087 (goto-char (point-min))
10088 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
10089 (setq rtn
10090 (catch 'exit
10091 (while t
10092 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [C-c]: multi%s"
10093 (if groups " [!] no groups" ""))
10094 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10095 (cond
10096 ((= c ?\r) (throw 'exit t))
10097 ((= c ?!)
10098 (setq groups nil)
10099 (goto-char (point-min))
10100 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10101 ((= c ?\C-c)
10102 (org-fast-tag-show-exit
10103 (setq exit-after-next (not exit-after-next))))
10104 ((or (= c ?\C-g)
10105 (and (= c ?q) (not (rassoc c ntable))))
10106 (org-detach-overlay org-tags-overlay)
10107 (setq quit-flag t))
10108 ((= c ?\ )
10109 (setq current nil)
10110 (if exit-after-next (setq exit-after-next 'now)))
10111 ((= c ?\t)
10112 (condition-case nil
10113 (setq tg (completing-read
10114 "Tag: "
10115 (or buffer-tags
10116 (with-current-buffer buf
10117 (org-get-buffer-tags)))))
10118 (quit (setq tg "")))
10119 (when (string-match "\\S-" tg)
10120 (add-to-list 'buffer-tags (list tg))
10121 (if (member tg current)
10122 (setq current (delete tg current))
10123 (push tg current)))
10124 (if exit-after-next (setq exit-after-next 'now)))
10125 ((setq e (rassoc c ntable) tg (car e))
10126 (if (member tg current)
10127 (setq current (delete tg current))
10128 (loop for g in groups do
10129 (if (member tg g)
10130 (mapcar (lambda (x)
10131 (setq current (delete x current)))
10132 g)))
10133 (push tg current))
10134 (if exit-after-next (setq exit-after-next 'now))))
10136 ;; Create a sorted list
10137 (setq current
10138 (sort current
10139 (lambda (a b)
10140 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10141 (if (eq exit-after-next 'now) (throw 'exit t))
10142 (goto-char (point-min))
10143 (beginning-of-line 2)
10144 (delete-region (point) (point-at-eol))
10145 (org-fast-tag-insert "Current" current c-face)
10146 (org-set-current-tags-overlay current ov-prefix)
10147 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
10148 (setq tg (match-string 1))
10149 (add-text-properties (match-beginning 1) (match-end 1)
10150 (list 'face
10151 (cond
10152 ((member tg current) c-face)
10153 ((member tg inherited) i-face)
10154 (t nil)))))
10155 (goto-char (point-min)))))
10156 (org-detach-overlay org-tags-overlay)
10157 (if rtn
10158 (mapconcat 'identity current ":")
10159 nil))))
10161 (defun org-get-tags ()
10162 "Get the TAGS string in the current headline."
10163 (unless (org-on-heading-p t)
10164 (error "Not on a heading"))
10165 (save-excursion
10166 (beginning-of-line 1)
10167 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10168 (org-match-string-no-properties 1)
10169 "")))
10171 (defun org-get-buffer-tags ()
10172 "Get a table of all tags used in the buffer, for completion."
10173 (let (tags)
10174 (save-excursion
10175 (goto-char (point-min))
10176 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
10177 (mapc (lambda (x) (add-to-list 'tags x))
10178 (org-split-string (org-match-string-no-properties 1) ":"))))
10179 (mapcar 'list tags)))
10181 ;;; Link Stuff
10183 (defvar org-create-file-search-functions nil
10184 "List of functions to construct the right search string for a file link.
10185 These functions are called in turn with point at the location to
10186 which the link should point.
10188 A function in the hook should first test if it would like to
10189 handle this file type, for example by checking the major-mode or
10190 the file extension. If it decides not to handle this file, it
10191 should just return nil to give other functions a chance. If it
10192 does handle the file, it must return the search string to be used
10193 when following the link. The search string will be part of the
10194 file link, given after a double colon, and `org-open-at-point'
10195 will automatically search for it. If special measures must be
10196 taken to make the search successful, another function should be
10197 added to the companion hook `org-execute-file-search-functions',
10198 which see.
10200 A function in this hook may also use `setq' to set the variable
10201 `description' to provide a suggestion for the descriptive text to
10202 be used for this link when it gets inserted into an Org-mode
10203 buffer with \\[org-insert-link].")
10205 (defvar org-execute-file-search-functions nil
10206 "List of functions to execute a file search triggered by a link.
10208 Functions added to this hook must accept a single argument, the
10209 search string that was part of the file link, the part after the
10210 double colon. The function must first check if it would like to
10211 handle this search, for example by checking the major-mode or the
10212 file extension. If it decides not to handle this search, it
10213 should just return nil to give other functions a chance. If it
10214 does handle the search, it must return a non-nil value to keep
10215 other functions from trying.
10217 Each function can access the current prefix argument through the
10218 variable `current-prefix-argument'. Note that a single prefix is
10219 used to force opening a link in Emacs, so it may be good to only
10220 use a numeric or double prefix to guide the search function.
10222 In case this is needed, a function in this hook can also restore
10223 the window configuration before `org-open-at-point' was called using:
10225 (set-window-configuration org-window-config-before-follow-link)")
10227 (defun org-find-file-at-mouse (ev)
10228 "Open file link or URL at mouse."
10229 (interactive "e")
10230 (mouse-set-point ev)
10231 (org-open-at-point 'in-emacs))
10233 (defun org-open-at-mouse (ev)
10234 "Open file link or URL at mouse."
10235 (interactive "e")
10236 (mouse-set-point ev)
10237 (org-open-at-point))
10239 (defvar org-window-config-before-follow-link nil
10240 "The window configuration before following a link.
10241 This is saved in case the need arises to restore it.")
10243 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
10244 (defun org-open-at-point (&optional in-emacs)
10245 "Open link at or after point.
10246 If there is no link at point, this function will search forward up to
10247 the end of the current subtree.
10248 Normally, files will be opened by an appropriate application. If the
10249 optional argument IN-EMACS is non-nil, Emacs will visit the file."
10250 (interactive "P")
10251 (setq org-window-config-before-follow-link (current-window-configuration))
10252 (org-remove-occur-highlights nil nil t)
10253 (if (org-at-timestamp-p t)
10254 (org-follow-timestamp-link)
10255 (let (type path link line search (pos (point)))
10256 (catch 'match
10257 (save-excursion
10258 (skip-chars-forward "^]\n\r")
10259 (when (and (re-search-backward "\\[\\[" nil t)
10260 (looking-at org-bracket-link-regexp)
10261 (<= (match-beginning 0) pos)
10262 (>= (match-end 0) pos))
10263 (setq link (org-link-unescape (org-match-string-no-properties 1)))
10264 (while (string-match " *\n *" link)
10265 (setq link (replace-match " " t t link)))
10266 (setq link (org-link-expand-abbrev link))
10267 (if (string-match org-link-re-with-space2 link)
10268 (setq type (match-string 1 link)
10269 path (match-string 2 link))
10270 (setq type "thisfile"
10271 path link))
10272 (throw 'match t)))
10274 (when (get-text-property (point) 'org-linked-text)
10275 (setq type "thisfile"
10276 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10277 (1+ (point)) (point))
10278 path (buffer-substring
10279 (previous-single-property-change pos 'org-linked-text)
10280 (next-single-property-change pos 'org-linked-text)))
10281 (throw 'match t))
10283 (save-excursion
10284 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
10285 (if (equal (char-before) ?<) (backward-char 1))
10286 (when (or (looking-at org-angle-link-re)
10287 (looking-at org-plain-link-re)
10288 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
10289 (re-search-forward org-plain-link-re (point-at-eol) t))
10290 (<= (match-beginning 0) pos)
10291 (>= (match-end 0) pos)))
10292 (setq type (match-string 1)
10293 path (match-string 2))
10294 (throw 'match t)))
10295 (save-excursion
10296 (skip-chars-backward "^ \t\n\r")
10297 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
10298 (setq type "tags"
10299 path (match-string 1))
10300 (while (string-match ":" path)
10301 (setq path (replace-match "+" t t path)))
10302 (throw 'match t)))
10303 (save-excursion
10304 (skip-chars-backward "a-zA-Z_")
10305 (when (and (memq 'camel org-activate-links)
10306 (looking-at org-camel-regexp))
10307 (setq type "camel" path (match-string 0))
10308 (if (equal (char-before) ?*)
10309 (setq path (concat "*" path))))
10310 (throw 'match t)))
10311 (unless path
10312 (error "No link found"))
10313 ;; Remove any trailing spaces in path
10314 (if (string-match " +\\'" path)
10315 (setq path (replace-match "" t t path)))
10317 (cond
10319 ((equal type "mailto")
10320 (let ((cmd (car org-link-mailto-program))
10321 (args (cdr org-link-mailto-program)) args1
10322 (address path) (subject "") a)
10323 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10324 (setq address (match-string 1 path)
10325 subject (org-link-escape (match-string 2 path))))
10326 (while args
10327 (cond
10328 ((not (stringp (car args))) (push (pop args) args1))
10329 (t (setq a (pop args))
10330 (if (string-match "%a" a)
10331 (setq a (replace-match address t t a)))
10332 (if (string-match "%s" a)
10333 (setq a (replace-match subject t t a)))
10334 (push a args1))))
10335 (apply cmd (nreverse args1))))
10337 ((member type '("http" "https" "ftp" "news"))
10338 (browse-url (concat type ":" path)))
10340 ((string= type "tags")
10341 (org-tags-view in-emacs path))
10342 ((or (string= type "camel")
10343 (string= type "thisfile"))
10344 (if in-emacs
10345 (switch-to-buffer-other-window
10346 (org-get-buffer-for-internal-link (current-buffer)))
10347 (org-mark-ring-push))
10348 (org-link-search
10349 path
10350 (cond ((equal in-emacs '(4)) 'occur)
10351 ((equal in-emacs '(16)) 'org-occur)
10352 (t nil))))
10354 ((string= type "file")
10355 (if (string-match "::\\([0-9]+\\)\\'" path)
10356 (setq line (string-to-number (match-string 1 path))
10357 path (substring path 0 (match-beginning 0)))
10358 (if (string-match "::\\(.+\\)\\'" path)
10359 (setq search (match-string 1 path)
10360 path (substring path 0 (match-beginning 0)))))
10361 (org-open-file path in-emacs line search))
10363 ((string= type "news")
10364 (org-follow-gnus-link path))
10366 ((string= type "bbdb")
10367 (org-follow-bbdb-link path))
10369 ((string= type "info")
10370 (org-follow-info-link path))
10372 ((string= type "gnus")
10373 (let (group article)
10374 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10375 (error "Error in Gnus link"))
10376 (setq group (match-string 1 path)
10377 article (match-string 3 path))
10378 (org-follow-gnus-link group article)))
10380 ((string= type "vm")
10381 (let (folder article)
10382 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10383 (error "Error in VM link"))
10384 (setq folder (match-string 1 path)
10385 article (match-string 3 path))
10386 ;; in-emacs is the prefix arg, will be interpreted as read-only
10387 (org-follow-vm-link folder article in-emacs)))
10389 ((string= type "wl")
10390 (let (folder article)
10391 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10392 (error "Error in Wanderlust link"))
10393 (setq folder (match-string 1 path)
10394 article (match-string 3 path))
10395 (org-follow-wl-link folder article)))
10397 ((string= type "mhe")
10398 (let (folder article)
10399 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10400 (error "Error in MHE link"))
10401 (setq folder (match-string 1 path)
10402 article (match-string 3 path))
10403 (org-follow-mhe-link folder article)))
10405 ((string= type "rmail")
10406 (let (folder article)
10407 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10408 (error "Error in RMAIL link"))
10409 (setq folder (match-string 1 path)
10410 article (match-string 3 path))
10411 (org-follow-rmail-link folder article)))
10413 ((string= type "shell")
10414 (let ((cmd path))
10415 (while (string-match "@{" cmd) ; FIXME: not needed for [[]] links
10416 (setq cmd (replace-match "<" t t cmd)))
10417 (while (string-match "@}" cmd) ; FIXME: not needed for [[]] links
10418 (setq cmd (replace-match ">" t t cmd)))
10419 (if (or (not org-confirm-shell-link-function)
10420 (funcall org-confirm-shell-link-function
10421 (format "Execute \"%s\" in shell? "
10422 (org-add-props cmd nil
10423 'face 'org-warning))))
10424 (progn
10425 (message "Executing %s" cmd)
10426 (shell-command cmd))
10427 (error "Abort"))))
10429 ((string= type "elisp")
10430 (let ((cmd path))
10431 (if (or (not org-confirm-elisp-link-function)
10432 (funcall org-confirm-elisp-link-function
10433 (format "Execute \"%s\" as elisp? "
10434 (org-add-props cmd nil
10435 'face 'org-warning))))
10436 (message "%s => %s" cmd (eval (read cmd)))
10437 (error "Abort"))))
10440 (browse-url-at-point))))))
10442 (defun org-link-expand-abbrev (link)
10443 "Apply replacements as defined in `org-link-abbrev-alist."
10444 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
10445 (let* ((key (match-string 1 link))
10446 (as (or (assoc key org-link-abbrev-alist-local)
10447 (assoc key org-link-abbrev-alist)))
10448 (tag (and (match-end 2) (match-string 3 link)))
10449 rpl)
10450 (if (not as)
10451 link
10452 (setq rpl (cdr as))
10453 (cond
10454 ((symbolp rpl) (funcall rpl tag))
10455 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10456 (t (concat rpl tag)))))
10457 link))
10459 (defun org-link-search (s &optional type)
10460 "Search for a link search option.
10461 When S is a CamelCaseWord, search for a target, or for a sentence containing
10462 the words. If S is surrounded by forward slashes, it is interpreted as a
10463 regular expression. In org-mode files, this will create an `org-occur'
10464 sparse tree. In ordinary files, `occur' will be used to list matches.
10465 If the current buffer is in `dired-mode', grep will be used to search
10466 in all files."
10467 (let ((case-fold-search t)
10468 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10469 (pos (point))
10470 (pre "") (post "")
10471 words re0 re1 re2 re3 re4 re5 re2a reall camel)
10472 (cond
10473 ;; First check if there are any special
10474 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10475 ;; Now try the builtin stuff
10476 ((save-excursion
10477 (goto-char (point-min))
10478 (and
10479 (re-search-forward
10480 (concat "<<" (regexp-quote s0) ">>") nil t)
10481 (setq pos (match-beginning 0))))
10482 ;; There is an exact target for this
10483 (goto-char pos))
10484 ((string-match "^/\\(.*\\)/$" s)
10485 ;; A regular expression
10486 (cond
10487 ((org-mode-p)
10488 (org-occur (match-string 1 s)))
10489 ;;((eq major-mode 'dired-mode)
10490 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10491 (t (org-do-occur (match-string 1 s)))))
10492 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
10494 ;; A camel or a normal search string
10495 (when (equal (string-to-char s) ?*)
10496 ;; Anchor on headlines, post may include tags.
10497 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10498 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
10499 s (substring s 1)))
10500 (remove-text-properties
10501 0 (length s)
10502 '(face nil mouse-face nil keymap nil fontified nil) s)
10503 ;; Make a series of regular expressions to find a match
10504 (setq words
10505 (if camel
10506 (org-camel-to-words s)
10507 (org-split-string s "[ \n\r\t]+"))
10508 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10509 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
10510 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10511 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10512 re1 (concat pre re2 post)
10513 re3 (concat pre re4 post)
10514 re5 (concat pre ".*" re4)
10515 re2 (concat pre re2)
10516 re2a (concat pre re2a)
10517 re4 (concat pre re4)
10518 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10519 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10520 re5 "\\)"
10522 (cond
10523 ((eq type 'org-occur) (org-occur reall))
10524 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10525 (t (goto-char (point-min))
10526 (if (or (org-search-not-link re0 nil t)
10527 (org-search-not-link re1 nil t)
10528 (org-search-not-link re2 nil t)
10529 (org-search-not-link re2a nil t)
10530 (org-search-not-link re3 nil t)
10531 (org-search-not-link re4 nil t)
10532 (org-search-not-link re5 nil t)
10534 (goto-char (match-beginning 1))
10535 (goto-char pos)
10536 (error "No match")))))
10538 ;; Normal string-search
10539 (goto-char (point-min))
10540 (if (search-forward s nil t)
10541 (goto-char (match-beginning 0))
10542 (error "No match"))))
10543 (and (org-mode-p) (org-show-context 'link-search))))
10545 (defun org-search-not-link (&rest args)
10546 "Execute `re-search-forward', but only accept matches that are not a link."
10547 (catch 'exit
10548 (let (p1)
10549 (while (apply 're-search-forward args)
10550 (setq p1 (point))
10551 (if (not (save-match-data
10552 (and (re-search-backward "\\[\\[" nil t)
10553 (looking-at org-bracket-link-regexp)
10554 (<= (match-beginning 0) p1)
10555 (>= (match-end 0) p1))))
10556 (progn (goto-char (match-end 0))
10557 (throw 'exit (point)))
10558 (goto-char (match-end 0)))))))
10560 (defun org-get-buffer-for-internal-link (buffer)
10561 "Return a buffer to be used for displaying the link target of internal links."
10562 (cond
10563 ((not org-display-internal-link-with-indirect-buffer)
10564 buffer)
10565 ((string-match "(Clone)$" (buffer-name buffer))
10566 (message "Buffer is already a clone, not making another one")
10567 ;; we also do not modify visibility in this case
10568 buffer)
10569 (t ; make a new indirect buffer for displaying the link
10570 (let* ((bn (buffer-name buffer))
10571 (ibn (concat bn "(Clone)"))
10572 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10573 (with-current-buffer ib (org-overview))
10574 ib))))
10576 (defun org-do-occur (regexp &optional cleanup)
10577 "Call the Emacs command `occur'.
10578 If CLEANUP is non-nil, remove the printout of the regular expression
10579 in the *Occur* buffer. This is useful if the regex is long and not useful
10580 to read."
10581 (occur regexp)
10582 (when cleanup
10583 (let ((cwin (selected-window)) win beg end)
10584 (when (setq win (get-buffer-window "*Occur*"))
10585 (select-window win))
10586 (goto-char (point-min))
10587 (when (re-search-forward "match[a-z]+" nil t)
10588 (setq beg (match-end 0))
10589 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10590 (setq end (1- (match-beginning 0)))))
10591 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10592 (goto-char (point-min))
10593 (select-window cwin))))
10595 (defvar org-mark-ring nil
10596 "Mark ring for positions before jumps in Org-mode.")
10597 (defvar org-mark-ring-last-goto nil
10598 "Last position in the mark ring used to go back.")
10599 ;; Fill and close the ring
10600 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10601 (loop for i from 1 to org-mark-ring-length do
10602 (push (make-marker) org-mark-ring))
10603 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10604 org-mark-ring)
10606 (defun org-mark-ring-push (&optional pos buffer)
10607 "Put the current position or POS into the mark ring and rotate it."
10608 (interactive)
10609 (setq pos (or pos (point)))
10610 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10611 (move-marker (car org-mark-ring)
10612 (or pos (point))
10613 (or buffer (current-buffer)))
10614 (message
10615 (substitute-command-keys
10616 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10618 (defun org-mark-ring-goto (&optional n)
10619 "Jump to the previous position in the mark ring.
10620 With prefix arg N, jump back that many stored positions. When
10621 called several times in succession, walk through the entire ring.
10622 Org-mode commands jumping to a different position in the current file,
10623 or to another Org-mode file, automatically push the old position
10624 onto the ring."
10625 (interactive "p")
10626 (let (p m)
10627 (if (eq last-command this-command)
10628 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10629 (setq p org-mark-ring))
10630 (setq org-mark-ring-last-goto p)
10631 (setq m (car p))
10632 (switch-to-buffer (marker-buffer m))
10633 (goto-char m)
10634 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10636 (defun org-camel-to-words (s)
10637 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
10638 (let ((case-fold-search nil)
10639 words)
10640 (while (string-match "[a-z][A-Z]" s)
10641 (push (substring s 0 (1+ (match-beginning 0))) words)
10642 (setq s (substring s (1+ (match-beginning 0)))))
10643 (nreverse (cons s words))))
10645 (defun org-remove-angle-brackets (s)
10646 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10647 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10649 (defun org-add-angle-brackets (s)
10650 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10651 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10654 (defun org-follow-timestamp-link ()
10655 (cond
10656 ((org-at-date-range-p t)
10657 (let ((org-agenda-start-on-weekday)
10658 (t1 (match-string 1))
10659 (t2 (match-string 2)))
10660 (setq t1 (time-to-days (org-time-string-to-time t1))
10661 t2 (time-to-days (org-time-string-to-time t2)))
10662 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10663 ((org-at-timestamp-p t)
10664 (org-agenda-list nil (time-to-days (org-time-string-to-time
10665 (substring (match-string 1) 0 10)))
10667 (t (error "This should not happen"))))
10670 (defun org-follow-bbdb-link (name)
10671 "Follow a BBDB link to NAME."
10672 (require 'bbdb)
10673 (let ((inhibit-redisplay t)
10674 (bbdb-electric-p nil))
10675 (catch 'exit
10676 ;; Exact match on name
10677 (bbdb-name (concat "\\`" name "\\'") nil)
10678 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10679 ;; Exact match on name
10680 (bbdb-company (concat "\\`" name "\\'") nil)
10681 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10682 ;; Partial match on name
10683 (bbdb-name name nil)
10684 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10685 ;; Partial match on company
10686 (bbdb-company name nil)
10687 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10688 ;; General match including network address and notes
10689 (bbdb name nil)
10690 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10691 (delete-window (get-buffer-window "*BBDB*"))
10692 (error "No matching BBDB record")))))
10695 (defun org-follow-info-link (name)
10696 "Follow an info file & node link to NAME."
10697 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10698 (string-match "\\(.*\\)" name))
10699 (progn
10700 (require 'info)
10701 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10702 (Info-find-node (match-string 1 name) (match-string 2 name))
10703 (Info-find-node (match-string 1 name) "Top")))
10704 (message (concat "Could not open: " name))))
10706 (defun org-follow-gnus-link (&optional group article)
10707 "Follow a Gnus link to GROUP and ARTICLE."
10708 (require 'gnus)
10709 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10710 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10711 (if group (gnus-fetch-group group))
10712 (if article
10713 (or (gnus-summary-goto-article article nil 'force)
10714 (if (fboundp 'gnus-summary-insert-cached-articles)
10715 (progn
10716 (gnus-summary-insert-cached-articles)
10717 (gnus-summary-goto-article article nil 'force))
10718 (message "Message could not be found.")))))
10720 (defun org-follow-vm-link (&optional folder article readonly)
10721 "Follow a VM link to FOLDER and ARTICLE."
10722 (require 'vm)
10723 (setq article (org-add-angle-brackets article))
10724 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10725 ;; ange-ftp or efs or tramp access
10726 (let ((user (or (match-string 1 folder) (user-login-name)))
10727 (host (match-string 2 folder))
10728 (file (match-string 3 folder)))
10729 (cond
10730 ((featurep 'tramp)
10731 ;; use tramp to access the file
10732 (if (featurep 'xemacs)
10733 (setq folder (format "[%s@%s]%s" user host file))
10734 (setq folder (format "/%s@%s:%s" user host file))))
10736 ;; use ange-ftp or efs
10737 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10738 (setq folder (format "/%s@%s:%s" user host file))))))
10739 (when folder
10740 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10741 (sit-for 0.1)
10742 (when article
10743 (vm-select-folder-buffer)
10744 (widen)
10745 (let ((case-fold-search t))
10746 (goto-char (point-min))
10747 (if (not (re-search-forward
10748 (concat "^" "message-id: *" (regexp-quote article))))
10749 (error "Could not find the specified message in this folder"))
10750 (vm-isearch-update)
10751 (vm-isearch-narrow)
10752 (vm-beginning-of-message)
10753 (vm-summarize)))))
10755 (defun org-follow-wl-link (folder article)
10756 "Follow a Wanderlust link to FOLDER and ARTICLE."
10757 (setq article (org-add-angle-brackets article))
10758 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
10759 (if article (wl-summary-jump-to-msg-by-message-id article))
10760 (wl-summary-redisplay))
10762 (defun org-follow-rmail-link (folder article)
10763 "Follow an RMAIL link to FOLDER and ARTICLE."
10764 (setq article (org-add-angle-brackets article))
10765 (let (message-number)
10766 (save-excursion
10767 (save-window-excursion
10768 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10769 (setq message-number
10770 (save-restriction
10771 (widen)
10772 (goto-char (point-max))
10773 (if (re-search-backward
10774 (concat "^Message-ID:\\s-+" (regexp-quote
10775 (or article "")))
10776 nil t)
10777 (rmail-what-message))))))
10778 (if message-number
10779 (progn
10780 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10781 (rmail-show-message message-number)
10782 message-number)
10783 (error "Message not found"))))
10785 ;; mh-e integration based on planner-mode
10786 (defun org-mhe-get-message-real-folder ()
10787 "Return the name of the current message real folder, so if you use
10788 sequences, it will now work."
10789 (save-excursion
10790 (let* ((folder
10791 (if (equal major-mode 'mh-folder-mode)
10792 mh-current-folder
10793 ;; Refer to the show buffer
10794 mh-show-folder-buffer))
10795 (end-index
10796 (if (boundp 'mh-index-folder)
10797 (min (length mh-index-folder) (length folder))))
10799 ;; a simple test on mh-index-data does not work, because
10800 ;; mh-index-data is always nil in a show buffer.
10801 (if (and (boundp 'mh-index-folder)
10802 (string= mh-index-folder (substring folder 0 end-index)))
10803 (if (equal major-mode 'mh-show-mode)
10804 (save-window-excursion
10805 (when (buffer-live-p (get-buffer folder))
10806 (progn
10807 (pop-to-buffer folder)
10808 (org-mhe-get-message-folder-from-index)
10811 (org-mhe-get-message-folder-from-index)
10813 folder
10817 (defun org-mhe-get-message-folder-from-index ()
10818 "Returns the name of the message folder in a index folder buffer."
10819 (save-excursion
10820 (mh-index-previous-folder)
10821 (re-search-forward "^\\(+.*\\)$" nil t)
10822 (message (match-string 1))))
10824 (defun org-mhe-get-message-folder ()
10825 "Return the name of the current message folder. Be careful if you
10826 use sequences."
10827 (save-excursion
10828 (if (equal major-mode 'mh-folder-mode)
10829 mh-current-folder
10830 ;; Refer to the show buffer
10831 mh-show-folder-buffer)))
10833 (defun org-mhe-get-message-num ()
10834 "Return the number of the current message. Be careful if you
10835 use sequences."
10836 (save-excursion
10837 (if (equal major-mode 'mh-folder-mode)
10838 (mh-get-msg-num nil)
10839 ;; Refer to the show buffer
10840 (mh-show-buffer-message-number))))
10842 (defun org-mhe-get-header (header)
10843 "Return a header of the message in folder mode. This will create a
10844 show buffer for the corresponding message. If you have a more clever
10845 idea..."
10846 (let* ((folder (org-mhe-get-message-folder))
10847 (num (org-mhe-get-message-num))
10848 (buffer (get-buffer-create (concat "show-" folder)))
10849 (header-field))
10850 (with-current-buffer buffer
10851 (mh-display-msg num folder)
10852 (if (equal major-mode 'mh-folder-mode)
10853 (mh-header-display)
10854 (mh-show-header-display))
10855 (set-buffer buffer)
10856 (setq header-field (mh-get-header-field header))
10857 (if (equal major-mode 'mh-folder-mode)
10858 (mh-show)
10859 (mh-show-show))
10860 header-field)))
10862 (defun org-follow-mhe-link (folder article)
10863 "Follow an MHE link to FOLDER and ARTICLE.
10864 If ARTICLE is nil FOLDER is shown. If the configuration variable
10865 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10866 ARTICLE is searched in all folders. Indexed searches (swish++,
10867 namazu, and others supported by MH-E) will always search in all
10868 folders."
10869 (require 'mh-e)
10870 (require 'mh-search)
10871 (require 'mh-utils)
10872 (mh-find-path)
10873 (if (not article)
10874 (mh-visit-folder (mh-normalize-folder-name folder))
10875 (setq article (org-add-angle-brackets article))
10876 (mh-search-choose)
10877 (if (equal mh-searcher 'pick)
10878 (progn
10879 (mh-search folder (list "--message-id" article))
10880 (when (and org-mhe-search-all-folders
10881 (not (org-mhe-get-message-real-folder)))
10882 (kill-this-buffer)
10883 (mh-search "+" (list "--message-id" article))))
10884 (mh-search "+" article))
10885 (if (org-mhe-get-message-real-folder)
10886 (mh-show-msg 1)
10887 (kill-this-buffer)
10888 (error "Message not found"))))
10890 ;; BibTeX links
10892 ;; Use the custom search meachnism to construct and use search strings for
10893 ;; file links to BibTeX database entries.
10895 (defun org-create-file-search-in-bibtex ()
10896 "Create the search string and description for a BibTeX database entry."
10897 (when (eq major-mode 'bibtex-mode)
10898 ;; yes, we want to construct this search string.
10899 ;; Make a good description for this entry, using names, year and the title
10900 ;; Put it into the `description' variable which is dynamically scoped.
10901 (let ((bibtex-autokey-names 1)
10902 (bibtex-autokey-names-stretch 1)
10903 (bibtex-autokey-name-case-convert-function 'identity)
10904 (bibtex-autokey-name-separator " & ")
10905 (bibtex-autokey-additional-names " et al.")
10906 (bibtex-autokey-year-length 4)
10907 (bibtex-autokey-name-year-separator " ")
10908 (bibtex-autokey-titlewords 3)
10909 (bibtex-autokey-titleword-separator " ")
10910 (bibtex-autokey-titleword-case-convert-function 'identity)
10911 (bibtex-autokey-titleword-length 'infty)
10912 (bibtex-autokey-year-title-separator ": "))
10913 (setq description (bibtex-generate-autokey)))
10914 ;; Now parse the entry, get the key and return it.
10915 (save-excursion
10916 (bibtex-beginning-of-entry)
10917 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10919 (defun org-execute-file-search-in-bibtex (s)
10920 "Find the link search string S as a key for a database entry."
10921 (when (eq major-mode 'bibtex-mode)
10922 ;; Yes, we want to do the search in this file.
10923 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10924 (goto-char (point-min))
10925 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10926 (regexp-quote s) "[ \t\n]*,") nil t)
10927 (goto-char (match-beginning 0)))
10928 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10929 ;; Use double prefix to indicate that any web link should be browsed
10930 (let ((b (current-buffer)) (p (point)))
10931 ;; Restore the window configuration because we just use the web link
10932 (set-window-configuration org-window-config-before-follow-link)
10933 (save-excursion (set-buffer b) (goto-char p)
10934 (bibtex-url)))
10935 (recenter 0)) ; Move entry start to beginning of window
10936 ;; return t to indicate that the search is done.
10939 ;; Finally add the functions to the right hooks.
10940 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10941 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10943 ;; end of Bibtex link setup
10945 (defun org-upgrade-old-links (&optional query-description)
10946 "Transfer old <...> style links to new [[...]] style links.
10947 With arg query-description, ask at each match for a description text to use
10948 for this link."
10949 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
10950 (save-excursion
10951 (goto-char (point-min))
10952 (let ((re (concat "\\([^[]\\)<\\("
10953 "\\(" (mapconcat 'identity org-link-types "\\|")
10954 "\\):"
10955 "[^" org-non-link-chars "]+\\)>"))
10956 l1 l2 (cnt 0))
10957 (while (re-search-forward re nil t)
10958 (setq cnt (1+ cnt)
10959 l1 (org-match-string-no-properties 2)
10960 l2 (save-match-data (org-link-escape l1)))
10961 (when query-description (setq l1 (read-string "Desc: " l1)))
10962 (if (equal l1 l2)
10963 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
10964 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
10965 (message "%d matches have beed treated" cnt))))
10967 (defun org-open-file (path &optional in-emacs line search)
10968 "Open the file at PATH.
10969 First, this expands any special file name abbreviations. Then the
10970 configuration variable `org-file-apps' is checked if it contains an
10971 entry for this file type, and if yes, the corresponding command is launched.
10972 If no application is found, Emacs simply visits the file.
10973 With optional argument IN-EMACS, Emacs will visit the file.
10974 Optional LINE specifies a line to go to, optional SEARCH a string to
10975 search for. If LINE or SEARCH is given, the file will always be
10976 opened in Emacs.
10977 If the file does not exist, an error is thrown."
10978 (setq in-emacs (or in-emacs line search))
10979 (let* ((file (if (equal path "")
10980 buffer-file-name
10981 (substitute-in-file-name (expand-file-name path))))
10982 (apps (append org-file-apps (org-default-apps)))
10983 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10984 (dirp (if remp nil (file-directory-p file)))
10985 (dfile (downcase file))
10986 (old-buffer (current-buffer))
10987 (old-pos (point))
10988 (old-mode major-mode)
10989 ext cmd)
10990 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10991 (setq ext (match-string 1 dfile))
10992 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10993 (setq ext (match-string 1 dfile))))
10994 (if in-emacs
10995 (setq cmd 'emacs)
10996 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10997 (and dirp (cdr (assoc 'directory apps)))
10998 (cdr (assoc ext apps))
10999 (cdr (assoc t apps)))))
11000 (when (eq cmd 'mailcap)
11001 (require 'mailcap)
11002 (mailcap-parse-mailcaps)
11003 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11004 (command (mailcap-mime-info mime-type)))
11005 (if (stringp command)
11006 (setq cmd command)
11007 (setq cmd 'emacs))))
11008 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
11009 (not (file-exists-p file))
11010 (not org-open-non-existing-files))
11011 (error "No such file: %s" file))
11012 (cond
11013 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11014 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11015 (if (string-match "['\"]%s['\"]" cmd)
11016 (setq cmd (replace-match "%s" t t cmd)))
11017 (setq cmd (format cmd (shell-quote-argument file)))
11018 (save-window-excursion
11019 (shell-command (concat cmd " &"))))
11020 ((or (stringp cmd)
11021 (eq cmd 'emacs))
11022 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
11023 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
11024 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11025 (if line (goto-line line)
11026 (if search (org-link-search search))))
11027 ((consp cmd)
11028 (eval cmd))
11029 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11030 (and (org-mode-p) (eq old-mode 'org-mode)
11031 (or (not (equal old-buffer (current-buffer)))
11032 (not (equal old-pos (point))))
11033 (org-mark-ring-push old-pos old-buffer))))
11035 (defun org-default-apps ()
11036 "Return the default applications for this operating system."
11037 (cond
11038 ((eq system-type 'darwin)
11039 org-file-apps-defaults-macosx)
11040 ((eq system-type 'windows-nt)
11041 org-file-apps-defaults-windowsnt)
11042 (t org-file-apps-defaults-gnu)))
11044 (defun org-expand-file-name (path)
11045 "Replace special path abbreviations and expand the file name."
11046 (expand-file-name path))
11048 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11049 (defun org-file-remote-p (file)
11050 "Test whether FILE specifies a location on a remote system.
11051 Return non-nil if the location is indeed remote.
11053 For example, the filename \"/user@host:/foo\" specifies a location
11054 on the system \"/user@host:\"."
11055 (cond ((fboundp 'file-remote-p)
11056 (file-remote-p file))
11057 ((fboundp 'tramp-handle-file-remote-p)
11058 (tramp-handle-file-remote-p file))
11059 ((and (boundp 'ange-ftp-name-format)
11060 (string-match (car ange-ftp-name-format) file))
11062 (t nil)))
11064 (defvar org-insert-link-history nil
11065 "Minibuffer history for links inserted with `org-insert-link'.")
11067 (defvar org-stored-links nil
11068 "Contains the links stored with `org-store-link'.")
11070 ;;;###autoload
11071 (defun org-store-link (arg)
11072 "\\<org-mode-map>Store an org-link to the current location.
11073 This link can later be inserted into an org-buffer with
11074 \\[org-insert-link].
11075 For some link types, a prefix arg is interpreted:
11076 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11077 For file links, arg negates `org-context-in-file-links'."
11078 (interactive "P")
11079 (let (link cpltxt desc description search txt (pos (point)))
11080 (cond
11082 ((eq major-mode 'bbdb-mode)
11083 (setq cpltxt (concat
11084 "bbdb:"
11085 (or (bbdb-record-name (bbdb-current-record))
11086 (bbdb-record-company (bbdb-current-record))))
11087 link (org-make-link cpltxt)))
11089 ((eq major-mode 'Info-mode)
11090 (setq link (org-make-link "info:"
11091 (file-name-nondirectory Info-current-file)
11092 ":" Info-current-node))
11093 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11094 ":" Info-current-node)))
11096 ((eq major-mode 'calendar-mode)
11097 (let ((cd (calendar-cursor-to-date)))
11098 (setq link
11099 (format-time-string
11100 (car org-time-stamp-formats)
11101 (apply 'encode-time
11102 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11103 nil nil nil))))))
11105 ((or (eq major-mode 'vm-summary-mode)
11106 (eq major-mode 'vm-presentation-mode))
11107 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11108 (vm-follow-summary-cursor)
11109 (save-excursion
11110 (vm-select-folder-buffer)
11111 (let* ((message (car vm-message-pointer))
11112 (folder buffer-file-name)
11113 (subject (vm-su-subject message))
11114 (author (vm-su-full-name message))
11115 (message-id (vm-su-message-id message)))
11116 (setq message-id (org-remove-angle-brackets message-id))
11117 (setq folder (abbreviate-file-name folder))
11118 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11119 folder)
11120 (setq folder (replace-match "" t t folder)))
11121 (setq cpltxt (concat author " on: " subject))
11122 (setq link (org-make-link "vm:" folder "#" message-id)))))
11124 ((eq major-mode 'wl-summary-mode)
11125 (let* ((msgnum (wl-summary-message-number))
11126 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11127 msgnum 'message-id))
11128 (wl-message-entity
11129 (if (fboundp 'elmo-message-entity)
11130 (elmo-message-entity
11131 wl-summary-buffer-elmo-folder msgnum)
11132 (elmo-msgdb-overview-get-entity
11133 msgnum (wl-summary-buffer-msgdb))))
11134 (author (wl-summary-line-from)) ; FIXME: correct?
11135 (subject "???")) ; FIXME:
11136 (setq message-id (org-remove-angle-brackets message-id))
11137 (setq cpltxt (concat author " on: " subject))
11138 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11139 "#" message-id))))
11141 ((or (equal major-mode 'mh-folder-mode)
11142 (equal major-mode 'mh-show-mode))
11143 (let ((from-header (org-mhe-get-header "From:"))
11144 (to-header (org-mhe-get-header "To:"))
11145 (subject (org-mhe-get-header "Subject:")))
11146 (setq cpltxt (concat from-header " on: " subject))
11147 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11148 (org-remove-angle-brackets
11149 (org-mhe-get-header "Message-Id:"))))))
11151 ((eq major-mode 'rmail-mode)
11152 (save-excursion
11153 (save-restriction
11154 (rmail-narrow-to-non-pruned-header)
11155 (let ((folder buffer-file-name)
11156 (message-id (mail-fetch-field "message-id"))
11157 (author (mail-fetch-field "from"))
11158 (subject (mail-fetch-field "subject")))
11159 (setq message-id (org-remove-angle-brackets message-id))
11160 (setq cpltxt (concat author " on: " subject))
11161 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11163 ((eq major-mode 'gnus-group-mode)
11164 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11165 (gnus-group-group-name)) ; version
11166 ((fboundp 'gnus-group-name)
11167 (gnus-group-name))
11168 (t "???"))))
11169 (setq cpltxt (concat
11170 (if (org-xor arg org-usenet-links-prefer-google)
11171 "http://groups.google.com/groups?group="
11172 "gnus:")
11173 group)
11174 link (org-make-link cpltxt))))
11176 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11177 (require 'gnus-sum) ; FIXME: I don't think this is needed, actually
11178 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11179 (gnus-summary-beginning-of-article)
11180 (let* ((group (car gnus-article-current))
11181 (article (cdr gnus-article-current))
11182 (header (gnus-summary-article-header article))
11183 (author (mail-header-from header))
11184 (message-id (mail-header-id header))
11185 (date (mail-header-date header))
11186 (subject (gnus-summary-subject-string)))
11187 (setq cpltxt (concat author " on: " subject))
11188 (if (org-xor arg org-usenet-links-prefer-google)
11189 (setq link
11190 (concat
11191 cpltxt "\n "
11192 (format "http://groups.google.com/groups?as_umsgid=%s"
11193 (org-fixup-message-id-for-http message-id))))
11194 (setq link (org-make-link "gnus:" group
11195 "#" (number-to-string article))))))
11197 ((eq major-mode 'w3-mode)
11198 (setq cpltxt (url-view-url t)
11199 link (org-make-link cpltxt)))
11200 ((eq major-mode 'w3m-mode)
11201 (setq cpltxt (or w3m-current-title w3m-current-url)
11202 link (org-make-link w3m-current-url)))
11204 ((setq search (run-hook-with-args-until-success
11205 'org-create-file-search-functions))
11206 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11207 "::" search))
11208 (setq cpltxt (or description link)))
11210 ((eq major-mode 'image-mode)
11211 (setq cpltxt (concat "file:"
11212 (abbreviate-file-name buffer-file-name))
11213 link (org-make-link cpltxt)))
11215 ((eq major-mode 'dired-mode)
11216 ;; link to the file in the current line
11217 (setq cpltxt (concat "file:"
11218 (abbreviate-file-name
11219 (expand-file-name
11220 (dired-get-filename nil t))))
11221 link (org-make-link cpltxt)))
11223 ((and buffer-file-name (org-mode-p))
11224 ;; Just link to current headline
11225 (setq cpltxt (concat "file:"
11226 (abbreviate-file-name buffer-file-name)))
11227 ;; Add a context search string
11228 (when (org-xor org-context-in-file-links arg)
11229 ;; Check if we are on a target
11230 (if (save-excursion
11231 (skip-chars-forward "^>\n\r")
11232 (and (re-search-backward "<<" nil t)
11233 (looking-at "<<\\(.*?\\)>>")
11234 (<= (match-beginning 0) pos)
11235 (>= (match-end 0) pos)))
11236 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11237 (setq txt (cond
11238 ((org-on-heading-p) nil)
11239 ((org-region-active-p)
11240 (buffer-substring (region-beginning) (region-end)))
11241 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11242 (when (or (null txt) (string-match "\\S-" txt))
11243 (setq cpltxt
11244 (concat cpltxt "::"
11245 (if org-file-link-context-use-camel-case
11246 (org-make-org-heading-camel txt)
11247 (org-make-org-heading-search-string txt)))
11248 desc "NONE"))))
11249 (if (string-match "::\\'" cpltxt)
11250 (setq cpltxt (substring cpltxt 0 -2)))
11251 (setq link (org-make-link cpltxt)))
11253 (buffer-file-name
11254 ;; Just link to this file here.
11255 (setq cpltxt (concat "file:"
11256 (abbreviate-file-name buffer-file-name)))
11257 ;; Add a context string
11258 (when (org-xor org-context-in-file-links arg)
11259 (setq txt (if (org-region-active-p)
11260 (buffer-substring (region-beginning) (region-end))
11261 (buffer-substring (point-at-bol) (point-at-eol))))
11262 ;; Only use search option if there is some text.
11263 (when (string-match "\\S-" txt)
11264 (setq cpltxt
11265 (concat cpltxt "::"
11266 (if org-file-link-context-use-camel-case
11267 (org-make-org-heading-camel txt)
11268 (org-make-org-heading-search-string txt)))
11269 desc "NONE")))
11270 (setq link (org-make-link cpltxt)))
11272 ((interactive-p)
11273 (error "Cannot link to a buffer which is not visiting a file"))
11275 (t (setq link nil)))
11277 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11278 (setq link (or link cpltxt)
11279 desc (or desc cpltxt))
11280 (if (equal desc "NONE") (setq desc nil))
11282 (if (and (interactive-p) link)
11283 (progn
11284 (setq org-stored-links
11285 (cons (list cpltxt link desc) org-stored-links))
11286 (message "Stored: %s" (or cpltxt link)))
11287 (org-make-link-string link desc))))
11289 (defun org-make-org-heading-search-string (&optional string heading)
11290 "Make search string for STRING or current headline."
11291 (interactive)
11292 (let ((s (or string (org-get-heading))))
11293 (unless (and string (not heading))
11294 ;; We are using a headline, clean up garbage in there.
11295 (if (string-match org-todo-regexp s)
11296 (setq s (replace-match "" t t s)))
11297 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
11298 (setq s (replace-match "" t t s)))
11299 (setq s (org-trim s))
11300 (if (string-match (concat "^\\(" org-quote-string "\\|"
11301 org-comment-string "\\)") s)
11302 (setq s (replace-match "" t t s)))
11303 (while (string-match org-ts-regexp s)
11304 (setq s (replace-match "" t t s))))
11305 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11306 (setq s (replace-match " " t t s)))
11307 (or string (setq s (concat "*" s))) ; Add * for headlines
11308 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11310 (defun org-make-org-heading-camel (&optional string heading)
11311 "Make a CamelCase string for STRING or the current headline."
11312 (interactive)
11313 (let ((s (or string (org-get-heading))))
11314 (unless (and string (not heading))
11315 ;; We are using a headline, clean up garbage in there.
11316 (if (string-match org-todo-regexp s)
11317 (setq s (replace-match "" t t s)))
11318 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
11319 (setq s (replace-match "" t t s)))
11320 (setq s (org-trim s))
11321 (if (string-match (concat "^\\(" org-quote-string "\\|"
11322 org-comment-string "\\)") s)
11323 (setq s (replace-match "" t t s)))
11324 (while (string-match org-ts-regexp s)
11325 (setq s (replace-match "" t t s))))
11326 (while (string-match "[^a-zA-Z_ \t]+" s)
11327 (setq s (replace-match " " t t s)))
11328 (or string (setq s (concat "*" s))) ; Add * for headlines
11329 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
11331 (defun org-make-link (&rest strings)
11332 "Concatenate STRINGS, format resulting string with `org-link-format'."
11333 (format org-link-format (apply 'concat strings)))
11335 (defun org-make-link-string (link &optional description)
11336 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11337 (if (eq org-link-style 'plain)
11338 (if (equal description link)
11339 link
11340 (concat description "\n" link))
11341 (when (stringp description)
11342 ;; Remove brackets from the description, they are fatal.
11343 (while (string-match "\\[\\|\\]" description)
11344 (setq description (replace-match "" t t description))))
11345 (when (equal (org-link-escape link) description)
11346 ;; No description needed, it is identical
11347 (setq description nil))
11348 (when (and (not description)
11349 (not (equal link (org-link-escape link))))
11350 (setq description link))
11351 (concat "[[" (org-link-escape link) "]"
11352 (if description (concat "[" description "]") "")
11353 "]")))
11355 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
11356 "Association list of escapes for some characters problematic in links.")
11358 (defun org-link-escape (text)
11359 "Escape charaters in TEXT that are problematic for links."
11360 (when text
11361 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11362 org-link-escape-chars "\\|")))
11363 (while (string-match re text)
11364 (setq text
11365 (replace-match
11366 (cdr (assoc (match-string 0 text) org-link-escape-chars))
11367 t t text)))
11368 text)))
11370 (defun org-link-unescape (text)
11371 "Reverse the action of `org-link-escape'."
11372 (when text
11373 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11374 org-link-escape-chars "\\|")))
11375 (while (string-match re text)
11376 (setq text
11377 (replace-match
11378 (car (rassoc (match-string 0 text) org-link-escape-chars))
11379 t t text)))
11380 text)))
11382 (defun org-xor (a b)
11383 "Exclusive or."
11384 (if a (not b) b))
11386 (defun org-get-header (header)
11387 "Find a header field in the current buffer."
11388 (save-excursion
11389 (goto-char (point-min))
11390 (let ((case-fold-search t) s)
11391 (cond
11392 ((eq header 'from)
11393 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11394 (setq s (match-string 1)))
11395 (while (string-match "\"" s)
11396 (setq s (replace-match "" t t s)))
11397 (if (string-match "[<(].*" s)
11398 (setq s (replace-match "" t t s))))
11399 ((eq header 'message-id)
11400 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11401 (setq s (match-string 1))))
11402 ((eq header 'subject)
11403 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11404 (setq s (match-string 1)))))
11405 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11406 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11407 s)))
11410 (defun org-fixup-message-id-for-http (s)
11411 "Replace special characters in a message id, so it can be used in an http query."
11412 (while (string-match "<" s)
11413 (setq s (replace-match "%3C" t t s)))
11414 (while (string-match ">" s)
11415 (setq s (replace-match "%3E" t t s)))
11416 (while (string-match "@" s)
11417 (setq s (replace-match "%40" t t s)))
11420 (defun org-insert-link (&optional complete-file)
11421 "Insert a link. At the prompt, enter the link.
11423 Completion can be used to select a link previously stored with
11424 `org-store-link'. When the empty string is entered (i.e. if you just
11425 press RET at the prompt), the link defaults to the most recently
11426 stored link. As SPC triggers completion in the minibuffer, you need to
11427 use M-SPC or C-q SPC to force the insertion of a space character.
11429 You will also be prompted for a description, and if one is given, it will
11430 be displayed in the buffer instead of the link.
11432 If there is already a link at point, this command will allow you to edit link
11433 and description parts.
11435 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11436 selected using completion. The path to the file will be relative to
11437 the current directory if the file is in the current directory or a
11438 subdirectory. Otherwise, the link will be the absolute path as
11439 completed in the minibuffer (i.e. normally ~/path/to/file).
11441 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11442 is in the current directory or below.
11443 With three \\[universal-argument] prefixes, negate the meaning of
11444 `org-keep-stored-link-after-insertion'."
11445 (interactive "P")
11446 (let (link desc entry remove file (pos (point)))
11447 (cond
11448 ((save-excursion
11449 (skip-chars-forward "^]\n\r")
11450 (and (re-search-backward "\\[\\[" nil t)
11451 (looking-at org-bracket-link-regexp)
11452 (<= (match-beginning 0) pos)
11453 (>= (match-end 0) pos)))
11454 ;; We do have a link at point, and we are going to edit it.
11455 (setq remove (list (match-beginning 0) (match-end 0)))
11456 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11457 (setq link (read-string "Link: "
11458 (org-link-unescape
11459 (org-match-string-no-properties 1)))))
11460 ((equal complete-file '(4))
11461 ;; Completing read for file names.
11462 (setq file (read-file-name "File: "))
11463 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11464 (pwd1 (file-name-as-directory (abbreviate-file-name
11465 (expand-file-name ".")))))
11466 (cond
11467 ((equal complete-file '(16))
11468 (setq link (org-make-link
11469 "file:"
11470 (abbreviate-file-name (expand-file-name file)))))
11471 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11472 (setq link (org-make-link "file:" (match-string 1 file))))
11473 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11474 (expand-file-name file))
11475 (setq link (org-make-link
11476 "file:" (match-string 1 (expand-file-name file)))))
11477 (t (setq link (org-make-link "file:" file))))))
11479 ;; Read link, with completion for stored links.
11480 (setq link (org-completing-read
11481 "Link: " org-stored-links nil nil nil
11482 org-insert-link-history
11483 (or (car (car org-stored-links)))))
11484 (setq entry (assoc link org-stored-links))
11485 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11486 (not org-keep-stored-link-after-insertion))
11487 (setq org-stored-links (delq (assoc link org-stored-links)
11488 org-stored-links)))
11489 (setq link (if entry (nth 1 entry) link)
11490 desc (or desc (nth 2 entry)))))
11492 (if (string-match org-plain-link-re link)
11493 ;; URL-like link, normalize the use of angular brackets.
11494 (setq link (org-make-link (org-remove-angle-brackets link))))
11496 ;; Check if we are linking to the current file with a search option
11497 ;; If yes, simplify the link by using only the search option.
11498 (when (and buffer-file-name
11499 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11500 (let* ((path (match-string 1 link))
11501 (case-fold-search nil)
11502 (search (match-string 2 link)))
11503 (save-match-data
11504 (if (equal (file-truename buffer-file-name) (file-truename path))
11505 ;; We are linking to this same file, with a search option
11506 (setq link search)))))
11508 ;; Check if we can/should use a relative path. If yes, simplify the link
11509 (when (string-match "\\<file:\\(.*\\)" link)
11510 (let* ((path (match-string 1 link))
11511 (case-fold-search nil))
11512 (cond
11513 ((eq org-link-file-path-type 'absolute)
11514 (setq path (abbreviate-file-name (expand-file-name path))))
11515 ((eq org-link-file-path-type 'noabbrev)
11516 (setq path (expand-file-name path)))
11517 ((eq org-link-file-path-type 'relative)
11518 (setq path (file-relative-name path)))
11520 (save-match-data
11521 (if (string-match (concat "^" (regexp-quote
11522 (file-name-as-directory
11523 (expand-file-name "."))))
11524 (expand-file-name path))
11525 ;; We are linking a file with relative path name.
11526 (setq path (substring (expand-file-name path)
11527 (match-end 0)))))))
11528 (setq link (concat "file:" path))))
11530 (setq desc (read-string "Description: " desc))
11531 (unless (string-match "\\S-" desc) (setq desc nil))
11532 (if remove (apply 'delete-region remove))
11533 (insert (org-make-link-string link desc))))
11535 (defun org-completing-read (&rest args)
11536 (let ((minibuffer-local-completion-map
11537 (copy-keymap minibuffer-local-completion-map)))
11538 (define-key minibuffer-local-completion-map " " 'self-insert-command)
11539 (apply 'completing-read args)))
11541 ;;; Hooks for remember.el
11543 (defvar org-finish-function nil)
11545 ;;;###autoload
11546 (defun org-remember-annotation ()
11547 "Return a link to the current location as an annotation for remember.el.
11548 If you are using Org-mode files as target for data storage with
11549 remember.el, then the annotations should include a link compatible with the
11550 conventions in Org-mode. This function returns such a link."
11551 (org-store-link nil))
11553 (defconst org-remember-help
11554 "Select a destination location for the note.
11555 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
11556 RET at beg-of-buf -> Append to file as level 2 headline
11557 RET on headline -> Store as sublevel entry to current headline
11558 <left>/<right> -> before/after current headline, same headings level")
11560 ;;;###autoload
11561 (defun org-remember-apply-template ()
11562 "Initialize *remember* buffer with template, invoke `org-mode'.
11563 This function should be placed into `remember-mode-hook' and in fact requires
11564 to be run from that hook to fucntion properly."
11565 (if org-remember-templates
11567 (let* ((entry (if (= (length org-remember-templates) 1)
11568 (cdar org-remember-templates)
11569 (message "Select template: %s"
11570 (mapconcat
11571 (lambda (x) (char-to-string (car x)))
11572 org-remember-templates " "))
11573 (cdr (assoc (read-char-exclusive) org-remember-templates))))
11574 (tpl (car entry))
11575 (file (if (consp (cdr entry)) (nth 1 entry)))
11576 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
11577 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
11578 (v-u (concat "[" (substring v-t 1 -1) "]"))
11579 (v-U (concat "[" (substring v-T 1 -1) "]"))
11580 (v-a annotation) ; defined in `remember-mode'
11581 (v-i initial) ; defined in `remember-mode'
11582 (v-n user-full-name)
11584 (unless tpl (setq tpl "") (message "No template") (ding))
11585 (insert tpl) (goto-char (point-min))
11586 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
11587 (when (and initial (equal (match-string 0) "%i"))
11588 (save-match-data
11589 (let* ((lead (buffer-substring
11590 (point-at-bol) (match-beginning 0))))
11591 (setq v-i (mapconcat 'identity
11592 (org-split-string initial "\n")
11593 (concat "\n" lead))))))
11594 (replace-match
11595 (or (eval (intern (concat "v-" (match-string 1)))) "")
11596 t t))
11597 (let ((org-startup-folded nil)
11598 (org-startup-with-deadline-check nil))
11599 (org-mode))
11600 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
11601 (org-set-local 'org-default-notes-file file))
11602 (goto-char (point-min))
11603 (if (re-search-forward "%\\?" nil t) (replace-match "")))
11604 (let ((org-startup-folded nil)
11605 (org-startup-with-deadline-check nil))
11606 (org-mode)))
11607 (org-set-local 'org-finish-function 'remember-buffer))
11609 ;;;###autoload
11610 (defun org-remember-handler ()
11611 "Store stuff from remember.el into an org file.
11612 First prompts for an org file. If the user just presses return, the value
11613 of `org-default-notes-file' is used.
11614 Then the command offers the headings tree of the selected file in order to
11615 file the text at a specific location.
11616 You can either immediately press RET to get the note appended to the
11617 file, or you can use vertical cursor motion and visibility cycling (TAB) to
11618 find a better place. Then press RET or <left> or <right> in insert the note.
11620 Key Cursor position Note gets inserted
11621 -----------------------------------------------------------------------------
11622 RET buffer-start as level 2 heading at end of file
11623 RET on headline as sublevel of the heading at cursor
11624 RET no heading at cursor position, level taken from context.
11625 Or use prefix arg to specify level manually.
11626 <left> on headline as same level, before current heading
11627 <right> on headline as same level, after current heading
11629 So the fastest way to store the note is to press RET RET to append it to
11630 the default file. This way your current train of thought is not
11631 interrupted, in accordance with the principles of remember.el. But with
11632 little extra effort, you can push it directly to the correct location.
11634 Before being stored away, the function ensures that the text has a
11635 headline, i.e. a first line that starts with a \"*\". If not, a headline
11636 is constructed from the current date and some additional data.
11638 If the variable `org-adapt-indentation' is non-nil, the entire text is
11639 also indented so that it starts in the same column as the headline
11640 \(i.e. after the stars).
11642 See also the variable `org-reverse-note-order'."
11643 (catch 'quit
11644 (let* ((txt (buffer-substring (point-min) (point-max)))
11645 (fastp current-prefix-arg)
11646 (file (if fastp org-default-notes-file (org-get-org-file)))
11647 (visiting (find-buffer-visiting file))
11648 (org-startup-with-deadline-check nil)
11649 (org-startup-folded nil)
11650 (org-startup-align-all-tables nil)
11651 spos level indent reversed)
11652 ;; Modify text so that it becomes a nice subtree which can be inserted
11653 ;; into an org tree.
11654 (let* ((lines (split-string txt "\n"))
11655 first)
11656 ;; remove empty lines at the beginning
11657 (while (and lines (string-match "^[ \t]*\n" (car lines)))
11658 (setq lines (cdr lines)))
11659 (setq first (car lines) lines (cdr lines))
11660 (if (string-match "^\\*+" first)
11661 ;; Is already a headline
11662 (setq indent nil)
11663 ;; We need to add a headline: Use time and first buffer line
11664 (setq lines (cons first lines)
11665 first (concat "* " (current-time-string)
11666 " (" (remember-buffer-desc) ")")
11667 indent " "))
11668 (if (and org-adapt-indentation indent)
11669 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
11670 (setq txt (concat first "\n"
11671 (mapconcat 'identity lines "\n"))))
11672 ;; Find the file
11673 (if (not visiting)
11674 (find-file-noselect file))
11675 (with-current-buffer (get-file-buffer file)
11676 (save-excursion (and (goto-char (point-min))
11677 (not (re-search-forward "^\\* " nil t))
11678 (insert "\n* Notes\n")))
11679 (setq reversed (org-notes-order-reversed-p))
11680 (save-excursion
11681 (save-restriction
11682 (widen)
11683 ;; Ask the User for a location
11684 (setq spos (if fastp 1 (org-get-location
11685 (current-buffer)
11686 org-remember-help)))
11687 (if (not spos) (throw 'quit nil)) ; return nil to show we did
11688 ; not handle this note
11689 (goto-char spos)
11690 (cond ((and (bobp) (not reversed))
11691 ;; Put it at the end, as level 2
11692 (save-restriction
11693 (widen)
11694 (goto-char (point-max))
11695 (if (not (bolp)) (newline))
11696 (org-paste-subtree 2 txt)))
11697 ((and (bobp) reversed)
11698 ;; Put it at the start, as level 1
11699 (save-restriction
11700 (widen)
11701 (goto-char (point-min))
11702 (re-search-forward "^\\*" nil t)
11703 (beginning-of-line 1)
11704 (org-paste-subtree 1 txt)))
11705 ((and (org-on-heading-p nil) (not current-prefix-arg))
11706 ;; Put it below this entry, at the beg/end of the subtree
11707 (org-back-to-heading)
11708 (setq level (funcall outline-level))
11709 (if reversed
11710 (outline-end-of-heading)
11711 (outline-end-of-subtree))
11712 (if (not (bolp)) (newline))
11713 (beginning-of-line 1)
11714 (org-paste-subtree (org-get-legal-level level 1) txt))
11716 ;; Put it right there, with automatic level determined by
11717 ;; org-paste-subtree or from prefix arg
11718 (org-paste-subtree current-prefix-arg txt)))
11719 (when remember-save-after-remembering
11720 (save-buffer)
11721 (if (not visiting) (kill-buffer (current-buffer)))))))))
11722 t) ;; return t to indicate that we took care of this note.
11724 (defun org-get-org-file ()
11725 "Read a filename, with default directory `org-directory'."
11726 (let ((default (or org-default-notes-file remember-data-file)))
11727 (read-file-name (format "File name [%s]: " default)
11728 (file-name-as-directory org-directory)
11729 default)))
11731 (defun org-notes-order-reversed-p ()
11732 "Check if the current file should receive notes in reversed order."
11733 (cond
11734 ((not org-reverse-note-order) nil)
11735 ((eq t org-reverse-note-order) t)
11736 ((not (listp org-reverse-note-order)) nil)
11737 (t (catch 'exit
11738 (let ((all org-reverse-note-order)
11739 entry)
11740 (while (setq entry (pop all))
11741 (if (string-match (car entry) buffer-file-name)
11742 (throw 'exit (cdr entry))))
11743 nil)))))
11745 ;;; Tables
11747 ;; Watch out: Here we are talking about two different kind of tables.
11748 ;; Most of the code is for the tables created with the Org-mode table editor.
11749 ;; Sometimes, we talk about tables created and edited with the table.el
11750 ;; Emacs package. We call the former org-type tables, and the latter
11751 ;; table.el-type tables.
11754 (defun org-before-change-function (beg end)
11755 "Every change indicates that a table might need an update."
11756 (setq org-table-may-need-update t))
11758 (defconst org-table-line-regexp "^[ \t]*|"
11759 "Detects an org-type table line.")
11760 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
11761 "Detects an org-type table line.")
11762 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
11763 "Detects a table line marked for automatic recalculation.")
11764 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
11765 "Detects a table line marked for automatic recalculation.")
11766 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
11767 "Detects a table line marked for automatic recalculation.")
11768 (defconst org-table-hline-regexp "^[ \t]*|-"
11769 "Detects an org-type table hline.")
11770 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
11771 "Detects a table-type table hline.")
11772 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
11773 "Detects an org-type or table-type table.")
11774 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
11775 "Searching from within a table (any type) this finds the first line
11776 outside the table.")
11777 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
11778 "Searching from within a table (any type) this finds the first line
11779 outside the table.")
11781 (defun org-table-create-with-table.el ()
11782 "Use the table.el package to insert a new table.
11783 If there is already a table at point, convert between Org-mode tables
11784 and table.el tables."
11785 (interactive)
11786 (require 'table)
11787 (cond
11788 ((org-at-table.el-p)
11789 (if (y-or-n-p "Convert table to Org-mode table? ")
11790 (org-table-convert)))
11791 ((org-at-table-p)
11792 (if (y-or-n-p "Convert table to table.el table? ")
11793 (org-table-convert)))
11794 (t (call-interactively 'table-insert))))
11796 (defun org-table-create-or-convert-from-region (arg)
11797 "Convert region to table, or create an empty table.
11798 If there is an active region, convert it to a table. If there is no such
11799 region, create an empty table."
11800 (interactive "P")
11801 (if (org-region-active-p)
11802 (org-table-convert-region (region-beginning) (region-end) arg)
11803 (org-table-create arg)))
11805 (defun org-table-create (&optional size)
11806 "Query for a size and insert a table skeleton.
11807 SIZE is a string Columns x Rows like for example \"3x2\"."
11808 (interactive "P")
11809 (unless size
11810 (setq size (read-string
11811 (concat "Table size Columns x Rows [e.g. "
11812 org-table-default-size "]: ")
11813 "" nil org-table-default-size)))
11815 (let* ((pos (point))
11816 (indent (make-string (current-column) ?\ ))
11817 (split (org-split-string size " *x *"))
11818 (rows (string-to-number (nth 1 split)))
11819 (columns (string-to-number (car split)))
11820 (line (concat (apply 'concat indent "|" (make-list columns " |"))
11821 "\n")))
11822 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
11823 (point-at-bol) (point)))
11824 (beginning-of-line 1)
11825 (newline))
11826 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
11827 (dotimes (i rows) (insert line))
11828 (goto-char pos)
11829 (if (> rows 1)
11830 ;; Insert a hline after the first row.
11831 (progn
11832 (end-of-line 1)
11833 (insert "\n|-")
11834 (goto-char pos)))
11835 (org-table-align)))
11837 (defun org-table-convert-region (beg0 end0 &optional nspace)
11838 "Convert region to a table.
11839 The region goes from BEG0 to END0, but these borders will be moved
11840 slightly, to make sure a beginning of line in the first line is included.
11841 When NSPACE is non-nil, it indicates the minimum number of spaces that
11842 separate columns (default: just one space)."
11843 (interactive "rP")
11844 (let* ((beg (min beg0 end0))
11845 (end (max beg0 end0))
11846 (tabsep t)
11848 (goto-char beg)
11849 (beginning-of-line 1)
11850 (setq beg (move-marker (make-marker) (point)))
11851 (goto-char end)
11852 (if (bolp) (backward-char 1) (end-of-line 1))
11853 (setq end (move-marker (make-marker) (point)))
11854 ;; Lets see if this is tab-separated material. If every nonempty line
11855 ;; contains a tab, we will assume that it is tab-separated material
11856 (if nspace
11857 (setq tabsep nil)
11858 (goto-char beg)
11859 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
11860 (if nspace (setq tabsep nil))
11861 (if tabsep
11862 (setq re "^\\|\t")
11863 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
11864 (max 1 (prefix-numeric-value nspace)))))
11865 (goto-char beg)
11866 (while (re-search-forward re end t)
11867 (replace-match "| " t t))
11868 (goto-char beg)
11869 (insert " ")
11870 (org-table-align)))
11872 (defun org-table-import (file arg)
11873 "Import FILE as a table.
11874 The file is assumed to be tab-separated. Such files can be produced by most
11875 spreadsheet and database applications. If no tabs (at least one per line)
11876 are found, lines will be split on whitespace into fields."
11877 (interactive "f\nP")
11878 (or (bolp) (newline))
11879 (let ((beg (point))
11880 (pm (point-max)))
11881 (insert-file-contents file)
11882 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
11884 (defun org-table-export ()
11885 "Export table as a tab-separated file.
11886 Such a file can be imported into a spreadsheet program like Excel."
11887 (interactive)
11888 (let* ((beg (org-table-begin))
11889 (end (org-table-end))
11890 (table (buffer-substring beg end))
11891 (file (read-file-name "Export table to: "))
11892 buf)
11893 (unless (or (not (file-exists-p file))
11894 (y-or-n-p (format "Overwrite file %s? " file)))
11895 (error "Abort"))
11896 (with-current-buffer (find-file-noselect file)
11897 (setq buf (current-buffer))
11898 (erase-buffer)
11899 (fundamental-mode)
11900 (insert table)
11901 (goto-char (point-min))
11902 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
11903 (replace-match "" t t)
11904 (end-of-line 1))
11905 (goto-char (point-min))
11906 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
11907 (replace-match "" t t)
11908 (goto-char (min (1+ (point)) (point-max))))
11909 (goto-char (point-min))
11910 (while (re-search-forward "^-[-+]*$" nil t)
11911 (replace-match "")
11912 (if (looking-at "\n")
11913 (delete-char 1)))
11914 (goto-char (point-min))
11915 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
11916 (replace-match "\t" t t))
11917 (save-buffer))
11918 (kill-buffer buf)))
11920 (defvar org-table-aligned-begin-marker (make-marker)
11921 "Marker at the beginning of the table last aligned.
11922 Used to check if cursor still is in that table, to minimize realignment.")
11923 (defvar org-table-aligned-end-marker (make-marker)
11924 "Marker at the end of the table last aligned.
11925 Used to check if cursor still is in that table, to minimize realignment.")
11926 (defvar org-table-last-alignment nil
11927 "List of flags for flushright alignment, from the last re-alignment.
11928 This is being used to correctly align a single field after TAB or RET.")
11929 (defvar org-table-last-column-widths nil
11930 "List of max width of fields in each column.
11931 This is being used to correctly align a single field after TAB or RET.")
11933 (defvar org-last-recalc-line nil)
11934 (defconst org-narrow-column-arrow "=>"
11935 "Used as display property in narrowed table columns.")
11937 (defun org-table-align ()
11938 "Align the table at point by aligning all vertical bars."
11939 (interactive)
11940 (let* (
11941 ;; Limits of table
11942 (beg (org-table-begin))
11943 (end (org-table-end))
11944 ;; Current cursor position
11945 (linepos (org-current-line))
11946 (colpos (org-table-current-column))
11947 (winstart (window-start))
11948 (winstartline (org-current-line (min winstart (1- (point-max)))))
11949 lines (new "") lengths l typenums ty fields maxfields i
11950 column
11951 (indent "") cnt frac
11952 rfmt hfmt
11953 (spaces '(1 . 1))
11954 (sp1 (car spaces))
11955 (sp2 (cdr spaces))
11956 (rfmt1 (concat
11957 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
11958 (hfmt1 (concat
11959 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
11960 emptystrings links dates narrow fmax f1 len c e)
11961 (untabify beg end)
11962 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
11963 ;; Check if we have links or dates
11964 (goto-char beg)
11965 (setq links (re-search-forward org-bracket-link-regexp end t))
11966 (goto-char beg)
11967 (setq dates (and org-display-custom-times
11968 (re-search-forward org-ts-regexp-both end t)))
11969 ;; Make sure the link properties are right
11970 (when links (goto-char beg) (while (org-activate-bracket-links end)))
11971 ;; Make sure the date properties are right
11972 (when dates (goto-char beg) (while (org-activate-dates end)))
11974 ;; Check if we are narrowing any columns
11975 (goto-char beg)
11976 (setq narrow (and org-format-transports-properties-p
11977 (re-search-forward "<[0-9]+>" end t)))
11978 ;; Get the rows
11979 (setq lines (org-split-string
11980 (buffer-substring beg end) "\n"))
11981 ;; Store the indentation of the first line
11982 (if (string-match "^ *" (car lines))
11983 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11984 ;; Mark the hlines by setting the corresponding element to nil
11985 ;; At the same time, we remove trailing space.
11986 (setq lines (mapcar (lambda (l)
11987 (if (string-match "^ *|-" l)
11989 (if (string-match "[ \t]+$" l)
11990 (substring l 0 (match-beginning 0))
11991 l)))
11992 lines))
11993 ;; Get the data fields by splitting the lines.
11994 (setq fields (mapcar
11995 (lambda (l)
11996 (org-split-string l " *| *"))
11997 (delq nil (copy-sequence lines))))
11998 ;; How many fields in the longest line?
11999 (condition-case nil
12000 (setq maxfields (apply 'max (mapcar 'length fields)))
12001 (error
12002 (kill-region beg end)
12003 (org-table-create org-table-default-size)
12004 (error "Empty table - created default table")))
12005 ;; A list of empty strings to fill any short rows on output
12006 (setq emptystrings (make-list maxfields ""))
12007 ;; Check for special formatting.
12008 (setq i -1)
12009 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
12010 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
12011 ;; Check if there is an explicit width specified
12012 (when (and org-table-limit-column-width narrow)
12013 (setq c column fmax nil)
12014 (while c
12015 (setq e (pop c))
12016 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
12017 (setq fmax (string-to-number (match-string 1 e)) c nil)))
12018 ;; Find fields that are wider than fmax, and shorten them
12019 (when fmax
12020 (loop for xx in column do
12021 (when (and (stringp xx)
12022 (> (org-string-width xx) fmax))
12023 (org-add-props xx nil
12024 'help-echo
12025 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
12026 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
12027 (unless (> f1 1)
12028 (error "Cannot narrow field starting with wide link \"%s\""
12029 (match-string 0 xx)))
12030 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
12031 (add-text-properties (- f1 2) f1
12032 (list 'display org-narrow-column-arrow)
12033 xx)))))
12034 ;; Get the maximum width for each column
12035 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
12036 ;; Get the fraction of numbers, to decide about alignment of the column
12037 (setq cnt 0 frac 0.0)
12038 (loop for x in column do
12039 (if (equal x "")
12041 (setq frac ( / (+ (* frac cnt)
12042 (if (string-match org-table-number-regexp x) 1 0))
12043 (setq cnt (1+ cnt))))))
12044 (push (>= frac org-table-number-fraction) typenums))
12045 (setq lengths (nreverse lengths) typenums (nreverse typenums))
12047 ;; Store the alignment of this table, for later editing of single fields
12048 (setq org-table-last-alignment typenums
12049 org-table-last-column-widths lengths)
12051 ;; With invisible characters, `format' does not get the field width right
12052 ;; So we need to make these fields wide by hand.
12053 (when links
12054 (loop for i from 0 upto (1- maxfields) do
12055 (setq len (nth i lengths))
12056 (loop for j from 0 upto (1- (length fields)) do
12057 (setq c (nthcdr i (car (nthcdr j fields))))
12058 (if (and (stringp (car c))
12059 (string-match org-bracket-link-regexp (car c))
12060 (< (org-string-width (car c)) len))
12061 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
12063 ;; Compute the formats needed for output of the table
12064 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
12065 (while (setq l (pop lengths))
12066 (setq ty (if (pop typenums) "" "-")) ; number types flushright
12067 (setq rfmt (concat rfmt (format rfmt1 ty l))
12068 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
12069 (setq rfmt (concat rfmt "\n")
12070 hfmt (concat (substring hfmt 0 -1) "|\n"))
12072 (setq new (mapconcat
12073 (lambda (l)
12074 (if l (apply 'format rfmt
12075 (append (pop fields) emptystrings))
12076 hfmt))
12077 lines ""))
12078 ;; Replace the old one
12079 (delete-region beg end)
12080 (move-marker end nil)
12081 (move-marker org-table-aligned-begin-marker (point))
12082 (insert new)
12083 (move-marker org-table-aligned-end-marker (point))
12084 (when (and orgtbl-mode (not (org-mode-p)))
12085 (goto-char org-table-aligned-begin-marker)
12086 (while (org-hide-wide-columns org-table-aligned-end-marker)))
12087 ;; Try to move to the old location
12088 (goto-line winstartline)
12089 (setq winstart (point-at-bol))
12090 (goto-line linepos)
12091 (set-window-start (selected-window) winstart 'noforce)
12092 (org-table-goto-column colpos)
12093 (setq org-table-may-need-update nil)
12096 (defun org-string-width (s)
12097 "Compute width of string, ignoring invisible characters.
12098 This ignores character with invisibility property `org-link', and also
12099 characters with property `org-cwidth', because these will become invisible
12100 upon the next fontification round."
12101 (let (b l)
12102 (when (or (eq t buffer-invisibility-spec)
12103 (assq 'org-link buffer-invisibility-spec))
12104 (while (setq b (text-property-any 0 (length s)
12105 'invisible 'org-link s))
12106 (setq s (concat (substring s 0 b)
12107 (substring s (or (next-single-property-change
12108 b 'invisible s) (length s)))))))
12109 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12110 (setq s (concat (substring s 0 b)
12111 (substring s (or (next-single-property-change
12112 b 'org-cwidth s) (length s))))))
12113 (setq l (string-width s) b -1)
12114 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12115 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12118 (defun org-table-begin (&optional table-type)
12119 "Find the beginning of the table and return its position.
12120 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
12121 (save-excursion
12122 (if (not (re-search-backward
12123 (if table-type org-table-any-border-regexp
12124 org-table-border-regexp)
12125 nil t))
12126 (progn (goto-char (point-min)) (point))
12127 (goto-char (match-beginning 0))
12128 (beginning-of-line 2)
12129 (point))))
12131 (defun org-table-end (&optional table-type)
12132 "Find the end of the table and return its position.
12133 With argument TABLE-TYPE, go to the end of a table.el-type table."
12134 (save-excursion
12135 (if (not (re-search-forward
12136 (if table-type org-table-any-border-regexp
12137 org-table-border-regexp)
12138 nil t))
12139 (goto-char (point-max))
12140 (goto-char (match-beginning 0)))
12141 (point-marker)))
12143 (defun org-table-justify-field-maybe (&optional new)
12144 "Justify the current field, text to left, number to right.
12145 Optional argument NEW may specify text to replace the current field content."
12146 (cond
12147 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
12148 ((org-at-table-hline-p))
12149 ((and (not new)
12150 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
12151 (current-buffer)))
12152 (< (point) org-table-aligned-begin-marker)
12153 (>= (point) org-table-aligned-end-marker)))
12154 ;; This is not the same table, force a full re-align
12155 (setq org-table-may-need-update t))
12156 (t ;; realign the current field, based on previous full realign
12157 (let* ((pos (point)) s
12158 (col (org-table-current-column))
12159 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
12160 l f n o e)
12161 (when (> col 0)
12162 (skip-chars-backward "^|\n")
12163 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
12164 (progn
12165 (setq s (match-string 1)
12166 o (match-string 0)
12167 l (max 1 (- (match-end 0) (match-beginning 0) 3))
12168 e (not (= (match-beginning 2) (match-end 2))))
12169 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
12170 l (if e "|" (setq org-table-may-need-update t) ""))
12171 n (format f s))
12172 (if new
12173 (if (<= (length new) l) ;; FIXME: length -> str-width?
12174 (setq n (format f new))
12175 (setq n (concat new "|") org-table-may-need-update t)))
12176 (or (equal n o)
12177 (let (org-table-may-need-update)
12178 (replace-match n))))
12179 (setq org-table-may-need-update t))
12180 (goto-char pos))))))
12182 (defun org-table-next-field ()
12183 "Go to the next field in the current table, creating new lines as needed.
12184 Before doing so, re-align the table if necessary."
12185 (interactive)
12186 (org-table-maybe-eval-formula)
12187 (org-table-maybe-recalculate-line)
12188 (if (and org-table-automatic-realign
12189 org-table-may-need-update)
12190 (org-table-align))
12191 (let ((end (org-table-end)))
12192 (if (org-at-table-hline-p)
12193 (end-of-line 1))
12194 (condition-case nil
12195 (progn
12196 (re-search-forward "|" end)
12197 (if (looking-at "[ \t]*$")
12198 (re-search-forward "|" end))
12199 (if (and (looking-at "-")
12200 org-table-tab-jumps-over-hlines
12201 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
12202 (goto-char (match-beginning 1)))
12203 (if (looking-at "-")
12204 (progn
12205 (beginning-of-line 0)
12206 (org-table-insert-row 'below))
12207 (if (looking-at " ") (forward-char 1))))
12208 (error
12209 (org-table-insert-row 'below)))))
12211 (defun org-table-previous-field ()
12212 "Go to the previous field in the table.
12213 Before doing so, re-align the table if necessary."
12214 (interactive)
12215 (org-table-justify-field-maybe)
12216 (org-table-maybe-recalculate-line)
12217 (if (and org-table-automatic-realign
12218 org-table-may-need-update)
12219 (org-table-align))
12220 (if (org-at-table-hline-p)
12221 (end-of-line 1))
12222 (re-search-backward "|" (org-table-begin))
12223 (re-search-backward "|" (org-table-begin))
12224 (while (looking-at "|\\(-\\|[ \t]*$\\)")
12225 (re-search-backward "|" (org-table-begin)))
12226 (if (looking-at "| ?")
12227 (goto-char (match-end 0))))
12229 (defun org-table-next-row ()
12230 "Go to the next row (same column) in the current table.
12231 Before doing so, re-align the table if necessary."
12232 (interactive)
12233 (org-table-maybe-eval-formula)
12234 (org-table-maybe-recalculate-line)
12235 (if (or (looking-at "[ \t]*$")
12236 (save-excursion (skip-chars-backward " \t") (bolp)))
12237 (newline)
12238 (if (and org-table-automatic-realign
12239 org-table-may-need-update)
12240 (org-table-align))
12241 (let ((col (org-table-current-column)))
12242 (beginning-of-line 2)
12243 (if (or (not (org-at-table-p))
12244 (org-at-table-hline-p))
12245 (progn
12246 (beginning-of-line 0)
12247 (org-table-insert-row 'below)))
12248 (org-table-goto-column col)
12249 (skip-chars-backward "^|\n\r")
12250 (if (looking-at " ") (forward-char 1)))))
12252 (defun org-table-copy-down (n)
12253 "Copy a field down in the current column.
12254 If the field at the cursor is empty, copy into it the content of the nearest
12255 non-empty field above. With argument N, use the Nth non-empty field.
12256 If the current field is not empty, it is copied down to the next row, and
12257 the cursor is moved with it. Therefore, repeating this command causes the
12258 column to be filled row-by-row.
12259 If the variable `org-table-copy-increment' is non-nil and the field is an
12260 integer, it will be incremented while copying."
12261 (interactive "p")
12262 (let* ((colpos (org-table-current-column))
12263 (field (org-table-get-field))
12264 (non-empty (string-match "[^ \t]" field))
12265 (beg (org-table-begin))
12266 txt)
12267 (org-table-check-inside-data-field)
12268 (if non-empty
12269 (progn
12270 (setq txt (org-trim field))
12271 (org-table-next-row)
12272 (org-table-blank-field))
12273 (save-excursion
12274 (setq txt
12275 (catch 'exit
12276 (while (progn (beginning-of-line 1)
12277 (re-search-backward org-table-dataline-regexp
12278 beg t))
12279 (org-table-goto-column colpos t)
12280 (if (and (looking-at
12281 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
12282 (= (setq n (1- n)) 0))
12283 (throw 'exit (match-string 1))))))))
12284 (if txt
12285 (progn
12286 (if (and org-table-copy-increment
12287 (string-match "^[0-9]+$" txt))
12288 (setq txt (format "%d" (+ (string-to-number txt) 1))))
12289 (insert txt)
12290 (org-table-maybe-recalculate-line)
12291 (org-table-align))
12292 (error "No non-empty field found"))))
12294 (defun org-table-check-inside-data-field ()
12295 "Is point inside a table data field?
12296 I.e. not on a hline or before the first or after the last column?
12297 This actually throws an error, so it aborts the current command."
12298 (if (or (not (org-at-table-p))
12299 (= (org-table-current-column) 0)
12300 (org-at-table-hline-p)
12301 (looking-at "[ \t]*$"))
12302 (error "Not in table data field")))
12304 (defvar org-table-clip nil
12305 "Clipboard for table regions.")
12307 (defun org-table-blank-field ()
12308 "Blank the current table field or active region."
12309 (interactive)
12310 (org-table-check-inside-data-field)
12311 (if (and (interactive-p) (org-region-active-p))
12312 (let (org-table-clip)
12313 (org-table-cut-region (region-beginning) (region-end)))
12314 (skip-chars-backward "^|")
12315 (backward-char 1)
12316 (if (looking-at "|[^|\n]+")
12317 (let* ((pos (match-beginning 0))
12318 (match (match-string 0))
12319 (len (org-string-width match)))
12320 (replace-match (concat "|" (make-string (1- len) ?\ )))
12321 (goto-char (+ 2 pos))
12322 (substring match 1)))))
12324 (defun org-table-get-field (&optional n replace)
12325 "Return the value of the field in column N of current row.
12326 N defaults to current field.
12327 If REPLACE is a string, replace field with this value. The return value
12328 is always the old value."
12329 (and n (org-table-goto-column n))
12330 (skip-chars-backward "^|\n")
12331 (backward-char 1)
12332 (if (looking-at "|[^|\r\n]*")
12333 (let* ((pos (match-beginning 0))
12334 (val (buffer-substring (1+ pos) (match-end 0))))
12335 (if replace
12336 (replace-match (concat "|" replace)))
12337 (goto-char (min (point-at-eol) (+ 2 pos)))
12338 val)
12339 (forward-char 1) ""))
12341 (defun org-table-current-column ()
12342 "Find out which column we are in.
12343 When called interactively, column is also displayed in echo area."
12344 (interactive)
12345 (if (interactive-p) (org-table-check-inside-data-field))
12346 (save-excursion
12347 (let ((cnt 0) (pos (point)))
12348 (beginning-of-line 1)
12349 (while (search-forward "|" pos t)
12350 (setq cnt (1+ cnt)))
12351 (if (interactive-p) (message "This is table column %d" cnt))
12352 cnt)))
12354 (defun org-table-goto-column (n &optional on-delim force)
12355 "Move the cursor to the Nth column in the current table line.
12356 With optional argument ON-DELIM, stop with point before the left delimiter
12357 of the field.
12358 If there are less than N fields, just go to after the last delimiter.
12359 However, when FORCE is non-nil, create new columns if necessary."
12360 (interactive "p")
12361 (let ((pos (point-at-eol)))
12362 (beginning-of-line 1)
12363 (when (> n 0)
12364 (while (and (> (setq n (1- n)) -1)
12365 (or (search-forward "|" pos t)
12366 (and force
12367 (progn (end-of-line 1)
12368 (skip-chars-backward "^|")
12369 (insert " | "))))))
12370 ; (backward-char 2) t)))))
12371 (when (and force (not (looking-at ".*|")))
12372 (save-excursion (end-of-line 1) (insert " | ")))
12373 (if on-delim
12374 (backward-char 1)
12375 (if (looking-at " ") (forward-char 1))))))
12377 (defun org-at-table-p (&optional table-type)
12378 "Return t if the cursor is inside an org-type table.
12379 If TABLE-TYPE is non-nil, also check for table.el-type tables."
12380 (if org-enable-table-editor
12381 (save-excursion
12382 (beginning-of-line 1)
12383 (looking-at (if table-type org-table-any-line-regexp
12384 org-table-line-regexp)))
12385 nil))
12387 (defun org-at-table.el-p ()
12388 "Return t if and only if we are at a table.el table."
12389 (and (org-at-table-p 'any)
12390 (save-excursion
12391 (goto-char (org-table-begin 'any))
12392 (looking-at org-table1-hline-regexp))))
12394 (defun org-table-recognize-table.el ()
12395 "If there is a table.el table nearby, recognize it and move into it."
12396 (if org-table-tab-recognizes-table.el
12397 (if (org-at-table.el-p)
12398 (progn
12399 (beginning-of-line 1)
12400 (if (looking-at org-table-dataline-regexp)
12402 (if (looking-at org-table1-hline-regexp)
12403 (progn
12404 (beginning-of-line 2)
12405 (if (looking-at org-table-any-border-regexp)
12406 (beginning-of-line -1)))))
12407 (if (re-search-forward "|" (org-table-end t) t)
12408 (progn
12409 (require 'table)
12410 (if (table--at-cell-p (point))
12412 (message "recognizing table.el table...")
12413 (table-recognize-table)
12414 (message "recognizing table.el table...done")))
12415 (error "This should not happen..."))
12417 nil)
12418 nil))
12420 (defun org-at-table-hline-p ()
12421 "Return t if the cursor is inside a hline in a table."
12422 (if org-enable-table-editor
12423 (save-excursion
12424 (beginning-of-line 1)
12425 (looking-at org-table-hline-regexp))
12426 nil))
12428 (defun org-table-insert-column ()
12429 "Insert a new column into the table."
12430 (interactive)
12431 (if (not (org-at-table-p))
12432 (error "Not at a table"))
12433 (org-table-find-dataline)
12434 (let* ((col (max 1 (org-table-current-column)))
12435 (beg (org-table-begin))
12436 (end (org-table-end))
12437 ;; Current cursor position
12438 (linepos (org-current-line))
12439 (colpos col))
12440 (goto-char beg)
12441 (while (< (point) end)
12442 (if (org-at-table-hline-p)
12444 (org-table-goto-column col t)
12445 (insert "| "))
12446 (beginning-of-line 2))
12447 (move-marker end nil)
12448 (goto-line linepos)
12449 (org-table-goto-column colpos)
12450 (org-table-align)
12451 (org-table-modify-formulas 'insert col)))
12453 (defun org-table-find-dataline ()
12454 "Find a dataline in the current table, which is needed for column commands."
12455 (if (and (org-at-table-p)
12456 (not (org-at-table-hline-p)))
12458 (let ((col (current-column))
12459 (end (org-table-end)))
12460 (move-to-column col)
12461 (while (and (< (point) end)
12462 (or (not (= (current-column) col))
12463 (org-at-table-hline-p)))
12464 (beginning-of-line 2)
12465 (move-to-column col))
12466 (if (and (org-at-table-p)
12467 (not (org-at-table-hline-p)))
12469 (error
12470 "Please position cursor in a data line for column operations")))))
12472 (defun org-table-delete-column ()
12473 "Delete a column from the table."
12474 (interactive)
12475 (if (not (org-at-table-p))
12476 (error "Not at a table"))
12477 (org-table-find-dataline)
12478 (org-table-check-inside-data-field)
12479 (let* ((col (org-table-current-column))
12480 (beg (org-table-begin))
12481 (end (org-table-end))
12482 ;; Current cursor position
12483 (linepos (org-current-line))
12484 (colpos col))
12485 (goto-char beg)
12486 (while (< (point) end)
12487 (if (org-at-table-hline-p)
12489 (org-table-goto-column col t)
12490 (and (looking-at "|[^|\n]+|")
12491 (replace-match "|")))
12492 (beginning-of-line 2))
12493 (move-marker end nil)
12494 (goto-line linepos)
12495 (org-table-goto-column colpos)
12496 (org-table-align)
12497 (org-table-modify-formulas 'remove col)))
12499 (defun org-table-move-column-right ()
12500 "Move column to the right."
12501 (interactive)
12502 (org-table-move-column nil))
12503 (defun org-table-move-column-left ()
12504 "Move column to the left."
12505 (interactive)
12506 (org-table-move-column 'left))
12508 (defun org-table-move-column (&optional left)
12509 "Move the current column to the right. With arg LEFT, move to the left."
12510 (interactive "P")
12511 (if (not (org-at-table-p))
12512 (error "Not at a table"))
12513 (org-table-find-dataline)
12514 (org-table-check-inside-data-field)
12515 (let* ((col (org-table-current-column))
12516 (col1 (if left (1- col) col))
12517 (beg (org-table-begin))
12518 (end (org-table-end))
12519 ;; Current cursor position
12520 (linepos (org-current-line))
12521 (colpos (if left (1- col) (1+ col))))
12522 (if (and left (= col 1))
12523 (error "Cannot move column further left"))
12524 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
12525 (error "Cannot move column further right"))
12526 (goto-char beg)
12527 (while (< (point) end)
12528 (if (org-at-table-hline-p)
12530 (org-table-goto-column col1 t)
12531 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
12532 (replace-match "|\\2|\\1|")))
12533 (beginning-of-line 2))
12534 (move-marker end nil)
12535 (goto-line linepos)
12536 (org-table-goto-column colpos)
12537 (org-table-align)
12538 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
12540 (defun org-table-move-row-down ()
12541 "Move table row down."
12542 (interactive)
12543 (org-table-move-row nil))
12544 (defun org-table-move-row-up ()
12545 "Move table row up."
12546 (interactive)
12547 (org-table-move-row 'up))
12549 (defun org-table-move-row (&optional up)
12550 "Move the current table line down. With arg UP, move it up."
12551 (interactive "P")
12552 (let ((col (current-column))
12553 (pos (point))
12554 (tonew (if up 0 2))
12555 txt)
12556 (beginning-of-line tonew)
12557 (if (not (org-at-table-p))
12558 (progn
12559 (goto-char pos)
12560 (error "Cannot move row further")))
12561 (goto-char pos)
12562 (beginning-of-line 1)
12563 (setq pos (point))
12564 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
12565 (delete-region (point) (1+ (point-at-eol)))
12566 (beginning-of-line tonew)
12567 (insert txt)
12568 (beginning-of-line 0)
12569 (move-to-column col)))
12571 (defun org-table-insert-row (&optional arg)
12572 "Insert a new row above the current line into the table.
12573 With prefix ARG, insert below the current line."
12574 (interactive "P")
12575 (if (not (org-at-table-p))
12576 (error "Not at a table"))
12577 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
12578 (new (org-table-clean-line line)))
12579 ;; Fix the first field if necessary
12580 (if (string-match "^[ \t]*| *[#$] *|" line)
12581 (setq new (replace-match (match-string 0 line) t t new)))
12582 (beginning-of-line (if arg 2 1))
12583 (let (org-table-may-need-update) (insert-before-markers new "\n"))
12584 (beginning-of-line 0)
12585 (re-search-forward "| ?" (point-at-eol) t)
12586 (and org-table-may-need-update (org-table-align))))
12588 (defun org-table-insert-hline (&optional arg)
12589 "Insert a horizontal-line below the current line into the table.
12590 With prefix ARG, insert above the current line."
12591 (interactive "P")
12592 (if (not (org-at-table-p))
12593 (error "Not at a table"))
12594 (let ((line (org-table-clean-line
12595 (buffer-substring (point-at-bol) (point-at-eol))))
12596 (col (current-column)))
12597 (while (string-match "|\\( +\\)|" line)
12598 (setq line (replace-match
12599 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
12600 ?-) "|") t t line)))
12601 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
12602 (beginning-of-line (if arg 1 2))
12603 (insert line "\n")
12604 (beginning-of-line (if arg 1 -1))
12605 (move-to-column col)))
12607 (defun org-table-clean-line (s)
12608 "Convert a table line S into a string with only \"|\" and space.
12609 In particular, this does handle wide and invisible characters."
12610 (if (string-match "^[ \t]*|-" s)
12611 ;; It's a hline, just map the characters
12612 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
12613 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
12614 (setq s (replace-match
12615 (concat "|" (make-string (org-string-width (match-string 1 s))
12616 ?\ ) "|")
12617 t t s)))
12620 (defun org-table-kill-row ()
12621 "Delete the current row or horizontal line from the table."
12622 (interactive)
12623 (if (not (org-at-table-p))
12624 (error "Not at a table"))
12625 (let ((col (current-column)))
12626 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
12627 (if (not (org-at-table-p)) (beginning-of-line 0))
12628 (move-to-column col)))
12630 (defun org-table-sort-lines (with-case &optional sorting-type)
12631 "Sort table lines according to the column at point.
12633 The position of point indicates the column to be used for
12634 sorting, and the range of lines is the range between the nearest
12635 horizontal separator lines, or the entire table of no such lines
12636 exist. If point is before the first column, you will be prompted
12637 for the sorting column. If there is an active region, the mark
12638 specifies the first line and the sorting column, while point
12639 should be in the last line to be included into the sorting.
12641 The command then prompts for the sorting type which can be
12642 alphabetically, numerically, or by time (as given in a time stamp
12643 in the field). Sorting in reverse order is also possible.
12645 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
12647 If SORTING-TYPE is specified when this function is called from a Lisp
12648 program, no prompting will take place. SORTING-TYPE must be a character,
12649 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
12650 should be done in reverse order."
12651 (interactive "P")
12652 (let* ((thisline (org-current-line))
12653 (thiscol (org-table-current-column))
12654 beg end bcol ecol tend tbeg column lns pos)
12655 (when (equal thiscol 0)
12656 (if (interactive-p)
12657 (setq thiscol
12658 (string-to-number
12659 (read-string "Use column N for sorting: ")))
12660 (setq thiscol 1))
12661 (org-table-goto-column thiscol))
12662 (org-table-check-inside-data-field)
12663 (if (org-region-active-p)
12664 (progn
12665 (setq beg (region-beginning) end (region-end))
12666 (goto-char beg)
12667 (setq column (org-table-current-column)
12668 beg (point-at-bol))
12669 (goto-char end)
12670 (setq end (point-at-bol 2)))
12671 (setq column (org-table-current-column)
12672 pos (point)
12673 tbeg (org-table-begin)
12674 tend (org-table-end))
12675 (if (re-search-backward org-table-hline-regexp tbeg t)
12676 (setq beg (point-at-bol 2))
12677 (goto-char tbeg)
12678 (setq beg (point-at-bol 1)))
12679 (goto-char pos)
12680 (if (re-search-forward org-table-hline-regexp tend t)
12681 (setq beg (point-at-bol 0))
12682 (goto-char tend)
12683 (setq end (point-at-bol))))
12684 (setq beg (move-marker (make-marker) beg)
12685 end (move-marker (make-marker) end))
12686 (untabify beg end)
12687 (goto-char beg)
12688 (org-table-goto-column column)
12689 (skip-chars-backward "^|")
12690 (setq bcol (current-column))
12691 (org-table-goto-column (1+ column))
12692 (skip-chars-backward "^|")
12693 (setq ecol (1- (current-column)))
12694 (org-table-goto-column column)
12695 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
12696 (org-split-string (buffer-substring beg end) "\n")))
12697 (setq lns (org-do-sort lns "Table" with-case sorting-type))
12698 (delete-region beg end)
12699 (move-marker beg nil)
12700 (move-marker end nil)
12701 (insert (mapconcat 'cdr lns "\n") "\n")
12702 (goto-line thisline)
12703 (org-table-goto-column thiscol)
12704 (message "%d lines sorted, based on column %d" (length lns) column)))
12706 (defun org-table-cut-region (beg end)
12707 "Copy region in table to the clipboard and blank all relevant fields."
12708 (interactive "r")
12709 (org-table-copy-region beg end 'cut))
12711 (defun org-table-copy-region (beg end &optional cut)
12712 "Copy rectangular region in table to clipboard.
12713 A special clipboard is used which can only be accessed
12714 with `org-table-paste-rectangle'."
12715 (interactive "rP")
12716 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
12717 region cols
12718 (rpl (if cut " " nil)))
12719 (goto-char beg)
12720 (org-table-check-inside-data-field)
12721 (setq l01 (count-lines (point-min) (point))
12722 c01 (org-table-current-column))
12723 (goto-char end)
12724 (org-table-check-inside-data-field)
12725 (setq l02 (count-lines (point-min) (point))
12726 c02 (org-table-current-column))
12727 (setq l1 (min l01 l02) l2 (max l01 l02)
12728 c1 (min c01 c02) c2 (max c01 c02))
12729 (catch 'exit
12730 (while t
12731 (catch 'nextline
12732 (if (> l1 l2) (throw 'exit t))
12733 (goto-line l1)
12734 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
12735 (setq cols nil ic1 c1 ic2 c2)
12736 (while (< ic1 (1+ ic2))
12737 (push (org-table-get-field ic1 rpl) cols)
12738 (setq ic1 (1+ ic1)))
12739 (push (nreverse cols) region)
12740 (setq l1 (1+ l1)))))
12741 (setq org-table-clip (nreverse region))
12742 (if cut (org-table-align))
12743 org-table-clip))
12745 (defun org-table-paste-rectangle ()
12746 "Paste a rectangular region into a table.
12747 The upper right corner ends up in the current field. All involved fields
12748 will be overwritten. If the rectangle does not fit into the present table,
12749 the table is enlarged as needed. The process ignores horizontal separator
12750 lines."
12751 (interactive)
12752 (unless (and org-table-clip (listp org-table-clip))
12753 (error "First cut/copy a region to paste!"))
12754 (org-table-check-inside-data-field)
12755 (let* ((clip org-table-clip)
12756 (line (count-lines (point-min) (point)))
12757 (col (org-table-current-column))
12758 (org-enable-table-editor t)
12759 (org-table-automatic-realign nil)
12760 c cols field)
12761 (while (setq cols (pop clip))
12762 (while (org-at-table-hline-p) (beginning-of-line 2))
12763 (if (not (org-at-table-p))
12764 (progn (end-of-line 0) (org-table-next-field)))
12765 (setq c col)
12766 (while (setq field (pop cols))
12767 (org-table-goto-column c nil 'force)
12768 (org-table-get-field nil field)
12769 (setq c (1+ c)))
12770 (beginning-of-line 2))
12771 (goto-line line)
12772 (org-table-goto-column col)
12773 (org-table-align)))
12775 (defun org-table-convert ()
12776 "Convert from `org-mode' table to table.el and back.
12777 Obviously, this only works within limits. When an Org-mode table is
12778 converted to table.el, all horizontal separator lines get lost, because
12779 table.el uses these as cell boundaries and has no notion of horizontal lines.
12780 A table.el table can be converted to an Org-mode table only if it does not
12781 do row or column spanning. Multiline cells will become multiple cells.
12782 Beware, Org-mode does not test if the table can be successfully converted - it
12783 blindly applies a recipe that works for simple tables."
12784 (interactive)
12785 (require 'table)
12786 (if (org-at-table.el-p)
12787 ;; convert to Org-mode table
12788 (let ((beg (move-marker (make-marker) (org-table-begin t)))
12789 (end (move-marker (make-marker) (org-table-end t))))
12790 (table-unrecognize-region beg end)
12791 (goto-char beg)
12792 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
12793 (replace-match ""))
12794 (goto-char beg))
12795 (if (org-at-table-p)
12796 ;; convert to table.el table
12797 (let ((beg (move-marker (make-marker) (org-table-begin)))
12798 (end (move-marker (make-marker) (org-table-end))))
12799 ;; first, get rid of all horizontal lines
12800 (goto-char beg)
12801 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
12802 (replace-match ""))
12803 ;; insert a hline before first
12804 (goto-char beg)
12805 (org-table-insert-hline 'above)
12806 (beginning-of-line -1)
12807 ;; insert a hline after each line
12808 (while (progn (beginning-of-line 3) (< (point) end))
12809 (org-table-insert-hline))
12810 (goto-char beg)
12811 (setq end (move-marker end (org-table-end)))
12812 ;; replace "+" at beginning and ending of hlines
12813 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
12814 (replace-match "\\1+-"))
12815 (goto-char beg)
12816 (while (re-search-forward "-|[ \t]*$" end t)
12817 (replace-match "-+"))
12818 (goto-char beg)))))
12820 (defun org-table-wrap-region (arg)
12821 "Wrap several fields in a column like a paragraph.
12822 This is useful if you'd like to spread the contents of a field over several
12823 lines, in order to keep the table compact.
12825 If there is an active region, and both point and mark are in the same column,
12826 the text in the column is wrapped to minimum width for the given number of
12827 lines. Generally, this makes the table more compact. A prefix ARG may be
12828 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
12829 formats the selected text to two lines. If the region was longer than two
12830 lines, the remaining lines remain empty. A negative prefix argument reduces
12831 the current number of lines by that amount. The wrapped text is pasted back
12832 into the table. If you formatted it to more lines than it was before, fields
12833 further down in the table get overwritten - so you might need to make space in
12834 the table first.
12836 If there is no region, the current field is split at the cursor position and
12837 the text fragment to the right of the cursor is prepended to the field one
12838 line down.
12840 If there is no region, but you specify a prefix ARG, the current field gets
12841 blank, and the content is appended to the field above."
12842 (interactive "P")
12843 (org-table-check-inside-data-field)
12844 (if (org-region-active-p)
12845 ;; There is a region: fill as a paragraph
12846 (let ((beg (region-beginning))
12847 nlines)
12848 (org-table-cut-region (region-beginning) (region-end))
12849 (if (> (length (car org-table-clip)) 1)
12850 (error "Region must be limited to single column"))
12851 (setq nlines (if arg
12852 (if (< arg 1)
12853 (+ (length org-table-clip) arg)
12854 arg)
12855 (length org-table-clip)))
12856 (setq org-table-clip
12857 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
12858 nil nlines)))
12859 (goto-char beg)
12860 (org-table-paste-rectangle))
12861 ;; No region, split the current field at point
12862 (if arg
12863 ;; combine with field above
12864 (let ((s (org-table-blank-field))
12865 (col (org-table-current-column)))
12866 (beginning-of-line 0)
12867 (while (org-at-table-hline-p) (beginning-of-line 0))
12868 (org-table-goto-column col)
12869 (skip-chars-forward "^|")
12870 (skip-chars-backward " ")
12871 (insert " " (org-trim s))
12872 (org-table-align))
12873 ;; split field
12874 (when (looking-at "\\([^|]+\\)+|")
12875 (let ((s (match-string 1)))
12876 (replace-match " |")
12877 (goto-char (match-beginning 0))
12878 (org-table-next-row)
12879 (insert (org-trim s) " ")
12880 (org-table-align))))))
12882 (defvar org-field-marker nil)
12884 (defun org-table-edit-field (arg)
12885 "Edit table field in a different window.
12886 This is mainly useful for fields that contain hidden parts.
12887 When called with a \\[universal-argument] prefix, just make the full field visible so that
12888 it can be edited in place."
12889 (interactive "P")
12890 (if arg
12891 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
12892 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
12893 (remove-text-properties b e '(org-cwidth t invisible t
12894 display t intangible t))
12895 (if (and (boundp 'font-lock-mode) font-lock-mode)
12896 (font-lock-fontify-block)))
12897 (let ((pos (move-marker (make-marker) (point)))
12898 (field (org-table-get-field))
12899 (cw (current-window-configuration))
12901 (switch-to-buffer-other-window "*Org tmp*")
12902 (erase-buffer)
12903 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
12904 (org-mode)
12905 (goto-char (setq p (point-max)))
12906 (insert (org-trim field))
12907 (remove-text-properties p (point-max)
12908 '(invisible t org-cwidth t display t
12909 intangible t))
12910 (goto-char p)
12911 (org-set-local 'org-finish-function
12912 'org-table-finish-edit-field)
12913 (org-set-local 'org-window-configuration cw)
12914 (org-set-local 'org-field-marker pos)
12915 (message "Edit and finish with C-c C-c"))))
12917 (defun org-table-finish-edit-field ()
12918 "Finish editing a table data field.
12919 Remove all newline characters, insert the result into the table, realign
12920 the table and kill the editing buffer."
12921 (let ((pos org-field-marker)
12922 (cw org-window-configuration)
12923 (cb (current-buffer))
12924 text)
12925 (goto-char (point-min))
12926 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
12927 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
12928 (replace-match " "))
12929 (setq text (org-trim (buffer-string)))
12930 (set-window-configuration cw)
12931 (kill-buffer cb)
12932 (select-window (get-buffer-window (marker-buffer pos)))
12933 (goto-char pos)
12934 (move-marker pos nil)
12935 (org-table-check-inside-data-field)
12936 (org-table-get-field nil text)
12937 (org-table-align)
12938 (message "New field value inserted")))
12940 (defun org-trim (s)
12941 "Remove whitespace at beginning and end of string."
12942 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
12943 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
12946 (defun org-wrap (string &optional width lines)
12947 "Wrap string to either a number of lines, or a width in characters.
12948 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12949 that costs. If there is a word longer than WIDTH, the text is actually
12950 wrapped to the length of that word.
12951 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12952 many lines, whatever width that takes.
12953 The return value is a list of lines, without newlines at the end."
12954 (let* ((words (org-split-string string "[ \t\n]+"))
12955 (maxword (apply 'max (mapcar 'org-string-width words)))
12956 w ll)
12957 (cond (width
12958 (org-do-wrap words (max maxword width)))
12959 (lines
12960 (setq w maxword)
12961 (setq ll (org-do-wrap words maxword))
12962 (if (<= (length ll) lines)
12964 (setq ll words)
12965 (while (> (length ll) lines)
12966 (setq w (1+ w))
12967 (setq ll (org-do-wrap words w)))
12968 ll))
12969 (t (error "Cannot wrap this")))))
12972 (defun org-do-wrap (words width)
12973 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12974 (let (lines line)
12975 (while words
12976 (setq line (pop words))
12977 (while (and words (< (+ (length line) (length (car words))) width))
12978 (setq line (concat line " " (pop words))))
12979 (setq lines (push line lines)))
12980 (nreverse lines)))
12982 (defun org-split-string (string &optional separators)
12983 "Splits STRING into substrings at SEPARATORS.
12984 No empty strings are returned if there are matches at the beginning
12985 and end of string."
12986 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12987 (start 0)
12988 notfirst
12989 (list nil))
12990 (while (and (string-match rexp string
12991 (if (and notfirst
12992 (= start (match-beginning 0))
12993 (< start (length string)))
12994 (1+ start) start))
12995 (< (match-beginning 0) (length string)))
12996 (setq notfirst t)
12997 (or (eq (match-beginning 0) 0)
12998 (and (eq (match-beginning 0) (match-end 0))
12999 (eq (match-beginning 0) start))
13000 (setq list
13001 (cons (substring string start (match-beginning 0))
13002 list)))
13003 (setq start (match-end 0)))
13004 (or (eq start (length string))
13005 (setq list
13006 (cons (substring string start)
13007 list)))
13008 (nreverse list)))
13010 (defun org-table-map-tables (function)
13011 "Apply FUNCTION to the start of all tables in the buffer."
13012 (save-excursion
13013 (save-restriction
13014 (widen)
13015 (goto-char (point-min))
13016 (while (re-search-forward org-table-any-line-regexp nil t)
13017 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
13018 (beginning-of-line 1)
13019 (if (looking-at org-table-line-regexp)
13020 (save-excursion (funcall function)))
13021 (re-search-forward org-table-any-border-regexp nil 1))))
13022 (message "Mapping tables: done"))
13024 (defun org-table-sum (&optional beg end nlast)
13025 "Sum numbers in region of current table column.
13026 The result will be displayed in the echo area, and will be available
13027 as kill to be inserted with \\[yank].
13029 If there is an active region, it is interpreted as a rectangle and all
13030 numbers in that rectangle will be summed. If there is no active
13031 region and point is located in a table column, sum all numbers in that
13032 column.
13034 If at least one number looks like a time HH:MM or HH:MM:SS, all other
13035 numbers are assumed to be times as well (in decimal hours) and the
13036 numbers are added as such.
13038 If NLAST is a number, only the NLAST fields will actually be summed."
13039 (interactive)
13040 (save-excursion
13041 (let (col (timecnt 0) diff h m s org-table-clip)
13042 (cond
13043 ((and beg end)) ; beg and end given explicitly
13044 ((org-region-active-p)
13045 (setq beg (region-beginning) end (region-end)))
13047 (setq col (org-table-current-column))
13048 (goto-char (org-table-begin))
13049 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
13050 (error "No table data"))
13051 (org-table-goto-column col)
13052 ;not needed? (skip-chars-backward "^|")
13053 (setq beg (point))
13054 (goto-char (org-table-end))
13055 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
13056 (error "No table data"))
13057 (org-table-goto-column col)
13058 ;not needed? (skip-chars-forward "^|")
13059 (setq end (point))))
13060 (let* ((items (apply 'append (org-table-copy-region beg end)))
13061 (items1 (cond ((not nlast) items)
13062 ((>= nlast (length items)) items)
13063 (t (setq items (reverse items))
13064 (setcdr (nthcdr (1- nlast) items) nil)
13065 (nreverse items))))
13066 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
13067 items1)))
13068 (res (apply '+ numbers))
13069 (sres (if (= timecnt 0)
13070 (format "%g" res)
13071 (setq diff (* 3600 res)
13072 h (floor (/ diff 3600)) diff (mod diff 3600)
13073 m (floor (/ diff 60)) diff (mod diff 60)
13074 s diff)
13075 (format "%d:%02d:%02d" h m s))))
13076 (kill-new sres)
13077 (if (interactive-p)
13078 (message "%s"
13079 (substitute-command-keys
13080 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
13081 (length numbers) sres))))
13082 sres))))
13084 (defun org-table-get-number-for-summing (s)
13085 (let (n)
13086 (if (string-match "^ *|? *" s)
13087 (setq s (replace-match "" nil nil s)))
13088 (if (string-match " *|? *$" s)
13089 (setq s (replace-match "" nil nil s)))
13090 (setq n (string-to-number s))
13091 (cond
13092 ((and (string-match "0" s)
13093 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
13094 ((string-match "\\`[ \t]+\\'" s) nil)
13095 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
13096 (let ((h (string-to-number (or (match-string 1 s) "0")))
13097 (m (string-to-number (or (match-string 2 s) "0")))
13098 (s (string-to-number (or (match-string 4 s) "0"))))
13099 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
13100 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
13101 ((equal n 0) nil)
13102 (t n))))
13104 (defun org-table-get-vertical-vector (desc &optional tbeg col)
13105 "Get a calc vector from a column, accorting to descriptor DESC.
13106 Optional arguments TBEG and COL can give the beginning of the table and
13107 the current column, to avoid unnecessary parsing."
13108 (save-excursion
13109 (or tbeg (setq tbeg (org-table-begin)))
13110 (or col (setq col (org-table-current-column)))
13111 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
13112 (cond
13113 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
13114 (setq n1 (- (match-end 1) (match-beginning 1)))
13115 (if (match-beginning 3)
13116 (setq n2 (- (match-end 2) (match-beginning 3))))
13117 (setq n (if n2 (max n1 n2) n1))
13118 (setq n1 (if n2 (min n1 n2)))
13119 (setq nn n)
13120 (while (and (> nn 0)
13121 (re-search-backward org-table-hline-regexp tbeg t))
13122 (push (org-current-line) hline-list)
13123 (setq nn (1- nn)))
13124 (setq hline-list (nreverse hline-list))
13125 (goto-line (nth (1- n) hline-list))
13126 (when (re-search-forward org-table-dataline-regexp)
13127 (org-table-goto-column col)
13128 (setq beg (point)))
13129 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
13130 (when (re-search-backward org-table-dataline-regexp)
13131 (org-table-goto-column col)
13132 (setq end (point)))
13133 (setq l (apply 'append (org-table-copy-region beg end)))
13134 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
13135 (if (equal x "") "0" x))
13136 l ",") "]"))
13137 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
13138 (setq n1 (string-to-number (match-string 1 desc))
13139 n2 (string-to-number (match-string 2 desc)))
13140 (beginning-of-line 1)
13141 (save-excursion
13142 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
13143 (org-table-goto-column col)
13144 (setq beg (point))))
13145 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
13146 (org-table-goto-column col)
13147 (setq end (point)))
13148 (setq l (apply 'append (org-table-copy-region beg end)))
13149 (concat "[" (mapconcat
13150 (lambda (x) (setq x (org-trim x))
13151 (if (equal x "") "0" x))
13152 l ",") "]"))
13153 ((string-match "\\([0-9]+\\)" desc)
13154 (beginning-of-line 1)
13155 (when (re-search-backward org-table-dataline-regexp tbeg t
13156 (string-to-number (match-string 0 desc)))
13157 (org-table-goto-column col)
13158 (org-trim (org-table-get-field))))))))
13160 (defvar org-table-formula-history nil)
13162 (defvar org-table-column-names nil
13163 "Alist with column names, derived from the `!' line.")
13164 (defvar org-table-column-name-regexp nil
13165 "Regular expression matching the current column names.")
13166 (defvar org-table-local-parameters nil
13167 "Alist with parameter names, derived from the `$' line.")
13168 (defvar org-table-named-field-locations nil
13169 "Alist with locations of named fields.")
13171 (defun org-table-get-formula (&optional equation named)
13172 "Read a formula from the minibuffer, offer stored formula as default."
13173 (let* ((name (car (rassoc (list (org-current-line)
13174 (org-table-current-column))
13175 org-table-named-field-locations)))
13176 (scol (if named
13177 (if name name
13178 (error "Not in a named field"))
13179 (int-to-string (org-table-current-column))))
13180 (dummy (and name (not named)
13181 (not (y-or-n-p "Replace named-field formula with column equation? " ))
13182 (error "Abort")))
13183 (org-table-may-need-update nil)
13184 (stored-list (org-table-get-stored-formulas))
13185 (stored (cdr (assoc scol stored-list)))
13186 (eq (cond
13187 ((and stored equation (string-match "^ *=? *$" equation))
13188 stored)
13189 ((stringp equation)
13190 equation)
13191 (t (read-string
13192 (format "%s formula $%s=" (if named "Field" "Column") scol)
13193 (or stored "") 'org-table-formula-history
13194 ;stored
13195 ))))
13196 mustsave)
13197 (when (not (string-match "\\S-" eq))
13198 ;; remove formula
13199 (setq stored-list (delq (assoc scol stored-list) stored-list))
13200 (org-table-store-formulas stored-list)
13201 (error "Formula removed"))
13202 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
13203 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
13204 (if (and name (not named))
13205 ;; We set the column equation, delete the named one.
13206 (setq stored-list (delq (assoc name stored-list) stored-list)
13207 mustsave t))
13208 (if stored
13209 (setcdr (assoc scol stored-list) eq)
13210 (setq stored-list (cons (cons scol eq) stored-list)))
13211 (if (or mustsave (not (equal stored eq)))
13212 (org-table-store-formulas stored-list))
13213 eq))
13215 (defun org-table-store-formulas (alist)
13216 "Store the list of formulas below the current table."
13217 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
13218 (save-excursion
13219 (goto-char (org-table-end))
13220 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
13221 (delete-region (point) (match-end 0)))
13222 (insert "#+TBLFM: "
13223 (mapconcat (lambda (x)
13224 (concat "$" (car x) "=" (cdr x)))
13225 alist "::")
13226 "\n")))
13228 (defun org-table-get-stored-formulas ()
13229 "Return an alist with the stored formulas directly after current table."
13230 (interactive)
13231 (let (scol eq eq-alist strings string seen)
13232 (save-excursion
13233 (goto-char (org-table-end))
13234 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
13235 (setq strings (org-split-string (match-string 2) " *:: *"))
13236 (while (setq string (pop strings))
13237 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
13238 (setq scol (match-string 1 string)
13239 eq (match-string 2 string)
13240 eq-alist (cons (cons scol eq) eq-alist))
13241 (if (member scol seen)
13242 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
13243 (push scol seen))))))
13244 (nreverse eq-alist)))
13246 (defun org-table-modify-formulas (action &rest columns)
13247 "Modify the formulas stored below the current table.
13248 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
13249 expected, for the other actions only a single column number is needed."
13250 (let ((list (org-table-get-stored-formulas))
13251 (nmax (length (org-split-string
13252 (buffer-substring (point-at-bol) (point-at-eol))
13253 "|")))
13254 col col1 col2 scol si sc1 sc2)
13255 (cond
13256 ((null list)) ; No action needed if there are no stored formulas
13257 ((eq action 'remove)
13258 (setq col (car columns)
13259 scol (int-to-string col))
13260 (org-table-replace-in-formulas list scol "INVALID")
13261 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
13262 (loop for i from (1+ col) upto nmax by 1 do
13263 (setq si (int-to-string i))
13264 (org-table-replace-in-formulas list si (int-to-string (1- i)))
13265 (if (assoc si list) (setcar (assoc si list)
13266 (int-to-string (1- i))))))
13267 ((eq action 'insert)
13268 (setq col (car columns))
13269 (loop for i from nmax downto col by 1 do
13270 (setq si (int-to-string i))
13271 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
13272 (if (assoc si list) (setcar (assoc si list)
13273 (int-to-string (1+ i))))))
13274 ((eq action 'swap)
13275 (setq col1 (car columns) col2 (nth 1 columns)
13276 sc1 (int-to-string col1) sc2 (int-to-string col2))
13277 ;; Hopefully, ZqZtZ will never be a name in a table
13278 (org-table-replace-in-formulas list sc1 "ZqZtZ")
13279 (org-table-replace-in-formulas list sc2 sc1)
13280 (org-table-replace-in-formulas list "ZqZtZ" sc2)
13281 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
13282 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
13283 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
13284 (t (error "Invalid action in `org-table-modify-formulas'")))
13285 (if list (org-table-store-formulas list))))
13287 (defun org-table-replace-in-formulas (list s1 s2)
13288 (let (elt re s)
13289 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
13290 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
13291 re (concat (regexp-quote s1) "\\>"))
13292 (while (setq elt (pop list))
13293 (setq s (cdr elt))
13294 (while (string-match re s)
13295 (setq s (replace-match s2 t t s)))
13296 (setcdr elt s))))
13298 (defun org-table-get-specials ()
13299 "Get the column names and local parameters for this table."
13300 (save-excursion
13301 (let ((beg (org-table-begin)) (end (org-table-end))
13302 names name fields fields1 field cnt c v line col)
13303 (setq org-table-column-names nil
13304 org-table-local-parameters nil
13305 org-table-named-field-locations nil)
13306 (goto-char beg)
13307 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
13308 (setq names (org-split-string (match-string 1) " *| *")
13309 cnt 1)
13310 (while (setq name (pop names))
13311 (setq cnt (1+ cnt))
13312 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
13313 (push (cons name (int-to-string cnt)) org-table-column-names))))
13314 (setq org-table-column-names (nreverse org-table-column-names))
13315 (setq org-table-column-name-regexp
13316 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
13317 (goto-char beg)
13318 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
13319 (setq fields (org-split-string (match-string 1) " *| *"))
13320 (while (setq field (pop fields))
13321 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
13322 (push (cons (match-string 1 field) (match-string 2 field))
13323 org-table-local-parameters))))
13324 (goto-char beg)
13325 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
13326 (setq c (match-string 1)
13327 fields (org-split-string (match-string 2) " *| *"))
13328 (save-excursion
13329 (beginning-of-line (if (equal c "_") 2 0))
13330 (setq line (org-current-line) col 1)
13331 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
13332 (setq fields1 (org-split-string (match-string 1) " *| *"))))
13333 (while (and fields1 (setq field (pop fields)))
13334 (setq v (pop fields1) col (1+ col))
13335 (when (and (stringp field) (stringp v)
13336 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
13337 (push (cons field v) org-table-local-parameters)
13338 (push (list field line col) org-table-named-field-locations)))))))
13340 (defun org-this-word ()
13341 ;; Get the current word
13342 (save-excursion
13343 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
13344 (end (progn (skip-chars-forward "^ \t\n") (point))))
13345 (buffer-substring-no-properties beg end))))
13347 (defun org-table-maybe-eval-formula ()
13348 "Check if the current field starts with \"=\" or \":=\".
13349 If yes, store the formula and apply it."
13350 ;; We already know we are in a table. Get field will only return a formula
13351 ;; when appropriate. It might return a separator line, but no problem.
13352 (when org-table-formula-evaluate-inline
13353 (let* ((field (org-trim (or (org-table-get-field) "")))
13354 named eq)
13355 (when (string-match "^:?=\\(.*\\)" field)
13356 (setq named (equal (string-to-char field) ?:)
13357 eq (match-string 1 field))
13358 (if (fboundp 'calc-eval)
13359 (org-table-eval-formula (if named '(4) nil) eq))))))
13361 (defvar org-recalc-commands nil
13362 "List of commands triggering the recalculation of a line.
13363 Will be filled automatically during use.")
13365 (defvar org-recalc-marks
13366 '((" " . "Unmarked: no special line, no automatic recalculation")
13367 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
13368 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
13369 ("!" . "Column name definition line. Reference in formula as $name.")
13370 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
13371 ("_" . "Names for values in row below this one.")
13372 ("^" . "Names for values in row above this one.")))
13374 (defun org-table-rotate-recalc-marks (&optional newchar)
13375 "Rotate the recalculation mark in the first column.
13376 If in any row, the first field is not consistent with a mark,
13377 insert a new column for the markers.
13378 When there is an active region, change all the lines in the region,
13379 after prompting for the marking character.
13380 After each change, a message will be displayed indicating the meaning
13381 of the new mark."
13382 (interactive)
13383 (unless (org-at-table-p) (error "Not at a table"))
13384 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
13385 (beg (org-table-begin))
13386 (end (org-table-end))
13387 (l (org-current-line))
13388 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
13389 (l2 (if (org-region-active-p) (org-current-line (region-end))))
13390 (have-col
13391 (save-excursion
13392 (goto-char beg)
13393 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
13394 (col (org-table-current-column))
13395 (forcenew (car (assoc newchar org-recalc-marks)))
13396 epos new)
13397 (when l1
13398 (message "Change region to what mark? Type # * ! $ or SPC: ")
13399 (setq newchar (char-to-string (read-char-exclusive))
13400 forcenew (car (assoc newchar org-recalc-marks))))
13401 (if (and newchar (not forcenew))
13402 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
13403 newchar))
13404 (if l1 (goto-line l1))
13405 (save-excursion
13406 (beginning-of-line 1)
13407 (unless (looking-at org-table-dataline-regexp)
13408 (error "Not at a table data line")))
13409 (unless have-col
13410 (org-table-goto-column 1)
13411 (org-table-insert-column)
13412 (org-table-goto-column (1+ col)))
13413 (setq epos (point-at-eol))
13414 (save-excursion
13415 (beginning-of-line 1)
13416 (org-table-get-field
13417 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
13418 (concat " "
13419 (setq new (or forcenew
13420 (cadr (member (match-string 1) marks))))
13421 " ")
13422 " # ")))
13423 (if (and l1 l2)
13424 (progn
13425 (goto-line l1)
13426 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
13427 (and (looking-at org-table-dataline-regexp)
13428 (org-table-get-field 1 (concat " " new " "))))
13429 (goto-line l1)))
13430 (if (not (= epos (point-at-eol))) (org-table-align))
13431 (goto-line l)
13432 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
13434 (defun org-table-maybe-recalculate-line ()
13435 "Recompute the current line if marked for it, and if we haven't just done it."
13436 (interactive)
13437 (and org-table-allow-automatic-line-recalculation
13438 (not (and (memq last-command org-recalc-commands)
13439 (equal org-last-recalc-line (org-current-line))))
13440 (save-excursion (beginning-of-line 1)
13441 (looking-at org-table-auto-recalculate-regexp))
13442 (fboundp 'calc-eval)
13443 (org-table-recalculate) t))
13445 (defvar org-table-formula-debug nil
13446 "Non-nil means, debug table formulas.
13447 When nil, simply write \"#ERROR\" in corrupted fields.")
13449 (defvar modes)
13450 (defsubst org-set-calc-mode (var &optional value)
13451 (if (stringp var)
13452 (setq var (assoc var '(("D" calc-angle-mode deg)
13453 ("R" calc-angle-mode rad)
13454 ("F" calc-prefer-frac t)
13455 ("S" calc-symbolic-mode t)))
13456 value (nth 2 var) var (nth 1 var)))
13457 (if (memq var modes)
13458 (setcar (cdr (memq var modes)) value)
13459 (cons var (cons value modes)))
13460 modes)
13462 (defun org-table-eval-formula (&optional arg equation
13463 suppress-align suppress-const
13464 suppress-store)
13465 "Replace the table field value at the cursor by the result of a calculation.
13467 This function makes use of Dave Gillespie's Calc package, in my view the
13468 most exciting program ever written for GNU Emacs. So you need to have Calc
13469 installed in order to use this function.
13471 In a table, this command replaces the value in the current field with the
13472 result of a formula. It also installs the formula as the \"current\" column
13473 formula, by storing it in a special line below the table. When called
13474 with a `C-u' prefix, the current field must ba a named field, and the
13475 formula is installed as valid in only this specific field.
13477 When called, the command first prompts for a formula, which is read in
13478 the minibuffer. Previously entered formulas are available through the
13479 history list, and the last used formula is offered as a default.
13480 These stored formulas are adapted correctly when moving, inserting, or
13481 deleting columns with the corresponding commands.
13483 The formula can be any algebraic expression understood by the Calc package.
13484 For details, see the Org-mode manual.
13486 This function can also be called from Lisp programs and offers
13487 additional arguments: EQUATION can be the formula to apply. If this
13488 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
13489 used to speed-up recursive calls by by-passing unnecessary aligns.
13490 SUPPRESS-CONST suppresses the interpretation of constants in the
13491 formula, assuming that this has been done already outside the function.
13492 SUPPRESS-STORE means the formula should not be stored, either because
13493 it is already stored, or because it is a modified equation that should
13494 not overwrite the stored one."
13495 (interactive "P")
13496 (require 'calc)
13497 (org-table-check-inside-data-field)
13498 (org-table-get-specials)
13499 (let* (fields
13500 (ndown (if (integerp arg) arg 1))
13501 (org-table-automatic-realign nil)
13502 (case-fold-search nil)
13503 (down (> ndown 1))
13504 (formula (if (and equation suppress-store)
13505 equation
13506 (org-table-get-formula equation (equal arg '(4)))))
13507 (n0 (org-table-current-column))
13508 (modes (copy-sequence org-calc-default-modes))
13509 n form fmt x ev orig c lispp)
13510 ;; Parse the format string. Since we have a lot of modes, this is
13511 ;; a lot of work. However, I think calc still uses most of the time.
13512 (if (string-match ";" formula)
13513 (let ((tmp (org-split-string formula ";")))
13514 (setq formula (car tmp)
13515 fmt (concat (cdr (assoc "%" org-table-local-parameters))
13516 (nth 1 tmp)))
13517 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
13518 (setq c (string-to-char (match-string 1 fmt))
13519 n (string-to-number (match-string 2 fmt)))
13520 (if (= c ?p)
13521 (setq modes (org-set-calc-mode 'calc-internal-prec n))
13522 (setq modes (org-set-calc-mode
13523 'calc-float-format
13524 (list (cdr (assoc c '((?n . float) (?f . fix)
13525 (?s . sci) (?e . eng))))
13526 n))))
13527 (setq fmt (replace-match "" t t fmt)))
13528 (while (string-match "[DRFS]" fmt)
13529 (setq modes (org-set-calc-mode (match-string 0 fmt)))
13530 (setq fmt (replace-match "" t t fmt)))
13531 (unless (string-match "\\S-" fmt)
13532 (setq fmt nil))))
13533 (if (and (not suppress-const) org-table-formula-use-constants)
13534 (setq formula (org-table-formula-substitute-names formula)))
13535 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
13536 (while (> ndown 0)
13537 (setq fields (org-split-string
13538 (buffer-substring
13539 (point-at-bol) (point-at-eol)) " *| *"))
13540 (if org-table-formula-numbers-only
13541 (setq fields (mapcar
13542 (lambda (x) (number-to-string (string-to-number x)))
13543 fields)))
13544 (setq ndown (1- ndown))
13545 (setq form (copy-sequence formula)
13546 lispp (equal (substring form 0 2) "'("))
13547 ;; Insert the references to fields in same row
13548 (while (string-match "\\$\\([0-9]+\\)?" form)
13549 (setq n (if (match-beginning 1)
13550 (string-to-number (match-string 1 form))
13552 x (nth (1- n) fields))
13553 (unless x (error "Invalid field specifier \"%s\""
13554 (match-string 0 form)))
13555 (if (equal x "") (setq x "0"))
13556 (setq form (replace-match
13557 (if lispp x (concat "(" x ")"))
13558 t t form)))
13559 ;; Insert ranges in current column
13560 (while (string-match "\\&[-I0-9]+" form)
13561 (setq form (replace-match
13562 (save-match-data
13563 (org-table-get-vertical-vector (match-string 0 form)
13564 nil n0))
13565 t t form)))
13566 (if lispp
13567 (setq ev (eval (eval (read form)))
13568 ev (if (numberp ev) (number-to-string ev) ev))
13569 (setq ev (calc-eval (cons form modes)
13570 (if org-table-formula-numbers-only 'num))))
13572 (when org-table-formula-debug
13573 (with-output-to-temp-buffer "*Help*"
13574 (princ (format "Substitution history of formula
13575 Orig: %s
13576 $xyz-> %s
13577 $1-> %s\n" orig formula form))
13578 (if (listp ev)
13579 (princ (format " %s^\nError: %s"
13580 (make-string (car ev) ?\-) (nth 1 ev)))
13581 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
13582 ev (or fmt "NONE")
13583 (if fmt (format fmt (string-to-number ev)) ev)))))
13584 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
13585 (unless (and (interactive-p) (not ndown))
13586 (unless (let (inhibit-redisplay)
13587 (y-or-n-p "Debugging Formula. Continue to next? "))
13588 (org-table-align)
13589 (error "Abort"))
13590 (delete-window (get-buffer-window "*Help*"))
13591 (message "")))
13592 (if (listp ev) (setq fmt nil ev "#ERROR"))
13593 (org-table-justify-field-maybe
13594 (if fmt (format fmt (string-to-number ev)) ev))
13595 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
13596 (call-interactively 'org-return)
13597 (setq ndown 0)))
13598 (and down (org-table-maybe-recalculate-line))
13599 (or suppress-align (and org-table-may-need-update
13600 (org-table-align)))))
13602 (defun org-table-recalculate (&optional all noalign)
13603 "Recalculate the current table line by applying all stored formulas.
13604 With prefix arg ALL, do this for all lines in the table."
13605 (interactive "P")
13606 (or (memq this-command org-recalc-commands)
13607 (setq org-recalc-commands (cons this-command org-recalc-commands)))
13608 (unless (org-at-table-p) (error "Not at a table"))
13609 (org-table-get-specials)
13610 (let* ((eqlist (sort (org-table-get-stored-formulas)
13611 (lambda (a b) (string< (car a) (car b)))))
13612 (inhibit-redisplay t)
13613 (line-re org-table-dataline-regexp)
13614 (thisline (org-current-line))
13615 (thiscol (org-table-current-column))
13616 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
13617 ;; Insert constants in all formulas
13618 (setq eqlist
13619 (mapcar (lambda (x)
13620 (setcdr x (org-table-formula-substitute-names (cdr x)))
13622 eqlist))
13623 ;; Split the equation list
13624 (while (setq eq (pop eqlist))
13625 (if (<= (string-to-char (car eq)) ?9)
13626 (push eq eqlnum)
13627 (push eq eqlname)))
13628 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
13629 (if all
13630 (progn
13631 (setq end (move-marker (make-marker) (1+ (org-table-end))))
13632 (goto-char (setq beg (org-table-begin)))
13633 (if (re-search-forward org-table-calculate-mark-regexp end t)
13634 ;; This is a table with marked lines, only compute selected lines
13635 (setq line-re org-table-recalculate-regexp)
13636 ;; Move forward to the first non-header line
13637 (if (and (re-search-forward org-table-dataline-regexp end t)
13638 (re-search-forward org-table-hline-regexp end t)
13639 (re-search-forward org-table-dataline-regexp end t))
13640 (setq beg (match-beginning 0))
13641 nil))) ;; just leave beg where it is
13642 (setq beg (point-at-bol)
13643 end (move-marker (make-marker) (1+ (point-at-eol)))))
13644 (goto-char beg)
13645 (and all (message "Re-applying formulas to full table..."))
13646 (while (re-search-forward line-re end t)
13647 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
13648 ;; Unprotected line, recalculate
13649 (and all (message "Re-applying formulas to full table...(line %d)"
13650 (setq cnt (1+ cnt))))
13651 (setq org-last-recalc-line (org-current-line))
13652 (setq eql eqlnum)
13653 (while (setq entry (pop eql))
13654 (goto-line org-last-recalc-line)
13655 (org-table-goto-column (string-to-number (car entry)) nil 'force)
13656 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
13657 (goto-line thisline)
13658 (org-table-goto-column thiscol)
13659 (or noalign (and org-table-may-need-update (org-table-align))
13660 (and all (message "Re-applying formulas to %d lines...done" cnt)))
13661 ;; Now do the names fields
13662 (while (setq eq (pop eqlname))
13663 (setq name (car eq)
13664 a (assoc name org-table-named-field-locations))
13665 (when a
13666 (message "Re-applying formula to named field: %s" name)
13667 (goto-line (nth 1 a))
13668 (org-table-goto-column (nth 2 a))
13669 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
13670 ;; back to initial position
13671 (goto-line thisline)
13672 (org-table-goto-column thiscol)
13673 (or noalign (and org-table-may-need-update (org-table-align))
13674 (and all (message "Re-applying formulas...done")))))
13676 (defun org-table-formula-substitute-names (f)
13677 "Replace $const with values in string F."
13678 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
13679 ;; First, check for column names
13680 (while (setq start (string-match org-table-column-name-regexp f start))
13681 (setq start (1+ start))
13682 (setq a (assoc (match-string 1 f) org-table-column-names))
13683 (setq f (replace-match (concat "$" (cdr a)) t t f)))
13684 ;; Expand ranges to vectors
13685 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
13686 (setq n1 (string-to-number (match-string 1 f))
13687 n2 (string-to-number (match-string 2 f))
13688 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
13689 s (concat "[($" (number-to-string (1- nn1)) ")"))
13690 (loop for i from nn1 upto nn2 do
13691 (setq s (concat s ",($" (int-to-string i) ")")))
13692 (setq s (concat s "]"))
13693 (if (< n2 n1) (setq s (concat "rev(" s ")")))
13694 (setq f (replace-match s t t f)))
13695 ;; Parameters and constants
13696 (setq start 0)
13697 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
13698 (setq start (1+ start))
13699 (if (setq a (save-match-data
13700 (org-table-get-constant (match-string 1 f))))
13701 (setq f (replace-match (concat "(" a ")") t t f))))
13702 (if org-table-formula-debug
13703 (put-text-property 0 (length f) :orig-formula f1 f))
13706 (defun org-table-get-constant (const)
13707 "Find the value for a parameter or constant in a formula.
13708 Parameters get priority."
13709 (or (cdr (assoc const org-table-local-parameters))
13710 (cdr (assoc const org-table-formula-constants))
13711 (and (fboundp 'constants-get) (constants-get const))
13712 "#UNDEFINED_NAME"))
13714 (defvar org-edit-formulas-map (make-sparse-keymap))
13715 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
13716 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
13717 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
13719 (defvar org-pos)
13721 (defun org-table-edit-formulas ()
13722 "Edit the formulas of the current table in a separate buffer."
13723 (interactive)
13724 (unless (org-at-table-p)
13725 (error "Not at a table"))
13726 (org-table-get-specials)
13727 (let ((eql (org-table-get-stored-formulas))
13728 (pos (move-marker (make-marker) (point)))
13729 (wc (current-window-configuration))
13730 entry loc s)
13731 (switch-to-buffer-other-window "*Edit Formulas*")
13732 (erase-buffer)
13733 (fundamental-mode)
13734 (org-set-local 'org-pos pos)
13735 (org-set-local 'org-window-configuration wc)
13736 (use-local-map org-edit-formulas-map)
13737 (setq s "# Edit formulas and finish with `C-c C-c'.
13738 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
13739 # Use `C-c ?' to get information about $name at point.
13740 # To cancel editing, press `C-c C-q'.\n")
13741 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13742 (insert s)
13743 (while (setq entry (pop eql))
13744 (when (setq loc (assoc (car entry) org-table-named-field-locations))
13745 (setq s (format "# Named formula, referring to column %d in line %d\n"
13746 (nth 2 loc) (nth 1 loc)))
13747 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
13748 (insert s))
13749 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
13750 (remove-text-properties 0 (length s) '(face nil) s)
13751 (insert s))
13752 (goto-char (point-min))
13753 (message "Edit formulas and finish with `C-c C-c'.")))
13755 (defun org-show-variable ()
13756 "Show the location/value of the $ expression at point."
13757 (interactive)
13758 (let (var (pos org-pos) (win (selected-window)) e)
13759 (save-excursion
13760 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
13761 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
13762 (setq var (match-string 1))
13763 (error "No variable at point")))
13764 (cond
13765 ((setq e (assoc var org-table-named-field-locations))
13766 (switch-to-buffer-other-window (marker-buffer pos))
13767 (goto-line (nth 1 e))
13768 (org-table-goto-column (nth 2 e))
13769 (select-window win)
13770 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
13771 ((setq e (assoc var org-table-column-names))
13772 (switch-to-buffer-other-window (marker-buffer pos))
13773 (goto-char pos)
13774 (goto-char (org-table-begin))
13775 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
13776 (org-table-end) t)
13777 (progn
13778 (goto-char (match-beginning 1))
13779 (message "Named column (column %s)" (cdr e)))
13780 (error "Column name not found"))
13781 (select-window win))
13782 ((string-match "^[0-9]$" var)
13783 ;; column number
13784 (switch-to-buffer-other-window (marker-buffer pos))
13785 (goto-char pos)
13786 (goto-char (org-table-begin))
13787 (recenter 1)
13788 (if (re-search-forward org-table-dataline-regexp
13789 (org-table-end) t)
13790 (progn
13791 (goto-char (match-beginning 0))
13792 (org-table-goto-column (string-to-number var))
13793 (message "Column %s" var))
13794 (error "Column name not found"))
13795 (select-window win))
13796 ((setq e (assoc var org-table-local-parameters))
13797 (switch-to-buffer-other-window (marker-buffer pos))
13798 (goto-char pos)
13799 (goto-char (org-table-begin))
13800 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
13801 (progn
13802 (goto-char (match-beginning 1))
13803 (message "Local parameter."))
13804 (error "Parameter not found"))
13805 (select-window win))
13807 (cond
13808 ((setq e (assoc var org-table-formula-constants))
13809 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
13810 ((setq e (and (fboundp 'constants-get) (constants-get var)))
13811 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
13812 (t (error "Undefined name $%s" var)))))))
13814 (defun org-finish-edit-formulas (&optional arg)
13815 "Parse the buffer for formula definitions and install them.
13816 With prefix ARG, apply the new formulas to the table."
13817 (interactive "P")
13818 (let ((pos org-pos) eql)
13819 (goto-char (point-min))
13820 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
13821 (push (cons (match-string 1) (match-string 2)) eql))
13822 (set-window-configuration org-window-configuration)
13823 (select-window (get-buffer-window (marker-buffer pos)))
13824 (goto-char pos)
13825 (unless (org-at-table-p)
13826 (error "Lost table position - cannot install formulae"))
13827 (org-table-store-formulas eql)
13828 (move-marker pos nil)
13829 (kill-buffer "*Edit Formulas*")
13830 (if arg
13831 (org-table-recalculate 'all)
13832 (message "New formulas installed - press C-u C-c C-c to apply."))))
13834 (defun org-abort-edit-formulas ()
13835 "Abort editing formulas, without installing the changes."
13836 (interactive)
13837 (let ((pos org-pos))
13838 (set-window-configuration org-window-configuration)
13839 (select-window (get-buffer-window (marker-buffer pos)))
13840 (goto-char pos)
13841 (message "Formula editing aborted without installing changes")))
13843 ;;; The orgtbl minor mode
13845 ;; Define a minor mode which can be used in other modes in order to
13846 ;; integrate the org-mode table editor.
13848 ;; This is really a hack, because the org-mode table editor uses several
13849 ;; keys which normally belong to the major mode, for example the TAB and
13850 ;; RET keys. Here is how it works: The minor mode defines all the keys
13851 ;; necessary to operate the table editor, but wraps the commands into a
13852 ;; function which tests if the cursor is currently inside a table. If that
13853 ;; is the case, the table editor command is executed. However, when any of
13854 ;; those keys is used outside a table, the function uses `key-binding' to
13855 ;; look up if the key has an associated command in another currently active
13856 ;; keymap (minor modes, major mode, global), and executes that command.
13857 ;; There might be problems if any of the keys used by the table editor is
13858 ;; otherwise used as a prefix key.
13860 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
13861 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
13862 ;; addresses this by checking explicitly for both bindings.
13864 ;; The optimized version (see variable `orgtbl-optimized') takes over
13865 ;; all keys which are bound to `self-insert-command' in the *global map*.
13866 ;; Some modes bind other commands to simple characters, for example
13867 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
13868 ;; active, this binding is ignored inside tables and replaced with a
13869 ;; modified self-insert.
13871 (defvar orgtbl-mode nil
13872 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
13873 table editor in arbitrary modes.")
13874 (make-variable-buffer-local 'orgtbl-mode)
13876 (defvar orgtbl-mode-map (make-keymap)
13877 "Keymap for `orgtbl-mode'.")
13879 ;;;###autoload
13880 (defun turn-on-orgtbl ()
13881 "Unconditionally turn on `orgtbl-mode'."
13882 (orgtbl-mode 1))
13884 ;;;###autoload
13885 (defun orgtbl-mode (&optional arg)
13886 "The `org-mode' table editor as a minor mode for use in other modes."
13887 (interactive)
13888 (if (org-mode-p)
13889 ;; Exit without error, in case some hook functions calls this
13890 ;; by accident in org-mode.
13891 (message "Orgtbl-mode is not useful in org-mode, command ignored")
13892 (setq orgtbl-mode
13893 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
13894 (if orgtbl-mode
13895 (progn
13896 (and (orgtbl-setup) (defun orgtbl-setup () nil))
13897 ;; Make sure we are first in minor-mode-map-alist
13898 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
13899 (and c (setq minor-mode-map-alist
13900 (cons c (delq c minor-mode-map-alist)))))
13901 (org-set-local (quote org-table-may-need-update) t)
13902 (org-add-hook 'before-change-functions 'org-before-change-function
13903 nil 'local)
13904 (org-set-local 'org-old-auto-fill-inhibit-regexp
13905 auto-fill-inhibit-regexp)
13906 (org-set-local 'auto-fill-inhibit-regexp
13907 (if auto-fill-inhibit-regexp
13908 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
13909 "[ \t]*|"))
13910 (org-add-to-invisibility-spec '(org-cwidth))
13911 (easy-menu-add orgtbl-mode-menu)
13912 (run-hooks 'orgtbl-mode-hook))
13913 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
13914 (org-cleanup-narrow-column-properties)
13915 (org-remove-from-invisibility-spec '(org-cwidth))
13916 (remove-hook 'before-change-functions 'org-before-change-function t)
13917 (easy-menu-remove orgtbl-mode-menu)
13918 (force-mode-line-update 'all))))
13920 (defun org-cleanup-narrow-column-properties ()
13921 "Remove all properties related to narrow-column invisibility."
13922 (let ((s 1))
13923 (while (setq s (text-property-any s (point-max)
13924 'display org-narrow-column-arrow))
13925 (remove-text-properties s (1+ s) '(display t)))
13926 (setq s 1)
13927 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
13928 (remove-text-properties s (1+ s) '(org-cwidth t)))
13929 (setq s 1)
13930 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
13931 (remove-text-properties s (1+ s) '(invisible t)))))
13933 ;; Install it as a minor mode.
13934 (put 'orgtbl-mode :included t)
13935 (put 'orgtbl-mode :menu-tag "Org Table Mode")
13936 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
13938 (defun orgtbl-make-binding (fun n &rest keys)
13939 "Create a function for binding in the table minor mode.
13940 FUN is the command to call inside a table. N is used to create a unique
13941 command name. KEYS are keys that should be checked in for a command
13942 to execute outside of tables."
13943 (eval
13944 (list 'defun
13945 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
13946 '(arg)
13947 (concat "In tables, run `" (symbol-name fun) "'.\n"
13948 "Outside of tables, run the binding of `"
13949 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
13950 "'.")
13951 '(interactive "p")
13952 (list 'if
13953 '(org-at-table-p)
13954 (list 'call-interactively (list 'quote fun))
13955 (list 'let '(orgtbl-mode)
13956 (list 'call-interactively
13957 (append '(or)
13958 (mapcar (lambda (k)
13959 (list 'key-binding k))
13960 keys)
13961 '('orgtbl-error))))))))
13963 (defun orgtbl-error ()
13964 "Error when there is no default binding for a table key."
13965 (interactive)
13966 (error "This key is has no function outside tables"))
13968 (defun orgtbl-setup ()
13969 "Setup orgtbl keymaps."
13970 (let ((nfunc 0)
13971 (bindings
13972 (list
13973 '([(meta shift left)] org-table-delete-column)
13974 '([(meta left)] org-table-move-column-left)
13975 '([(meta right)] org-table-move-column-right)
13976 '([(meta shift right)] org-table-insert-column)
13977 '([(meta shift up)] org-table-kill-row)
13978 '([(meta shift down)] org-table-insert-row)
13979 '([(meta up)] org-table-move-row-up)
13980 '([(meta down)] org-table-move-row-down)
13981 '("\C-c\C-w" org-table-cut-region)
13982 '("\C-c\M-w" org-table-copy-region)
13983 '("\C-c\C-y" org-table-paste-rectangle)
13984 '("\C-c-" org-table-insert-hline)
13985 ; '([(shift tab)] org-table-previous-field)
13986 '("\C-m" org-table-next-row)
13987 (list (org-key 'S-return) 'org-table-copy-down)
13988 '([(meta return)] org-table-wrap-region)
13989 '("\C-c\C-q" org-table-wrap-region)
13990 '("\C-c?" org-table-current-column)
13991 '("\C-c " org-table-blank-field)
13992 '("\C-c+" org-table-sum)
13993 '("\C-c=" org-table-eval-formula)
13994 '("\C-c'" org-table-edit-formulas)
13995 '("\C-c`" org-table-edit-field)
13996 '("\C-c*" org-table-recalculate)
13997 '("\C-c|" org-table-create-or-convert-from-region)
13998 '("\C-c^" org-table-sort-lines)
13999 '([(control ?#)] org-table-rotate-recalc-marks)))
14000 elt key fun cmd)
14001 (while (setq elt (pop bindings))
14002 (setq nfunc (1+ nfunc))
14003 (setq key (car elt)
14004 fun (nth 1 elt)
14005 cmd (orgtbl-make-binding fun nfunc key))
14006 (define-key orgtbl-mode-map key cmd))
14007 ;; Special treatment needed for TAB and RET
14008 (define-key orgtbl-mode-map [(return)]
14009 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
14010 (define-key orgtbl-mode-map "\C-m"
14011 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
14012 (define-key orgtbl-mode-map [(tab)]
14013 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
14014 (define-key orgtbl-mode-map "\C-i"
14015 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
14016 (define-key orgtbl-mode-map "\C-i"
14017 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
14018 (define-key orgtbl-mode-map "\C-c\C-c"
14019 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
14020 (when orgtbl-optimized
14021 ;; If the user wants maximum table support, we need to hijack
14022 ;; some standard editing functions
14023 (org-remap orgtbl-mode-map
14024 'self-insert-command 'orgtbl-self-insert-command
14025 'delete-char 'org-delete-char
14026 'delete-backward-char 'org-delete-backward-char)
14027 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
14028 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
14029 '("OrgTbl"
14030 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
14031 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
14032 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
14033 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
14034 "--"
14035 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
14036 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
14037 ["Copy Field from Above"
14038 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
14039 "--"
14040 ("Column"
14041 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
14042 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
14043 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
14044 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
14045 "--"
14046 ["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])
14047 ("Row"
14048 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
14049 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
14050 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
14051 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
14052 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
14053 "--"
14054 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
14055 ("Rectangle"
14056 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
14057 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
14058 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
14059 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
14060 "--"
14061 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
14062 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14063 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
14064 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
14065 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
14066 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
14067 ["Sum Column/Rectangle" org-table-sum
14068 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
14069 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
14070 ["Debug Formulas"
14071 (setq org-table-formula-debug (not org-table-formula-debug))
14072 :style toggle :selected org-table-formula-debug]
14076 (defun orgtbl-tab (arg)
14077 "Justification and field motion for `orgtbl-mode'."
14078 (interactive "P")
14079 (if arg (org-table-edit-field t)
14080 (org-table-justify-field-maybe)
14081 (org-table-next-field)))
14083 (defun orgtbl-ret ()
14084 "Justification and field motion for `orgtbl-mode'."
14085 (interactive)
14086 (org-table-justify-field-maybe)
14087 (org-table-next-row))
14089 (defun orgtbl-self-insert-command (N)
14090 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14091 If the cursor is in a table looking at whitespace, the whitespace is
14092 overwritten, and the table is not marked as requiring realignment."
14093 (interactive "p")
14094 (if (and (org-at-table-p)
14096 (and org-table-auto-blank-field
14097 (member last-command
14098 '(orgtbl-hijacker-command-100
14099 orgtbl-hijacker-command-101
14100 orgtbl-hijacker-command-102
14101 orgtbl-hijacker-command-103
14102 orgtbl-hijacker-command-104
14103 orgtbl-hijacker-command-105))
14104 (org-table-blank-field))
14106 (eq N 1)
14107 (looking-at "[^|\n]* +|"))
14108 (let (org-table-may-need-update)
14109 (goto-char (1- (match-end 0)))
14110 (delete-backward-char 1)
14111 (goto-char (match-beginning 0))
14112 (self-insert-command N))
14113 (setq org-table-may-need-update t)
14114 (let (orgtbl-mode)
14115 (call-interactively (key-binding (vector last-input-event))))))
14117 (defun org-force-self-insert (N)
14118 "Needed to enforce self-insert under remapping."
14119 (interactive "p")
14120 (self-insert-command N))
14122 ;;; Exporting
14124 (defconst org-level-max 20)
14126 (defvar org-export-html-preamble nil
14127 "Preamble, to be inserted just after <body>. Set by publishing functions.")
14128 (defvar org-export-html-postamble nil
14129 "Preamble, to be inserted just before </body>. Set by publishing functions.")
14130 (defvar org-export-html-auto-preamble t
14131 "Should default preamble be inserted? Set by publishing functions.")
14132 (defvar org-export-html-auto-postamble t
14133 "Should default postamble be inserted? Set by publishing functions.")
14135 (defconst org-export-plist-vars
14136 '((:language . org-export-default-language)
14137 (:customtime . org-display-custom-times)
14138 (:headline-levels . org-export-headline-levels)
14139 (:section-numbers . org-export-with-section-numbers)
14140 (:table-of-contents . org-export-with-toc)
14141 (:archived-trees . org-export-with-archived-trees)
14142 (:emphasize . org-export-with-emphasize)
14143 (:sub-superscript . org-export-with-sub-superscripts)
14144 (:TeX-macros . org-export-with-TeX-macros)
14145 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
14146 (:fixed-width . org-export-with-fixed-width)
14147 (:timestamps . org-export-with-timestamps)
14148 (:tables . org-export-with-tables)
14149 (:table-auto-headline . org-export-highlight-first-table-line)
14150 (:style . org-export-html-style)
14151 (:convert-org-links . org-export-html-link-org-files-as-html)
14152 (:inline-images . org-export-html-inline-images)
14153 (:expand-quoted-html . org-export-html-expand)
14154 (:timestamp . org-export-html-with-timestamp)
14155 (:publishing-directory . org-export-publishing-directory)
14156 (:preamble . org-export-html-preamble)
14157 (:postamble . org-export-html-postamble)
14158 (:auto-preamble . org-export-html-auto-preamble)
14159 (:auto-postamble . org-export-html-auto-postamble)
14160 (:author . user-full-name)
14161 (:email . user-mail-address)))
14163 (defun org-default-export-plist ()
14164 "Return the property list with default settings for the export variables."
14165 (let ((l org-export-plist-vars) rtn e)
14166 (while (setq e (pop l))
14167 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
14168 rtn))
14170 (defun org-infile-export-plist ()
14171 "Return the property list with file-local settings for export."
14172 (save-excursion
14173 (goto-char 0)
14174 (let ((re (org-make-options-regexp
14175 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
14176 p key val text options)
14177 (while (re-search-forward re nil t)
14178 (setq key (org-match-string-no-properties 1)
14179 val (org-match-string-no-properties 2))
14180 (cond
14181 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
14182 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
14183 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
14184 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
14185 ((string-equal key "TEXT")
14186 (setq text (if text (concat text "\n" val) val)))
14187 ((string-equal key "OPTIONS") (setq options val))))
14188 (setq p (plist-put p :text text))
14189 (when options
14190 (let ((op '(("H" . :headline-levels)
14191 ("num" . :section-numbers)
14192 ("toc" . :table-of-contents)
14193 ("\\n" . :preserve-breaks)
14194 ("@" . :expand-quoted-html)
14195 (":" . :fixed-width)
14196 ("|" . :tables)
14197 ("^" . :sub-superscript)
14198 ("*" . :emphasize)
14199 ("TeX" . :TeX-macros)
14200 ("LaTeX" . :LaTeX-fragments)))
14202 (while (setq o (pop op))
14203 (if (string-match (concat (regexp-quote (car o))
14204 ":\\([^ \t\n\r;,.]*\\)")
14205 options)
14206 (setq p (plist-put p (cdr o)
14207 (car (read-from-string
14208 (match-string 1 options)))))))))
14209 p)))
14211 (defun org-combine-plists (&rest plists)
14212 "Create a single property list from all plists in PLISTS.
14213 The process starts by copying the last list, and then setting properties
14214 from the other lists. Settings in the first list are the most significant
14215 ones and overrule settings in the other lists."
14216 (let ((rtn (copy-sequence (pop plists)))
14217 p v ls)
14218 (while plists
14219 (setq ls (pop plists))
14220 (while ls
14221 (setq p (pop ls) v (pop ls))
14222 (setq rtn (plist-put rtn p v))))
14223 rtn))
14225 (defun org-export-directory (type plist)
14226 (let* ((val (plist-get plist :publishing-directory))
14227 (dir (if (listp val)
14228 (or (cdr (assoc type val)) ".")
14229 val)))
14230 dir))
14232 (defun org-export-find-first-heading-line (list)
14233 "Remove all lines from LIST which are before the first headline."
14234 (let ((orig-list list)
14235 (re (concat "^" outline-regexp)))
14236 (while (and list
14237 (not (string-match re (car list))))
14238 (pop list))
14239 (or list orig-list)))
14241 (defun org-skip-comments (lines)
14242 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
14243 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
14244 (re2 "^\\(\\*+\\)[ \t\n\r]")
14245 rtn line level)
14246 (while (setq line (pop lines))
14247 (cond
14248 ((and (string-match re1 line)
14249 (setq level (- (match-end 1) (match-beginning 1))))
14250 ;; Beginning of a COMMENT subtree. Skip it.
14251 (while (and (setq line (pop lines))
14252 (or (not (string-match re2 line))
14253 (> (- (match-end 1) (match-beginning 1)) level))))
14254 (setq lines (cons line lines)))
14255 ((string-match "^#" line)
14256 ;; an ordinary comment line
14258 ((and org-export-table-remove-special-lines
14259 (string-match "^[ \t]*|" line)
14260 (or (string-match "^[ \t]*| *[!_^] *|" line)
14261 (and (string-match "| *<[0-9]+> *|" line)
14262 (not (string-match "| *[^ <|]" line)))))
14263 ;; a special table line that should be removed
14265 (t (setq rtn (cons line rtn)))))
14266 (nreverse rtn)))
14268 (defun org-export (&optional arg)
14269 (interactive)
14270 (let ((help "[t] insert the export option template
14271 \[v] limit export to visible part of outline tree
14273 \[a] export as ASCII
14274 \[h] export as HTML
14275 \[b] export as HTML and browse immediately
14276 \[x] export as XOXO
14278 \[i] export current file as iCalendar file
14279 \[I] export all agenda files as iCalendar files
14280 \[c] export agenda files into combined iCalendar file
14282 \[F] publish current file
14283 \[P] publish current project
14284 \[X] publish... (project will be prompted for)
14285 \[A] publish all projects")
14286 (cmds
14287 '((?t . org-insert-export-options-template)
14288 (?v . org-export-visible)
14289 (?a . org-export-as-ascii)
14290 (?h . org-export-as-html)
14291 (?b . org-export-as-html-and-open)
14292 (?x . org-export-as-xoxo)
14293 (?i . org-export-icalendar-this-file)
14294 (?I . org-export-icalendar-all-agenda-files)
14295 (?c . org-export-icalendar-combine-agenda-files)
14296 (?F . org-publish-current-file)
14297 (?P . org-publish-current-project)
14298 (?X . org-publish)
14299 (?A . org-publish-all)))
14300 r1 r2 ass)
14301 (save-window-excursion
14302 (delete-other-windows)
14303 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
14304 (princ help))
14305 (message "Select command: ")
14306 (setq r1 (read-char-exclusive)))
14307 (setq r2 (if (< r1 27) (+ r1 96) r1))
14308 (if (setq ass (assq r2 cmds))
14309 (call-interactively (cdr ass))
14310 (error "No command associated with key %c" r1))))
14312 ;; ASCII
14314 (defconst org-html-entities
14315 '(("nbsp")
14316 ("iexcl")
14317 ("cent")
14318 ("pound")
14319 ("curren")
14320 ("yen")
14321 ("brvbar")
14322 ("sect")
14323 ("uml")
14324 ("copy")
14325 ("ordf")
14326 ("laquo")
14327 ("not")
14328 ("shy")
14329 ("reg")
14330 ("macr")
14331 ("deg")
14332 ("plusmn")
14333 ("sup2")
14334 ("sup3")
14335 ("acute")
14336 ("micro")
14337 ("para")
14338 ("middot")
14339 ("odot"."o")
14340 ("star"."*")
14341 ("cedil")
14342 ("sup1")
14343 ("ordm")
14344 ("raquo")
14345 ("frac14")
14346 ("frac12")
14347 ("frac34")
14348 ("iquest")
14349 ("Agrave")
14350 ("Aacute")
14351 ("Acirc")
14352 ("Atilde")
14353 ("Auml")
14354 ("Aring") ("AA"."&Aring;")
14355 ("AElig")
14356 ("Ccedil")
14357 ("Egrave")
14358 ("Eacute")
14359 ("Ecirc")
14360 ("Euml")
14361 ("Igrave")
14362 ("Iacute")
14363 ("Icirc")
14364 ("Iuml")
14365 ("ETH")
14366 ("Ntilde")
14367 ("Ograve")
14368 ("Oacute")
14369 ("Ocirc")
14370 ("Otilde")
14371 ("Ouml")
14372 ("times")
14373 ("Oslash")
14374 ("Ugrave")
14375 ("Uacute")
14376 ("Ucirc")
14377 ("Uuml")
14378 ("Yacute")
14379 ("THORN")
14380 ("szlig")
14381 ("agrave")
14382 ("aacute")
14383 ("acirc")
14384 ("atilde")
14385 ("auml")
14386 ("aring")
14387 ("aelig")
14388 ("ccedil")
14389 ("egrave")
14390 ("eacute")
14391 ("ecirc")
14392 ("euml")
14393 ("igrave")
14394 ("iacute")
14395 ("icirc")
14396 ("iuml")
14397 ("eth")
14398 ("ntilde")
14399 ("ograve")
14400 ("oacute")
14401 ("ocirc")
14402 ("otilde")
14403 ("ouml")
14404 ("divide")
14405 ("oslash")
14406 ("ugrave")
14407 ("uacute")
14408 ("ucirc")
14409 ("uuml")
14410 ("yacute")
14411 ("thorn")
14412 ("yuml")
14413 ("fnof")
14414 ("Alpha")
14415 ("Beta")
14416 ("Gamma")
14417 ("Delta")
14418 ("Epsilon")
14419 ("Zeta")
14420 ("Eta")
14421 ("Theta")
14422 ("Iota")
14423 ("Kappa")
14424 ("Lambda")
14425 ("Mu")
14426 ("Nu")
14427 ("Xi")
14428 ("Omicron")
14429 ("Pi")
14430 ("Rho")
14431 ("Sigma")
14432 ("Tau")
14433 ("Upsilon")
14434 ("Phi")
14435 ("Chi")
14436 ("Psi")
14437 ("Omega")
14438 ("alpha")
14439 ("beta")
14440 ("gamma")
14441 ("delta")
14442 ("epsilon")
14443 ("varepsilon"."&epsilon;")
14444 ("zeta")
14445 ("eta")
14446 ("theta")
14447 ("iota")
14448 ("kappa")
14449 ("lambda")
14450 ("mu")
14451 ("nu")
14452 ("xi")
14453 ("omicron")
14454 ("pi")
14455 ("rho")
14456 ("sigmaf") ("varsigma"."&sigmaf;")
14457 ("sigma")
14458 ("tau")
14459 ("upsilon")
14460 ("phi")
14461 ("chi")
14462 ("psi")
14463 ("omega")
14464 ("thetasym") ("vartheta"."&thetasym;")
14465 ("upsih")
14466 ("piv")
14467 ("bull") ("bullet"."&bull;")
14468 ("hellip") ("dots"."&hellip;")
14469 ("prime")
14470 ("Prime")
14471 ("oline")
14472 ("frasl")
14473 ("weierp")
14474 ("image")
14475 ("real")
14476 ("trade")
14477 ("alefsym")
14478 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
14479 ("uarr") ("uparrow"."&uarr;")
14480 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
14481 ("darr")("downarrow"."&darr;")
14482 ("harr") ("leftrightarrow"."&harr;")
14483 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
14484 ("lArr") ("Leftarrow"."&lArr;")
14485 ("uArr") ("Uparrow"."&uArr;")
14486 ("rArr") ("Rightarrow"."&rArr;")
14487 ("dArr") ("Downarrow"."&dArr;")
14488 ("hArr") ("Leftrightarrow"."&hArr;")
14489 ("forall")
14490 ("part") ("partial"."&part;")
14491 ("exist") ("exists"."&exist;")
14492 ("empty") ("emptyset"."&empty;")
14493 ("nabla")
14494 ("isin") ("in"."&isin;")
14495 ("notin")
14496 ("ni")
14497 ("prod")
14498 ("sum")
14499 ("minus")
14500 ("lowast") ("ast"."&lowast;")
14501 ("radic")
14502 ("prop") ("proptp"."&prop;")
14503 ("infin") ("infty"."&infin;")
14504 ("ang") ("angle"."&ang;")
14505 ("and") ("vee"."&and;")
14506 ("or") ("wedge"."&or;")
14507 ("cap")
14508 ("cup")
14509 ("int")
14510 ("there4")
14511 ("sim")
14512 ("cong") ("simeq"."&cong;")
14513 ("asymp")("approx"."&asymp;")
14514 ("ne") ("neq"."&ne;")
14515 ("equiv")
14516 ("le")
14517 ("ge")
14518 ("sub") ("subset"."&sub;")
14519 ("sup") ("supset"."&sup;")
14520 ("nsub")
14521 ("sube")
14522 ("supe")
14523 ("oplus")
14524 ("otimes")
14525 ("perp")
14526 ("sdot") ("cdot"."&sdot;")
14527 ("lceil")
14528 ("rceil")
14529 ("lfloor")
14530 ("rfloor")
14531 ("lang")
14532 ("rang")
14533 ("loz") ("Diamond"."&loz;")
14534 ("spades") ("spadesuit"."&spades;")
14535 ("clubs") ("clubsuit"."&clubs;")
14536 ("hearts") ("diamondsuit"."&hearts;")
14537 ("diams") ("diamondsuit"."&diams;")
14538 ("quot")
14539 ("amp")
14540 ("lt")
14541 ("gt")
14542 ("OElig")
14543 ("oelig")
14544 ("Scaron")
14545 ("scaron")
14546 ("Yuml")
14547 ("circ")
14548 ("tilde")
14549 ("ensp")
14550 ("emsp")
14551 ("thinsp")
14552 ("zwnj")
14553 ("zwj")
14554 ("lrm")
14555 ("rlm")
14556 ("ndash")
14557 ("mdash")
14558 ("lsquo")
14559 ("rsquo")
14560 ("sbquo")
14561 ("ldquo")
14562 ("rdquo")
14563 ("bdquo")
14564 ("dagger")
14565 ("Dagger")
14566 ("permil")
14567 ("lsaquo")
14568 ("rsaquo")
14569 ("euro")
14571 ("arccos"."arccos")
14572 ("arcsin"."arcsin")
14573 ("arctan"."arctan")
14574 ("arg"."arg")
14575 ("cos"."cos")
14576 ("cosh"."cosh")
14577 ("cot"."cot")
14578 ("coth"."coth")
14579 ("csc"."csc")
14580 ("deg"."deg")
14581 ("det"."det")
14582 ("dim"."dim")
14583 ("exp"."exp")
14584 ("gcd"."gcd")
14585 ("hom"."hom")
14586 ("inf"."inf")
14587 ("ker"."ker")
14588 ("lg"."lg")
14589 ("lim"."lim")
14590 ("liminf"."liminf")
14591 ("limsup"."limsup")
14592 ("ln"."ln")
14593 ("log"."log")
14594 ("max"."max")
14595 ("min"."min")
14596 ("Pr"."Pr")
14597 ("sec"."sec")
14598 ("sin"."sin")
14599 ("sinh"."sinh")
14600 ("sup"."sup")
14601 ("tan"."tan")
14602 ("tanh"."tanh")
14604 "Entities for TeX->HTML translation.
14605 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
14606 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
14607 In that case, \"\\ent\" will be translated to \"&other;\".
14608 The list contains HTML entities for Latin-1, Greek and other symbols.
14609 It is supplemented by a number of commonly used TeX macros with appropriate
14610 translations. There is currently no way for users to extend this.")
14612 (defun org-cleaned-string-for-export (string &rest parameters)
14613 "Cleanup a buffer substring so that links can be created safely."
14614 (interactive)
14615 (let* ((re-radio (and org-target-link-regexp
14616 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
14617 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
14618 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
14619 (re-archive (concat ":" org-archive-tag ":"))
14620 rtn)
14621 (save-excursion
14622 (set-buffer (get-buffer-create " org-mode-tmp"))
14623 (erase-buffer)
14624 (insert string)
14625 (let ((org-inhibit-startup t)) (org-mode))
14626 (untabify (point-min) (point-max))
14628 ;; Get rid of archived trees
14629 (when (not (eq org-export-with-archived-trees t))
14630 (goto-char (point-min))
14631 (while (re-search-forward re-archive nil t)
14632 (if (not (org-on-heading-p))
14633 (org-end-of-subtree t)
14634 (beginning-of-line 1)
14635 (delete-region
14636 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
14637 (org-end-of-subtree t)))))
14639 ;; Find targets in comments and move them out of comments,
14640 ;; but mark them as targets that should be invisible
14641 (goto-char (point-min))
14642 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
14643 (replace-match "\\1(INVISIBLE)"))
14645 ;; Remove comments
14646 (goto-char (point-min))
14647 (while (re-search-forward "^#.*\n?" nil t)
14648 (replace-match ""))
14650 ;; Find matches for radio targets and turn them into internal links
14651 (goto-char (point-min))
14652 (when re-radio
14653 (while (re-search-forward re-radio nil t)
14654 (replace-match "\\1[[\\2]]")))
14656 ;; Find all links that contain a newline and put them into a single line
14657 (goto-char (point-min))
14658 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
14659 (replace-match "\\1 \\3")
14660 (goto-char (match-beginning 0)))
14662 ;; Convert LaTeX fragments to images
14663 (when (memq :LaTeX-fragments parameters)
14664 (org-format-latex
14665 (concat "ltxpng/" (file-name-sans-extension
14666 (file-name-nondirectory
14667 org-current-export-file)))
14668 org-current-export-dir nil "Creating LaTeX image %s"))
14669 (message "Exporting...")
14671 ;; Normalize links: Convert angle and plain links into bracket links
14672 ;; Expand link abbreviations
14673 (goto-char (point-min))
14674 (while (re-search-forward re-plain-link nil t)
14675 (replace-match
14676 (concat
14677 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
14678 t t))
14679 (goto-char (point-min))
14680 (while (re-search-forward re-angle-link nil t)
14681 (replace-match
14682 (concat
14683 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
14684 t t))
14685 (goto-char (point-min))
14686 (while (re-search-forward org-bracket-link-regexp nil t)
14687 (replace-match
14688 (concat "[[" (save-match-data
14689 (org-link-expand-abbrev (match-string 1)))
14691 (if (match-end 3)
14692 (match-string 2)
14693 (concat "[" (match-string 1) "]"))
14694 "]")
14695 t t))
14697 ;; Find multiline emphasis and put them into single line
14698 (when (memq :emph-multiline parameters)
14699 (goto-char (point-min))
14700 (while (re-search-forward org-emph-re nil t)
14701 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
14702 (goto-char (1- (match-end 0)))))
14704 (setq rtn (buffer-string)))
14705 (kill-buffer " org-mode-tmp")
14706 rtn))
14708 (defun org-solidify-link-text (s &optional alist)
14709 "Take link text and make a safe target out of it."
14710 (save-match-data
14711 (let* ((rtn
14712 (mapconcat
14713 'identity
14714 (org-split-string s "[ \t\r\n]+") "--"))
14715 (a (assoc rtn alist)))
14716 (or (cdr a) rtn))))
14718 (defun org-convert-to-odd-levels ()
14719 "Convert an org-mode file with all levels allowed to one with odd levels.
14720 This will leave level 1 alone, convert level 2 to level 3, level 3 to
14721 level 5 etc."
14722 (interactive)
14723 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
14724 (let ((org-odd-levels-only nil) n)
14725 (save-excursion
14726 (goto-char (point-min))
14727 (while (re-search-forward "^\\*\\*+" nil t)
14728 (setq n (1- (length (match-string 0))))
14729 (while (>= (setq n (1- n)) 0)
14730 (org-demote))
14731 (end-of-line 1))))))
14734 (defun org-convert-to-oddeven-levels ()
14735 "Convert an org-mode file with only odd levels to one with odd and even levels.
14736 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
14737 section with an even level, conversion would destroy the structure of the file. An error
14738 is signaled in this case."
14739 (interactive)
14740 (goto-char (point-min))
14741 ;; First check if there are no even levels
14742 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
14743 (org-show-context t)
14744 (error "Not all levels are odd in this file. Conversion not possible."))
14745 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
14746 (let ((org-odd-levels-only nil) n)
14747 (save-excursion
14748 (goto-char (point-min))
14749 (while (re-search-forward "^\\*\\*+" nil t)
14750 (setq n (/ (length (match-string 0)) 2))
14751 (while (>= (setq n (1- n)) 0)
14752 (org-promote))
14753 (end-of-line 1))))))
14755 (defun org-tr-level (n)
14756 "Make N odd if required."
14757 (if org-odd-levels-only (1+ (/ n 2)) n))
14759 (defvar org-last-level nil) ; dynamically scoped variable
14760 (defvar org-ascii-current-indentation nil) ; For communication
14762 (defun org-export-as-ascii (arg)
14763 "Export the outline as a pretty ASCII file.
14764 If there is an active region, export only the region.
14765 The prefix ARG specifies how many levels of the outline should become
14766 underlined headlines. The default is 3."
14767 (interactive "P")
14768 (setq-default org-todo-line-regexp org-todo-line-regexp)
14769 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14770 (org-infile-export-plist)))
14771 (region
14772 (buffer-substring
14773 (if (org-region-active-p) (region-beginning) (point-min))
14774 (if (org-region-active-p) (region-end) (point-max))))
14775 (custom-times org-display-custom-times)
14776 (lines (org-export-find-first-heading-line
14777 (org-skip-comments
14778 (org-split-string
14779 (org-cleaned-string-for-export region)
14780 "[\r\n]"))))
14781 (org-ascii-current-indentation '(0 . 0))
14782 (org-startup-with-deadline-check nil)
14783 (level 0) line txt
14784 (umax nil)
14785 (case-fold-search nil)
14786 (filename (concat (file-name-as-directory
14787 (org-export-directory :ascii opt-plist))
14788 (file-name-sans-extension
14789 (file-name-nondirectory buffer-file-name))
14790 ".txt"))
14791 (buffer (find-file-noselect filename))
14792 (levels-open (make-vector org-level-max nil))
14793 (odd org-odd-levels-only)
14794 (date (format-time-string "%Y/%m/%d" (current-time)))
14795 (time (format-time-string "%X" (org-current-time)))
14796 (author (plist-get opt-plist :author))
14797 (title (or (plist-get opt-plist :title)
14798 (file-name-sans-extension
14799 (file-name-nondirectory buffer-file-name))))
14800 (email (plist-get opt-plist :email))
14801 (language (plist-get opt-plist :language))
14802 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14803 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14804 (text nil)
14805 (todo nil)
14806 (lang-words nil))
14808 (setq org-last-level 1)
14809 (org-init-section-numbers)
14811 (find-file-noselect filename)
14813 (setq lang-words (or (assoc language org-export-language-setup)
14814 (assoc "en" org-export-language-setup)))
14815 (if org-export-ascii-show-new-buffer
14816 (switch-to-buffer-other-window buffer)
14817 (set-buffer buffer))
14818 (erase-buffer)
14819 (fundamental-mode)
14820 ;; create local variables for all options, to make sure all called
14821 ;; functions get the correct information
14822 (mapcar (lambda (x)
14823 (set (make-local-variable (cdr x))
14824 (plist-get opt-plist (car x))))
14825 org-export-plist-vars)
14826 (org-set-local 'org-odd-levels-only odd)
14827 (setq umax (if arg (prefix-numeric-value arg)
14828 org-export-headline-levels))
14830 ;; File header
14831 (if title (org-insert-centered title ?=))
14832 (insert "\n")
14833 (if (or author email)
14834 (insert (concat (nth 1 lang-words) ": " (or author "")
14835 (if email (concat " <" email ">") "")
14836 "\n")))
14837 (if (and date time)
14838 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
14839 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
14841 (insert "\n\n")
14843 (if org-export-with-toc
14844 (progn
14845 (insert (nth 3 lang-words) "\n"
14846 (make-string (length (nth 3 lang-words)) ?=) "\n")
14847 (mapcar '(lambda (line)
14848 (if (string-match org-todo-line-regexp
14849 line)
14850 ;; This is a headline
14851 (progn
14852 (setq level (- (match-end 1) (match-beginning 1))
14853 level (org-tr-level level)
14854 txt (match-string 3 line)
14855 todo
14856 (or (and org-export-mark-todo-in-toc
14857 (match-beginning 2)
14858 (not (equal (match-string 2 line)
14859 org-done-string)))
14860 ; TODO, not DONE
14861 (and org-export-mark-todo-in-toc
14862 (= level umax)
14863 (org-search-todo-below
14864 line lines level))))
14865 (setq txt (org-html-expand-for-ascii txt))
14867 (if (and (memq org-export-with-tags '(not-in-toc nil))
14868 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
14869 (setq txt (replace-match "" t t txt)))
14870 (if (string-match quote-re0 txt)
14871 (setq txt (replace-match "" t t txt)))
14873 (if org-export-with-section-numbers
14874 (setq txt (concat (org-section-number level)
14875 " " txt)))
14876 (if (<= level umax)
14877 (progn
14878 (insert
14879 (make-string (* (1- level) 4) ?\ )
14880 (format (if todo "%s (*)\n" "%s\n") txt))
14881 (setq org-last-level level))
14882 ))))
14883 lines)))
14885 (org-init-section-numbers)
14886 (while (setq line (pop lines))
14887 ;; Remove the quoted HTML tags.
14888 (setq line (org-html-expand-for-ascii line))
14889 ;; Remove targets
14890 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
14891 (setq line (replace-match "" t t line)))
14892 ;; Replace internal links
14893 (while (string-match org-bracket-link-regexp line)
14894 (setq line (replace-match
14895 (if (match-end 3) "[\\3]" "[\\1]")
14896 t nil line)))
14897 (when custom-times
14898 (setq line (org-translate-time line)))
14899 (cond
14900 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14901 ;; a Headline
14902 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14903 txt (match-string 2 line))
14904 (org-ascii-level-start level txt umax lines))
14906 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
14907 (normal-mode)
14908 (save-buffer)
14909 ;; remove display and invisible chars
14910 (let (beg end)
14911 (goto-char (point-min))
14912 (while (setq beg (next-single-property-change (point) 'display))
14913 (setq end (next-single-property-change beg 'display))
14914 (delete-region beg end)
14915 (goto-char beg)
14916 (insert "=>"))
14917 (goto-char (point-min))
14918 (while (setq beg (next-single-property-change (point) 'org-cwidth))
14919 (setq end (next-single-property-change beg 'org-cwidth))
14920 (delete-region beg end)
14921 (goto-char beg)))
14922 (goto-char (point-min))))
14924 (defun org-search-todo-below (line lines level)
14925 "Search the subtree below LINE for any TODO entries."
14926 (let ((rest (cdr (memq line lines)))
14927 (re org-todo-line-regexp)
14928 line lv todo)
14929 (catch 'exit
14930 (while (setq line (pop rest))
14931 (if (string-match re line)
14932 (progn
14933 (setq lv (- (match-end 1) (match-beginning 1))
14934 todo (and (match-beginning 2)
14935 (not (equal (match-string 2 line)
14936 org-done-string))))
14937 ; TODO, not DONE
14938 (if (<= lv level) (throw 'exit nil))
14939 (if todo (throw 'exit t))))))))
14941 (defun org-html-expand-for-ascii (line)
14942 "Handle quoted HTML for ASCII export."
14943 (if org-export-html-expand
14944 (while (string-match "@<[^<>\n]*>" line)
14945 ;; We just remove the tags for now.
14946 (setq line (replace-match "" nil nil line))))
14947 line)
14949 (defun org-insert-centered (s &optional underline)
14950 "Insert the string S centered and underline it with character UNDERLINE."
14951 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
14952 (insert (make-string ind ?\ ) s "\n")
14953 (if underline
14954 (insert (make-string ind ?\ )
14955 (make-string (string-width s) underline)
14956 "\n"))))
14958 (defun org-ascii-level-start (level title umax &optional lines)
14959 "Insert a new level in ASCII export."
14960 (let (char (n (- level umax 1)) (ind 0))
14961 (if (> level umax)
14962 (progn
14963 (insert (make-string (* 2 n) ?\ )
14964 (char-to-string (nth (% n (length org-export-ascii-bullets))
14965 org-export-ascii-bullets))
14966 " " title "\n")
14967 ;; find the indentation of the next non-empty line
14968 (catch 'stop
14969 (while lines
14970 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
14971 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
14972 (throw 'stop (setq ind (org-get-indentation (car lines)))))
14973 (pop lines)))
14974 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
14975 (if (or (not (equal (char-before) ?\n))
14976 (not (equal (char-before (1- (point))) ?\n)))
14977 (insert "\n"))
14978 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
14979 (unless org-export-with-tags
14980 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14981 (setq title (replace-match "" t t title))))
14982 (if org-export-with-section-numbers
14983 (setq title (concat (org-section-number level) " " title)))
14984 (insert title "\n" (make-string (string-width title) char) "\n")
14985 (setq org-ascii-current-indentation '(0 . 0)))))
14987 (defun org-export-visible (type arg)
14988 "Create a copy of the visible part of the current buffer, and export it.
14989 The copy is created in a temporary buffer and removed after use.
14990 TYPE is the final key (as a string) that also select the export command in
14991 the `C-c C-e' export dispatcher.
14992 As a special case, if the you type SPC at the prompt, the temporary
14993 org-mode file will not be removed but presented to you so that you can
14994 continue to use it. The prefix arg ARG is passed through to the exporting
14995 command."
14996 (interactive
14997 (list (progn
14998 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
14999 (read-char-exclusive))
15000 current-prefix-arg))
15001 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
15002 (error "Invalid export key"))
15003 (let* ((binding (cdr (assoc type
15004 '((?a . org-export-as-ascii)
15005 (?\C-a . org-export-as-ascii)
15006 (?b . org-export-as-html-and-open)
15007 (?\C-b . org-export-as-html-and-open)
15008 (?h . org-export-as-html)
15009 (?x . org-export-as-xoxo)))))
15010 (keepp (equal type ?\ ))
15011 (file buffer-file-name)
15012 (buffer (get-buffer-create "*Org Export Visible*"))
15013 s e)
15014 (with-current-buffer buffer (erase-buffer))
15015 (save-excursion
15016 (setq s (goto-char (point-min)))
15017 (while (not (= (point) (point-max)))
15018 (goto-char (org-find-invisible))
15019 (append-to-buffer buffer s (point))
15020 (setq s (goto-char (org-find-visible))))
15021 (goto-char (point-min))
15022 (unless keepp
15023 ;; Copy all comment lines to the end, to make sure #+ settings are
15024 ;; still available for the second export step. Kind of a hack, but
15025 ;; does do the trick.
15026 (if (looking-at "#[^\r\n]*")
15027 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
15028 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
15029 (append-to-buffer buffer (1+ (match-beginning 0))
15030 (min (point-max) (1+ (match-end 0))))))
15031 (set-buffer buffer)
15032 (let ((buffer-file-name file)
15033 (org-inhibit-startup t))
15034 (org-mode)
15035 (show-all)
15036 (unless keepp (funcall binding arg))))
15037 (if (not keepp)
15038 (kill-buffer buffer)
15039 (switch-to-buffer-other-window buffer)
15040 (goto-char (point-min)))))
15042 (defun org-find-visible ()
15043 (let ((s (point)))
15044 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
15045 (get-char-property s 'invisible)))
15047 (defun org-find-invisible ()
15048 (let ((s (point)))
15049 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
15050 (not (get-char-property s 'invisible))))
15053 ;; HTML
15055 (defun org-get-current-options ()
15056 "Return a string with current options as keyword options.
15057 Does include HTML export options as well as TODO and CATEGORY stuff."
15058 (format
15059 "#+TITLE: %s
15060 #+AUTHOR: %s
15061 #+EMAIL: %s
15062 #+LANGUAGE: %s
15063 #+TEXT: Some descriptive text to be emitted. Several lines OK.
15064 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
15065 #+CATEGORY: %s
15066 #+SEQ_TODO: %s
15067 #+TYP_TODO: %s
15068 #+STARTUP: %s %s %s %s %s %s
15069 #+TAGS: %s
15070 #+ARCHIVE: %s
15071 #+LINK: %s
15073 (buffer-name) (user-full-name) user-mail-address org-export-default-language
15074 org-export-headline-levels
15075 org-export-with-section-numbers
15076 org-export-with-toc
15077 org-export-preserve-breaks
15078 org-export-html-expand
15079 org-export-with-fixed-width
15080 org-export-with-tables
15081 org-export-with-sub-superscripts
15082 org-export-with-emphasize
15083 org-export-with-TeX-macros
15084 org-export-with-LaTeX-fragments
15085 (file-name-nondirectory buffer-file-name)
15086 (if (equal org-todo-interpretation 'sequence)
15087 (mapconcat 'identity org-todo-keywords " ")
15088 "TODO FEEDBACK VERIFY DONE")
15089 (if (equal org-todo-interpretation 'type)
15090 (mapconcat 'identity org-todo-keywords " ")
15091 "Me Jason Marie DONE")
15092 (cdr (assoc org-startup-folded
15093 '((nil . "showall") (t . "overview") (content . "content"))))
15094 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
15095 (if org-odd-levels-only "odd" "oddeven")
15096 (if org-hide-leading-stars "hidestars" "showstars")
15097 (if org-startup-align-all-tables "align" "noalign")
15098 (if org-log-done "logging" "nologging")
15099 (or (mapconcat (lambda (x)
15100 (cond
15101 ((equal '(:startgroup) x) "{")
15102 ((equal '(:endgroup) x) "}")
15103 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
15104 (t (car x))))
15105 (or org-tag-alist (org-get-buffer-tags)) " ") "")
15106 org-archive-location
15107 "org file:~/org/%s.org"
15110 (defun org-insert-export-options-template ()
15111 "Insert into the buffer a template with information for exporting."
15112 (interactive)
15113 (if (not (bolp)) (newline))
15114 (let ((s (org-get-current-options)))
15115 (and (string-match "#\\+CATEGORY" s)
15116 (setq s (substring s 0 (match-beginning 0))))
15117 (insert s)))
15119 (defun org-toggle-fixed-width-section (arg)
15120 "Toggle the fixed-width export.
15121 If there is no active region, the QUOTE keyword at the current headline is
15122 inserted or removed. When present, it causes the text between this headline
15123 and the next to be exported as fixed-width text, and unmodified.
15124 If there is an active region, this command adds or removes a colon as the
15125 first character of this line. If the first character of a line is a colon,
15126 this line is also exported in fixed-width font."
15127 (interactive "P")
15128 (let* ((cc 0)
15129 (regionp (org-region-active-p))
15130 (beg (if regionp (region-beginning) (point)))
15131 (end (if regionp (region-end)))
15132 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15133 (re "[ \t]*\\(:\\)")
15134 off)
15135 (if regionp
15136 (save-excursion
15137 (goto-char beg)
15138 (setq cc (current-column))
15139 (beginning-of-line 1)
15140 (setq off (looking-at re))
15141 (while (> nlines 0)
15142 (setq nlines (1- nlines))
15143 (beginning-of-line 1)
15144 (cond
15145 (arg
15146 (move-to-column cc t)
15147 (insert ":\n")
15148 (forward-line -1))
15149 ((and off (looking-at re))
15150 (replace-match "" t t nil 1))
15151 ((not off) (move-to-column cc t) (insert ":")))
15152 (forward-line 1)))
15153 (save-excursion
15154 (org-back-to-heading)
15155 (if (looking-at (concat outline-regexp
15156 "\\( +\\<" org-quote-string "\\>\\)"))
15157 (replace-match "" t t nil 1)
15158 (if (looking-at outline-regexp)
15159 (progn
15160 (goto-char (match-end 0))
15161 (insert " " org-quote-string))))))))
15163 (defun org-export-as-html-and-open (arg)
15164 "Export the outline as HTML and immediately open it with a browser.
15165 If there is an active region, export only the region.
15166 The prefix ARG specifies how many levels of the outline should become
15167 headlines. The default is 3. Lower levels will become bulleted lists."
15168 (interactive "P")
15169 (org-export-as-html arg 'hidden)
15170 (org-open-file buffer-file-name))
15172 (defun org-export-as-html-batch ()
15173 "Call `org-export-as-html', may be used in batch processing as
15174 emacs --batch
15175 --load=$HOME/lib/emacs/org.el
15176 --eval \"(setq org-export-headline-levels 2)\"
15177 --visit=MyFile --funcall org-export-as-html-batch"
15178 (org-export-as-html org-export-headline-levels 'hidden))
15180 (defun org-export-as-html (arg &optional hidden ext-plist)
15181 "Export the outline as a pretty HTML file.
15182 If there is an active region, export only the region.
15183 The prefix ARG specifies how many levels of the outline should become
15184 headlines. The default is 3. Lower levels will become bulleted lists.
15185 When HIDDEN is non-nil, don't display the HTML buffer.
15186 EXT-PLIST is a property list with external parameters overriding
15187 org-mode's default settings, but still inferior to file-local settings."
15188 (interactive "P")
15189 (message "Exporting...")
15190 (setq-default org-todo-line-regexp org-todo-line-regexp)
15191 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
15192 (setq-default org-done-string org-done-string)
15193 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15194 ext-plist
15195 (org-infile-export-plist)))
15197 (style (plist-get opt-plist :style))
15198 (link-validate (plist-get opt-plist :link-validation-function))
15199 valid
15200 (odd org-odd-levels-only)
15201 (region-p (org-region-active-p))
15202 (region
15203 (buffer-substring
15204 (if region-p (region-beginning) (point-min))
15205 (if region-p (region-end) (point-max))))
15206 ;; The following two are dynamically scoped into other
15207 ;; routines below.
15208 (org-current-export-dir (org-export-directory :html opt-plist))
15209 (org-current-export-file buffer-file-name)
15210 (all_lines
15211 (org-skip-comments (org-split-string
15212 (org-cleaned-string-for-export
15213 region :emph-multiline
15214 (if (plist-get opt-plist :LaTeX-fragments)
15215 :LaTeX-fragments))
15216 "[\r\n]")))
15217 (lines (org-export-find-first-heading-line all_lines))
15218 (level 0) (line "") (origline "") txt todo
15219 (umax nil)
15220 (filename (concat (file-name-as-directory
15221 (org-export-directory :html opt-plist))
15222 (file-name-sans-extension
15223 (file-name-nondirectory buffer-file-name))
15224 ".html"))
15225 (current-dir (file-name-directory buffer-file-name))
15226 (buffer (find-file-noselect filename))
15227 (levels-open (make-vector org-level-max nil))
15228 (date (format-time-string "%Y/%m/%d" (current-time)))
15229 (time (format-time-string "%X" (org-current-time)))
15230 (author (plist-get opt-plist :author))
15231 (title (or (plist-get opt-plist :title)
15232 (file-name-sans-extension
15233 (file-name-nondirectory buffer-file-name))))
15234 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
15235 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
15236 (inquote nil)
15237 (infixed nil)
15238 (in-local-list nil)
15239 (local-list-num nil)
15240 (local-list-indent nil)
15241 (llt org-plain-list-ordered-item-terminator)
15242 (email (plist-get opt-plist :email))
15243 (language (plist-get opt-plist :language))
15244 (text (plist-get opt-plist :text))
15245 (lang-words nil)
15246 (target-alist nil) tg
15247 (head-count 0) cnt
15248 (start 0)
15249 (coding-system (and (boundp 'buffer-file-coding-system)
15250 buffer-file-coding-system))
15251 (coding-system-for-write coding-system)
15252 (save-buffer-coding-system coding-system)
15253 (charset (and coding-system
15254 (fboundp 'coding-system-get)
15255 (coding-system-get coding-system 'mime-charset)))
15256 table-open type
15257 table-buffer table-orig-buffer
15258 ind start-is-num starter
15259 rpl path desc descp desc1 desc2 link
15261 (message "Exporting...")
15263 (setq org-last-level 1)
15264 (org-init-section-numbers)
15266 ;; Get the language-dependent settings
15267 (setq lang-words (or (assoc language org-export-language-setup)
15268 (assoc "en" org-export-language-setup)))
15270 ;; Switch to the output buffer
15271 (if (or hidden (not org-export-html-show-new-buffer))
15272 (set-buffer buffer)
15273 (switch-to-buffer-other-window buffer))
15274 (erase-buffer)
15275 (fundamental-mode)
15276 (let ((case-fold-search nil)
15277 (org-odd-levels-only odd))
15278 ;; create local variables for all options, to make sure all called
15279 ;; functions get the correct information
15280 (mapcar (lambda (x)
15281 (set (make-local-variable (cdr x))
15282 (plist-get opt-plist (car x))))
15283 org-export-plist-vars)
15284 (setq umax (if arg (prefix-numeric-value arg)
15285 org-export-headline-levels))
15287 ;; File header
15288 (insert (format
15289 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
15290 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
15291 <html xmlns=\"http://www.w3.org/1999/xhtml\"
15292 lang=\"%s\" xml:lang=\"%s\">
15293 <head>
15294 <title>%s</title>
15295 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
15296 <meta name=\"generator\" content=\"Org-mode\"/>
15297 <meta name=\"generated\" content=\"%s %s\"/>
15298 <meta name=\"author\" content=\"%s\"/>
15300 </head><body>
15302 language language (org-html-expand title) (or charset "iso-8859-1")
15303 date time author style))
15306 (insert (or (plist-get opt-plist :preamble) ""))
15308 (when (plist-get opt-plist :auto-preamble)
15309 (if title (insert (format org-export-html-title-format
15310 (org-html-expand title))))
15311 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
15313 (if org-export-with-toc
15314 (progn
15315 (insert (format "<h%d>%s</h%d>\n"
15316 org-export-html-toplevel-hlevel
15317 (nth 3 lang-words)
15318 org-export-html-toplevel-hlevel))
15319 (insert "<ul>\n<li>")
15320 (setq lines
15321 (mapcar '(lambda (line)
15322 (if (string-match org-todo-line-regexp line)
15323 ;; This is a headline
15324 (progn
15325 (setq level (- (match-end 1) (match-beginning 1))
15326 level (org-tr-level level)
15327 txt (save-match-data
15328 (org-html-expand
15329 (org-export-cleanup-toc-line
15330 (match-string 3 line))))
15331 todo
15332 (or (and org-export-mark-todo-in-toc
15333 (match-beginning 2)
15334 (not (equal (match-string 2 line)
15335 org-done-string)))
15336 ; TODO, not DONE
15337 (and org-export-mark-todo-in-toc
15338 (= level umax)
15339 (org-search-todo-below
15340 line lines level))))
15341 (if (and (memq org-export-with-tags '(not-in-toc nil))
15342 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
15343 (setq txt (replace-match "" t t txt)))
15344 (if (string-match quote-re0 txt)
15345 (setq txt (replace-match "" t t txt)))
15346 (if org-export-with-section-numbers
15347 (setq txt (concat (org-section-number level)
15348 " " txt)))
15349 (if (<= level umax)
15350 (progn
15351 (setq head-count (+ head-count 1))
15352 (if (> level org-last-level)
15353 (progn
15354 (setq cnt (- level org-last-level))
15355 (while (>= (setq cnt (1- cnt)) 0)
15356 (insert "\n<ul>\n<li>"))
15357 (insert "\n")))
15358 (if (< level org-last-level)
15359 (progn
15360 (setq cnt (- org-last-level level))
15361 (while (>= (setq cnt (1- cnt)) 0)
15362 (insert "</li>\n</ul>"))
15363 (insert "\n")))
15364 ;; Check for targets
15365 (while (string-match org-target-regexp line)
15366 (setq tg (match-string 1 line)
15367 line (replace-match
15368 (concat "@<span class=\"target\">" tg "@</span> ")
15369 t t line))
15370 (push (cons (org-solidify-link-text tg)
15371 (format "sec-%d" head-count))
15372 target-alist))
15373 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
15374 (setq txt (replace-match "" t t txt)))
15375 (insert
15376 (format
15377 (if todo
15378 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
15379 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
15380 head-count txt))
15382 (setq org-last-level level))
15384 line)
15385 lines))
15386 (while (> org-last-level 0)
15387 (setq org-last-level (1- org-last-level))
15388 (insert "</li>\n</ul>\n"))
15390 (setq head-count 0)
15391 (org-init-section-numbers)
15393 (while (setq line (pop lines) origline line)
15394 (catch 'nextline
15396 ;; end of quote section?
15397 (when (and inquote (string-match "^\\*+" line))
15398 (insert "</pre>\n")
15399 (setq inquote nil))
15400 ;; inside a quote section?
15401 (when inquote
15402 (insert (org-html-protect line) "\n")
15403 (throw 'nextline nil))
15405 ;; verbatim lines
15406 (when (and org-export-with-fixed-width
15407 (string-match "^[ \t]*:\\(.*\\)" line))
15408 (when (not infixed)
15409 (setq infixed t)
15410 (insert "<pre>\n"))
15411 (insert (org-html-protect (match-string 1 line)) "\n")
15412 (when (and lines
15413 (not (string-match "^[ \t]*\\(:.*\\)"
15414 (car lines))))
15415 (setq infixed nil)
15416 (insert "</pre>\n"))
15417 (throw 'nextline nil))
15420 ;; make targets to anchors
15421 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
15422 (cond
15423 ((match-end 2)
15424 (setq line (replace-match
15425 (concat "@<a name=\""
15426 (org-solidify-link-text (match-string 1 line))
15427 "\">\\nbsp@</a>")
15428 t t line)))
15429 ((and org-export-with-toc (equal (string-to-char line) ?*))
15430 (setq line (replace-match
15431 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
15432 ; (concat "@<i>" (match-string 1 line) "@</i> ")
15433 t t line)))
15435 (setq line (replace-match
15436 (concat "@<a name=\""
15437 (org-solidify-link-text (match-string 1 line))
15438 "\" class=\"target\">" (match-string 1 line) "@</a> ")
15439 t t line)))))
15441 (setq line (org-html-handle-time-stamps line))
15443 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
15444 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
15445 ;; Also handle sub_superscripts and checkboxes
15446 (setq line (org-html-expand line))
15448 ;; Format the links
15449 (setq start 0)
15450 (while (string-match org-bracket-link-analytic-regexp line start)
15451 (setq start (match-beginning 0))
15452 (setq type (if (match-end 2) (match-string 2 line) "internal"))
15453 (setq path (match-string 3 line))
15454 (setq desc1 (if (match-end 5) (match-string 5 line))
15455 desc2 (if (match-end 2) (concat type ":" path) path)
15456 descp (and desc1 (not (equal desc1 desc2)))
15457 desc (or desc1 desc2))
15458 ;; FIXME: do we need to unescape here somewhere?
15459 (cond
15460 ((equal type "internal")
15461 (setq rpl
15462 (concat
15463 "<a href=\"#"
15464 (org-solidify-link-text path target-alist)
15465 "\">" desc "</a>")))
15466 ((member type '("http" "https" "ftp" "mailto" "news"))
15467 ;; standard URL
15468 (setq link (concat type ":" path))
15469 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
15470 ((string= type "file")
15471 ;; FILE link
15472 (let* ((filename path)
15473 (abs-p (file-name-absolute-p filename))
15474 thefile file-is-image-p search)
15475 (save-match-data
15476 (if (string-match "::\\(.*\\)" filename)
15477 (setq search (match-string 1 filename)
15478 filename (replace-match "" t nil filename)))
15479 (setq valid
15480 (if (functionp link-validate)
15481 (funcall link-validate filename current-dir)
15483 (setq file-is-image-p
15484 (string-match (org-image-file-name-regexp) filename))
15485 (setq thefile (if abs-p (expand-file-name filename) filename))
15486 (when (and org-export-html-link-org-files-as-html
15487 (string-match "\\.org$" thefile))
15488 (setq thefile (concat (substring thefile 0
15489 (match-beginning 0))
15490 ".html"))
15491 (if (and search
15492 ;; make sure this is can be used as target search
15493 (not (string-match "^[0-9]*$" search))
15494 (not (string-match "^\\*" search))
15495 (not (string-match "^/.*/$" search)))
15496 (setq thefile (concat thefile "#"
15497 (org-solidify-link-text
15498 (org-link-unescape search)))))
15499 (when (string-match "^file:" desc)
15500 (setq desc (replace-match "" t t desc))
15501 (if (string-match "\\.org$" desc)
15502 (setq desc (replace-match "" t t desc))))))
15503 (setq rpl (if (and file-is-image-p
15504 (or (eq t org-export-html-inline-images)
15505 (and org-export-html-inline-images
15506 (not descp))))
15507 (concat "<img src=\"" thefile "\"/>")
15508 (concat "<a href=\"" thefile "\">" desc "</a>")))
15509 (if (not valid) (setq rpl desc))))
15510 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
15511 (setq rpl (concat "<i>&lt;" type ":"
15512 (save-match-data (org-link-unescape path))
15513 "&gt;</i>"))))
15514 (setq line (replace-match rpl t t line)
15515 start (+ start (length rpl))))
15516 ;; TODO items
15517 (if (and (string-match org-todo-line-regexp line)
15518 (match-beginning 2))
15519 (if (equal (match-string 2 line) org-done-string)
15520 (setq line (replace-match
15521 "<span class=\"done\">\\2</span>"
15522 t nil line 2))
15523 (setq line (replace-match "<span class=\"todo\">\\2</span>"
15524 t nil line 2))))
15526 (cond
15527 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15528 ;; This is a headline
15529 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15530 txt (match-string 2 line))
15531 (if (string-match quote-re0 txt)
15532 (setq txt (replace-match "" t t txt)))
15533 (if (<= level umax) (setq head-count (+ head-count 1)))
15534 (when in-local-list
15535 ;; Close any local lists before inserting a new header line
15536 (while local-list-num
15537 (org-close-li)
15538 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15539 (pop local-list-num))
15540 (setq local-list-indent nil
15541 in-local-list nil))
15542 (org-html-level-start level txt umax
15543 (and org-export-with-toc (<= level umax))
15544 head-count)
15545 ;; QUOTES
15546 (when (string-match quote-re line)
15547 (insert "<pre>")
15548 (setq inquote t)))
15550 ((and org-export-with-tables
15551 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
15552 (if (not table-open)
15553 ;; New table starts
15554 (setq table-open t table-buffer nil table-orig-buffer nil))
15555 ;; Accumulate lines
15556 (setq table-buffer (cons line table-buffer)
15557 table-orig-buffer (cons origline table-orig-buffer))
15558 (when (or (not lines)
15559 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
15560 (car lines))))
15561 (setq table-open nil
15562 table-buffer (nreverse table-buffer)
15563 table-orig-buffer (nreverse table-orig-buffer))
15564 (org-close-par-maybe)
15565 (insert (org-format-table-html table-buffer table-orig-buffer))))
15567 ;; Normal lines
15568 (when (string-match
15569 (cond
15570 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15571 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15572 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
15573 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
15574 line)
15575 (setq ind (org-get-string-indentation line)
15576 start-is-num (match-beginning 4)
15577 starter (if (match-beginning 2)
15578 (substring (match-string 2 line) 0 -1))
15579 line (substring line (match-beginning 5)))
15580 (unless (string-match "[^ \t]" line)
15581 ;; empty line. Pretend indentation is large.
15582 (setq ind (1+ (or (car local-list-indent) 1))))
15583 (while (and in-local-list
15584 (or (and (= ind (car local-list-indent))
15585 (not starter))
15586 (< ind (car local-list-indent))))
15587 (org-close-li)
15588 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
15589 (pop local-list-num) (pop local-list-indent)
15590 (setq in-local-list local-list-indent))
15591 (cond
15592 ((and starter
15593 (or (not in-local-list)
15594 (> ind (car local-list-indent))))
15595 ;; Start new (level of ) list
15596 (org-close-par-maybe)
15597 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
15598 (push start-is-num local-list-num)
15599 (push ind local-list-indent)
15600 (setq in-local-list t))
15601 (starter
15602 ;; continue current list
15603 (org-close-li)
15604 (insert "<li>\n")))
15605 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
15606 (setq line
15607 (replace-match
15608 (if (equal (match-string 1 line) "X")
15609 "<b>[X]</b>"
15610 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
15611 t t line))))
15613 ;; Empty lines start a new paragraph. If hand-formatted lists
15614 ;; are not fully interpreted, lines starting with "-", "+", "*"
15615 ;; also start a new paragraph.
15616 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
15618 ;; Check if the line break needs to be conserved
15619 (cond
15620 ((string-match "\\\\\\\\[ \t]*$" line)
15621 (setq line (replace-match "<br/>" t t line)))
15622 (org-export-preserve-breaks
15623 (setq line (concat line "<br/>"))))
15625 (insert line "\n")))))
15627 ;; Properly close all local lists and other lists
15628 (when inquote (insert "</pre>\n"))
15629 (when in-local-list
15630 ;; Close any local lists before inserting a new header line
15631 (while local-list-num
15632 (org-close-li)
15633 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
15634 (pop local-list-num))
15635 (setq local-list-indent nil
15636 in-local-list nil))
15637 (org-html-level-start 1 nil umax
15638 (and org-export-with-toc (<= level umax))
15639 head-count)
15641 (when (plist-get opt-plist :auto-postamble)
15642 (when author
15643 (insert "<p class=\"author\"> "
15644 (nth 1 lang-words) ": " author "\n")
15645 (when email
15646 (insert "<a href=\"mailto:" email "\">&lt;"
15647 email "&gt;</a>\n"))
15648 (insert "</p>\n"))
15649 (when (and date time)
15650 (insert "<p class=\"date\"> "
15651 (nth 2 lang-words) ": "
15652 date " " time "</p>\n")))
15654 (if org-export-html-with-timestamp
15655 (insert org-export-html-html-helper-timestamp))
15656 (insert (or (plist-get opt-plist :postamble) ""))
15657 (insert "</body>\n</html>\n")
15658 (normal-mode)
15659 ;; remove empty paragraphs and lists
15660 (goto-char (point-min))
15661 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
15662 (replace-match ""))
15663 (goto-char (point-min))
15664 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
15665 (replace-match ""))
15666 (save-buffer)
15667 (goto-char (point-min))
15668 (message "Exporting... done"))))
15671 (defun org-format-table-html (lines olines)
15672 "Find out which HTML converter to use and return the HTML code."
15673 (if (string-match "^[ \t]*|" (car lines))
15674 ;; A normal org table
15675 (org-format-org-table-html lines)
15676 ;; Table made by table.el - test for spanning
15677 (let* ((hlines (delq nil (mapcar
15678 (lambda (x)
15679 (if (string-match "^[ \t]*\\+-" x) x
15680 nil))
15681 lines)))
15682 (first (car hlines))
15683 (ll (and (string-match "\\S-+" first)
15684 (match-string 0 first)))
15685 (re (concat "^[ \t]*" (regexp-quote ll)))
15686 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
15687 hlines))))
15688 (if (and (not spanning)
15689 (not org-export-prefer-native-exporter-for-tables))
15690 ;; We can use my own converter with HTML conversions
15691 (org-format-table-table-html lines)
15692 ;; Need to use the code generator in table.el, with the original text.
15693 (org-format-table-table-html-using-table-generate-source olines)))))
15695 (defun org-format-org-table-html (lines)
15696 "Format a table into HTML."
15697 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15698 (setq lines (nreverse lines))
15699 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
15700 (setq lines (nreverse lines))
15701 (when org-export-table-remove-special-lines
15702 ;; Check if the table has a marking column. If yes remove the
15703 ;; column and the special lines
15704 (let* ((special
15705 (not
15706 (memq nil
15707 (mapcar
15708 (lambda (x)
15709 (or (string-match "^[ \t]*|-" x)
15710 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
15711 lines)))))
15712 (if special
15713 (setq lines
15714 (delq nil
15715 (mapcar
15716 (lambda (x)
15717 (if (string-match "^[ \t]*| *[!_^] *|" x)
15718 nil ; ignore this line
15719 (and (or (string-match "^[ \t]*|-+\\+" x)
15720 (string-match "^[ \t]*|[^|]*|" x))
15721 (replace-match "|" t t x))))
15722 lines))))))
15724 (let ((head (and org-export-highlight-first-table-line
15725 (delq nil (mapcar
15726 (lambda (x) (string-match "^[ \t]*|-" x))
15727 (cdr lines)))))
15728 line fields html)
15729 (setq html (concat org-export-html-table-tag "\n"))
15730 (while (setq line (pop lines))
15731 (catch 'next-line
15732 (if (string-match "^[ \t]*|-" line)
15733 (progn
15734 (setq head nil) ;; head ends here, first time around
15735 ;; ignore this line
15736 (throw 'next-line t)))
15737 ;; Break the line into fields
15738 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15739 (setq html (concat
15740 html
15741 "<tr>"
15742 (mapconcat (lambda (x)
15743 (if head
15744 (concat "<th>" x "</th>")
15745 (concat "<td>" x "</td>")))
15746 fields "")
15747 "</tr>\n"))))
15748 (setq html (concat html "</table>\n"))
15749 html))
15751 (defun org-fake-empty-table-line (line)
15752 "Replace everything except \"|\" with spaces."
15753 (let ((i (length line))
15754 (newstr (copy-sequence line)))
15755 (while (> i 0)
15756 (setq i (1- i))
15757 (if (not (eq (aref newstr i) ?|))
15758 (aset newstr i ?\ )))
15759 newstr))
15761 (defun org-format-table-table-html (lines)
15762 "Format a table generated by table.el into HTML.
15763 This conversion does *not* use `table-generate-source' from table.el.
15764 This has the advantage that Org-mode's HTML conversions can be used.
15765 But it has the disadvantage, that no cell- or row-spanning is allowed."
15766 (let (line field-buffer
15767 (head org-export-highlight-first-table-line)
15768 fields html empty)
15769 (setq html (concat org-export-html-table-tag "\n"))
15770 (while (setq line (pop lines))
15771 (setq empty "&nbsp;")
15772 (catch 'next-line
15773 (if (string-match "^[ \t]*\\+-" line)
15774 (progn
15775 (if field-buffer
15776 (progn
15777 (setq html (concat
15778 html
15779 "<tr>"
15780 (mapconcat
15781 (lambda (x)
15782 (if (equal x "") (setq x empty))
15783 (if head
15784 (concat "<th>" x "</th>\n")
15785 (concat "<td>" x "</td>\n")))
15786 field-buffer "\n")
15787 "</tr>\n"))
15788 (setq head nil)
15789 (setq field-buffer nil)))
15790 ;; Ignore this line
15791 (throw 'next-line t)))
15792 ;; Break the line into fields and store the fields
15793 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
15794 (if field-buffer
15795 (setq field-buffer (mapcar
15796 (lambda (x)
15797 (concat x "<br/>" (pop fields)))
15798 field-buffer))
15799 (setq field-buffer fields))))
15800 (setq html (concat html "</table>\n"))
15801 html))
15803 (defun org-format-table-table-html-using-table-generate-source (lines)
15804 "Format a table into html, using `table-generate-source' from table.el.
15805 This has the advantage that cell- or row-spanning is allowed.
15806 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
15807 (require 'table)
15808 (with-current-buffer (get-buffer-create " org-tmp1 ")
15809 (erase-buffer)
15810 (insert (mapconcat 'identity lines "\n"))
15811 (goto-char (point-min))
15812 (if (not (re-search-forward "|[^+]" nil t))
15813 (error "Error processing table"))
15814 (table-recognize-table)
15815 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
15816 (table-generate-source 'html " org-tmp2 ")
15817 (set-buffer " org-tmp2 ")
15818 (buffer-substring (point-min) (point-max))))
15820 (defun org-html-handle-time-stamps (s)
15821 "Format time stamps in string S, or remove them."
15822 (catch 'exit
15823 (let (r b)
15824 (while (string-match org-maybe-keyword-time-regexp s)
15825 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
15826 ;; never export CLOCK
15827 (throw 'exit ""))
15828 (or b (setq b (substring s 0 (match-beginning 0))))
15829 (if (not org-export-with-timestamps)
15830 (setq r (concat r (substring s 0 (match-beginning 0)))
15831 s (substring s (match-end 0)))
15832 (setq r (concat
15833 r (substring s 0 (match-beginning 0))
15834 (if (match-end 1)
15835 (format "@<span class=\"timestamp-kwd\">%s @</span>"
15836 (match-string 1 s)))
15837 (format " @<span class=\"timestamp\">%s@</span>"
15838 (substring
15839 (org-translate-time (match-string 3 s)) 1 -1)))
15840 s (substring s (match-end 0)))))
15841 ;; Line break if line started and ended with time stamp stuff
15842 (if (not r)
15844 (setq r (concat r s))
15845 (unless (string-match "\\S-" (concat b s))
15846 (setq r (concat r "@<br/>")))
15847 r))))
15849 (defun org-html-protect (s)
15850 ;; convert & to &amp;, < to &lt; and > to &gt;
15851 (let ((start 0))
15852 (while (string-match "&" s start)
15853 (setq s (replace-match "&amp;" t t s)
15854 start (1+ (match-beginning 0))))
15855 (while (string-match "<" s)
15856 (setq s (replace-match "&lt;" t t s)))
15857 (while (string-match ">" s)
15858 (setq s (replace-match "&gt;" t t s))))
15861 (defun org-export-cleanup-toc-line (s)
15862 "Remove tags and time staps from lines going into the toc."
15863 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
15864 (setq s (replace-match "" t t s)))
15865 (when org-export-remove-timestamps-from-toc
15866 (while (string-match org-maybe-keyword-time-regexp s)
15867 (setq s (replace-match "" t t s))))
15870 (defun org-html-expand (string)
15871 "Prepare STRING for HTML export. Applies all active conversions.
15872 If there are links in the string, don't modify these."
15873 (let* (m s l res)
15874 (while (setq m (string-match org-bracket-link-regexp string))
15875 (setq s (substring string 0 m)
15876 l (match-string 0 string)
15877 string (substring string (match-end 0)))
15878 (push (org-html-do-expand s) res)
15879 (push l res))
15880 (push (org-html-do-expand string) res)
15881 (apply 'concat (nreverse res))))
15883 (defun org-html-do-expand (s)
15884 "Apply all active conversions to translate special ASCII to HTML."
15885 (setq s (org-html-protect s))
15886 (if org-export-html-expand
15887 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
15888 (setq s (replace-match "<\\1>" t nil s))))
15889 (if org-export-with-emphasize
15890 (setq s (org-export-html-convert-emphasize s)))
15891 (if org-export-with-sub-superscripts
15892 (setq s (org-export-html-convert-sub-super s)))
15893 (if org-export-with-TeX-macros
15894 (let ((start 0) wd ass)
15895 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
15896 (setq wd (match-string 1 s))
15897 (if (setq ass (assoc wd org-html-entities))
15898 (setq s (replace-match (or (cdr ass)
15899 (concat "&" (car ass) ";"))
15900 t t s))
15901 (setq start (+ start (length wd)))))))
15904 (defun org-create-multibrace-regexp (left right n)
15905 "Create a regular expression which will match a balanced sexp.
15906 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
15907 as single character strings.
15908 The regexp returned will match the entire expression including the
15909 delimiters. It will also define a single group which contains the
15910 match except for the outermost delimiters. The maximum depth of
15911 stacked delimiters is N. Escaping delimiters is not possible."
15912 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
15913 (or "\\|")
15914 (re nothing)
15915 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
15916 (while (> n 1)
15917 (setq n (1- n)
15918 re (concat re or next)
15919 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
15920 (concat left "\\(" re "\\)" right)))
15922 (defvar org-match-substring-regexp
15923 (concat
15924 "\\([^\\]\\)\\([_^]\\)\\("
15925 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
15926 "\\|"
15927 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
15928 "\\|"
15929 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
15930 "The regular expression matching a sub- or superscript.")
15932 (defun org-export-html-convert-sub-super (string)
15933 "Convert sub- and superscripts in STRING to HTML."
15934 (let (key c)
15935 (while (string-match org-match-substring-regexp string)
15936 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
15937 (setq c (or (match-string 8 string)
15938 (match-string 6 string)
15939 (match-string 5 string)))
15940 (setq string (replace-match
15941 (concat (match-string 1 string)
15942 "<" key ">" c "</" key ">")
15943 t t string)))
15944 (while (string-match "\\\\\\([_^]\\)" string)
15945 (setq string (replace-match (match-string 1 string) t t string))))
15946 string)
15948 (defun org-export-html-convert-emphasize (string)
15949 "Apply emphasis."
15950 (while (string-match org-emph-re string)
15951 (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)))
15952 string)
15954 (defvar org-par-open nil)
15955 (defun org-open-par ()
15956 "Insert <p>, but first close previous paragraph if any."
15957 (org-close-par-maybe)
15958 (insert "\n<p>")
15959 (setq org-par-open t))
15960 (defun org-close-par-maybe ()
15961 "Close paragraph if there is one open."
15962 (when org-par-open
15963 (insert "</p>")
15964 (setq org-par-open nil)))
15965 (defun org-close-li ()
15966 "Close <li> if necessary."
15967 (org-close-par-maybe)
15968 (insert "</li>\n"))
15969 ; (when (save-excursion
15970 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
15971 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
15972 ; (insert "</li>"))))
15974 (defun org-html-level-start (level title umax with-toc head-count)
15975 "Insert a new level in HTML export.
15976 When TITLE is nil, just close all open levels."
15977 (org-close-par-maybe)
15978 (let ((l (1+ (max level umax))))
15979 (while (<= l org-level-max)
15980 (if (aref levels-open (1- l))
15981 (progn
15982 (org-html-level-close l)
15983 (aset levels-open (1- l) nil)))
15984 (setq l (1+ l)))
15985 (when title
15986 ;; If title is nil, this means this function is called to close
15987 ;; all levels, so the rest is done only if title is given
15988 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
15989 (setq title (replace-match
15990 (if org-export-with-tags
15991 (save-match-data
15992 (concat
15993 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
15994 (mapconcat 'identity (org-split-string
15995 (match-string 1 title) ":")
15996 "&nbsp;")
15997 "</span>"))
15999 t t title)))
16000 (if (> level umax)
16001 (progn
16002 (if (aref levels-open (1- level))
16003 (progn
16004 (org-close-li)
16005 (insert "<li>" title "<br/>\n"))
16006 (aset levels-open (1- level) t)
16007 (org-close-par-maybe)
16008 (insert "<ul>\n<li>" title "<br/>\n")))
16009 (if org-export-with-section-numbers
16010 (setq title (concat (org-section-number level) " " title)))
16011 (setq level (+ level org-export-html-toplevel-hlevel -1))
16012 (if with-toc
16013 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
16014 level head-count title level))
16015 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
16016 (org-open-par)))))
16018 (defun org-html-level-close (&rest args)
16019 "Terminate one level in HTML export."
16020 (org-close-li)
16021 (insert "</ul>"))
16023 ;; Variable holding the vector with section numbers
16024 (defvar org-section-numbers (make-vector org-level-max 0))
16026 (defun org-init-section-numbers ()
16027 "Initialize the vector for the section numbers."
16028 (let* ((level -1)
16029 (numbers (nreverse (org-split-string "" "\\.")))
16030 (depth (1- (length org-section-numbers)))
16031 (i depth) number-string)
16032 (while (>= i 0)
16033 (if (> i level)
16034 (aset org-section-numbers i 0)
16035 (setq number-string (or (car numbers) "0"))
16036 (if (string-match "\\`[A-Z]\\'" number-string)
16037 (aset org-section-numbers i
16038 (- (string-to-char number-string) ?A -1))
16039 (aset org-section-numbers i (string-to-number number-string)))
16040 (pop numbers))
16041 (setq i (1- i)))))
16043 (defun org-section-number (&optional level)
16044 "Return a string with the current section number.
16045 When LEVEL is non-nil, increase section numbers on that level."
16046 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
16047 (when level
16048 (when (> level -1)
16049 (aset org-section-numbers
16050 level (1+ (aref org-section-numbers level))))
16051 (setq idx (1+ level))
16052 (while (<= idx depth)
16053 (if (not (= idx 1))
16054 (aset org-section-numbers idx 0))
16055 (setq idx (1+ idx))))
16056 (setq idx 0)
16057 (while (<= idx depth)
16058 (setq n (aref org-section-numbers idx))
16059 (setq string (concat string (if (not (string= string "")) "." "")
16060 (int-to-string n)))
16061 (setq idx (1+ idx)))
16062 (save-match-data
16063 (if (string-match "\\`\\([@0]\\.\\)+" string)
16064 (setq string (replace-match "" t nil string)))
16065 (if (string-match "\\(\\.0\\)+\\'" string)
16066 (setq string (replace-match "" t nil string))))
16067 string))
16070 ;;;###autoload
16071 (defun org-export-icalendar-this-file ()
16072 "Export current file as an iCalendar file.
16073 The iCalendar file will be located in the same directory as the Org-mode
16074 file, but with extension `.ics'."
16075 (interactive)
16076 (org-export-icalendar nil buffer-file-name))
16078 (defun org-export-as-xoxo-insert-into (buffer &rest output)
16079 (with-current-buffer buffer
16080 (apply 'insert output)))
16081 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
16083 (defun org-export-as-xoxo (&optional buffer)
16084 "Export the org buffer as XOXO.
16085 The XOXO buffer is named *xoxo-<source buffer name>*"
16086 (interactive (list (current-buffer)))
16087 ;; A quickie abstraction
16089 ;; Output everything as XOXO
16090 (with-current-buffer (get-buffer buffer)
16091 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
16092 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
16093 (org-infile-export-plist)))
16094 (filename (concat (file-name-as-directory
16095 (org-export-directory :xoxo opt-plist))
16096 (file-name-sans-extension
16097 (file-name-nondirectory buffer-file-name))
16098 ".html"))
16099 (out (find-file-noselect filename))
16100 (last-level 1)
16101 (hanging-li nil))
16102 ;; Check the output buffer is empty.
16103 (with-current-buffer out (erase-buffer))
16104 ;; Kick off the output
16105 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
16106 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
16107 (let* ((hd (match-string-no-properties 1))
16108 (level (length hd))
16109 (text (concat
16110 (match-string-no-properties 2)
16111 (save-excursion
16112 (goto-char (match-end 0))
16113 (let ((str ""))
16114 (catch 'loop
16115 (while 't
16116 (forward-line)
16117 (if (looking-at "^[ \t]\\(.*\\)")
16118 (setq str (concat str (match-string-no-properties 1)))
16119 (throw 'loop str)))))))))
16121 ;; Handle level rendering
16122 (cond
16123 ((> level last-level)
16124 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
16126 ((< level last-level)
16127 (dotimes (- (- last-level level) 1)
16128 (if hanging-li
16129 (org-export-as-xoxo-insert-into out "</li>\n"))
16130 (org-export-as-xoxo-insert-into out "</ol>\n"))
16131 (when hanging-li
16132 (org-export-as-xoxo-insert-into out "</li>\n")
16133 (setq hanging-li nil)))
16135 ((equal level last-level)
16136 (if hanging-li
16137 (org-export-as-xoxo-insert-into out "</li>\n")))
16140 (setq last-level level)
16142 ;; And output the new li
16143 (setq hanging-li 't)
16144 (if (equal ?+ (elt text 0))
16145 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
16146 (org-export-as-xoxo-insert-into out "<li>" text))))
16148 ;; Finally finish off the ol
16149 (dotimes (- last-level 1)
16150 (if hanging-li
16151 (org-export-as-xoxo-insert-into out "</li>\n"))
16152 (org-export-as-xoxo-insert-into out "</ol>\n"))
16154 ;; Finish the buffer off and clean it up.
16155 (switch-to-buffer-other-window out)
16156 (indent-region (point-min) (point-max) nil)
16157 (save-buffer)
16158 (goto-char (point-min))
16161 ;;;###autoload
16162 (defun org-export-icalendar-all-agenda-files ()
16163 "Export all files in `org-agenda-files' to iCalendar .ics files.
16164 Each iCalendar file will be located in the same directory as the Org-mode
16165 file, but with extension `.ics'."
16166 (interactive)
16167 (apply 'org-export-icalendar nil (org-agenda-files t)))
16169 ;;;###autoload
16170 (defun org-export-icalendar-combine-agenda-files ()
16171 "Export all files in `org-agenda-files' to a single combined iCalendar file.
16172 The file is stored under the name `org-combined-agenda-icalendar-file'."
16173 (interactive)
16174 (apply 'org-export-icalendar t (org-agenda-files t)))
16176 (defun org-export-icalendar (combine &rest files)
16177 "Create iCalendar files for all elements of FILES.
16178 If COMBINE is non-nil, combine all calendar entries into a single large
16179 file and store it under the name `org-combined-agenda-icalendar-file'."
16180 (save-excursion
16181 (let* ((dir (org-export-directory
16182 :ical (list :publishing-directory
16183 org-export-publishing-directory)))
16184 file ical-file ical-buffer category started org-agenda-new-buffers)
16186 (when combine
16187 (setq ical-file
16188 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
16189 org-combined-agenda-icalendar-file
16190 (expand-file-name org-combined-agenda-icalendar-file dir))
16191 ical-buffer (org-get-agenda-file-buffer ical-file))
16192 (set-buffer ical-buffer) (erase-buffer))
16193 (while (setq file (pop files))
16194 (catch 'nextfile
16195 (org-check-agenda-file file)
16196 (set-buffer (org-get-agenda-file-buffer file))
16197 (unless combine
16198 (setq ical-file (concat (file-name-as-directory dir)
16199 (file-name-sans-extension
16200 (file-name-nondirectory buffer-file-name))
16201 ".ics"))
16202 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
16203 (with-current-buffer ical-buffer (erase-buffer)))
16204 (setq category (or org-category
16205 (file-name-sans-extension
16206 (file-name-nondirectory buffer-file-name))))
16207 (if (symbolp category) (setq category (symbol-name category)))
16208 (let ((standard-output ical-buffer))
16209 (if combine
16210 (and (not started) (setq started t)
16211 (org-start-icalendar-file org-icalendar-combined-name))
16212 (org-start-icalendar-file category))
16213 (org-print-icalendar-entries combine category)
16214 (when (or (and combine (not files)) (not combine))
16215 (org-finish-icalendar-file)
16216 (set-buffer ical-buffer)
16217 (save-buffer)
16218 (run-hooks 'org-after-save-iCalendar-file-hook)))))
16219 (org-release-buffers org-agenda-new-buffers))))
16221 (defvar org-after-save-iCalendar-file-hook nil
16222 "Hook run after an iCalendar file has been saved.
16223 The iCalendar buffer is still current when this hook is run.
16224 A good way to use this is to tell a desktop calenndar application to re-read
16225 the iCalendar file.")
16227 (defun org-print-icalendar-entries (&optional combine category)
16228 "Print iCalendar entries for the current Org-mode file to `standard-output'.
16229 When COMBINE is non nil, add the category to each line."
16230 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
16231 (dts (org-ical-ts-to-string
16232 (format-time-string (cdr org-time-stamp-formats) (current-time))
16233 "DTSTART"))
16234 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
16235 (save-excursion
16236 (goto-char (point-min))
16237 (while (re-search-forward org-ts-regexp nil t)
16238 (setq pos (match-beginning 0)
16239 ts (match-string 0)
16240 inc t
16241 hd (org-get-heading))
16242 (if (looking-at re2)
16243 (progn
16244 (goto-char (match-end 0))
16245 (setq ts2 (match-string 1) inc nil))
16246 (setq ts2 ts
16247 tmp (buffer-substring (max (point-min)
16248 (- pos org-ds-keyword-length))
16249 pos)
16250 deadlinep (string-match org-deadline-regexp tmp)
16251 scheduledp (string-match org-scheduled-regexp tmp)
16252 ;; donep (org-entry-is-done-p)
16254 (if (or (string-match org-tr-regexp hd)
16255 (string-match org-ts-regexp hd))
16256 (setq hd (replace-match "" t t hd)))
16257 (if combine
16258 (setq hd (concat hd " (category " category ")")))
16259 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
16260 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
16261 (princ (format "BEGIN:VEVENT
16264 SUMMARY:%s
16265 END:VEVENT\n"
16266 (org-ical-ts-to-string ts "DTSTART")
16267 (org-ical-ts-to-string ts2 "DTEND" inc)
16268 hd)))
16269 (when org-icalendar-include-todo
16270 (goto-char (point-min))
16271 (while (re-search-forward org-todo-line-regexp nil t)
16272 (setq state (match-string 1))
16273 (unless (equal state org-done-string)
16274 (setq hd (match-string 3))
16275 (if (string-match org-priority-regexp hd)
16276 (setq pri (string-to-char (match-string 2 hd))
16277 hd (concat (substring hd 0 (match-beginning 1))
16278 (substring hd (- (match-end 1)))))
16279 (setq pri org-default-priority))
16280 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
16281 (- org-lowest-priority ?A))))))
16283 (princ (format "BEGIN:VTODO
16285 SUMMARY:%s
16286 SEQUENCE:1
16287 PRIORITY:%d
16288 END:VTODO\n"
16289 dts hd pri))))))))
16291 (defun org-start-icalendar-file (name)
16292 "Start an iCalendar file by inserting the header."
16293 (let ((user user-full-name)
16294 (name (or name "unknown"))
16295 (timezone (cadr (current-time-zone))))
16296 (princ
16297 (format "BEGIN:VCALENDAR
16298 VERSION:2.0
16299 X-WR-CALNAME:%s
16300 PRODID:-//%s//Emacs with Org-mode//EN
16301 X-WR-TIMEZONE:%s
16302 CALSCALE:GREGORIAN\n" name user timezone))))
16304 (defun org-finish-icalendar-file ()
16305 "Finish an iCalendar file by inserting the END statement."
16306 (princ "END:VCALENDAR\n"))
16308 (defun org-ical-ts-to-string (s keyword &optional inc)
16309 "Take a time string S and convert it to iCalendar format.
16310 KEYWORD is added in front, to make a complete line like DTSTART....
16311 When INC is non-nil, increase the hour by two (if time string contains
16312 a time), or the day by one (if it does not contain a time)."
16313 (let ((t1 (org-parse-time-string s 'nodefault))
16314 t2 fmt have-time time)
16315 (if (and (car t1) (nth 1 t1) (nth 2 t1))
16316 (setq t2 t1 have-time t)
16317 (setq t2 (org-parse-time-string s)))
16318 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
16319 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
16320 (when inc
16321 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
16322 (setq time (encode-time s mi h d m y)))
16323 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
16324 (concat keyword (format-time-string fmt time))))
16326 ;;; LaTeX stuff
16328 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16329 "Keymap for the minor `org-cdlatex-mode'.")
16331 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16332 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16333 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16334 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16335 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16337 (defvar org-cdlatex-texmathp-advice-is-done nil
16338 "Flag remembering if we have applied the advice to texmathp already.")
16340 (define-minor-mode org-cdlatex-mode
16341 "Toggle the minor `org-cdlatex-mode'.
16342 This mode supports entering LaTeX environment and math in LaTeX fragments
16343 in Org-mode.
16344 \\{org-cdlatex-mode-map}"
16345 nil " OCDL" nil
16346 (when org-cdlatex-mode (require 'cdlatex))
16347 (unless org-cdlatex-texmathp-advice-is-done
16348 (setq org-cdlatex-texmathp-advice-is-done t)
16349 (defadvice texmathp (around org-math-always-on activate)
16350 "Always return t in org-mode buffers.
16351 This is because we want to insert math symbols without dollars even outside
16352 the LaTeX math segments. If Orgmode thinks that point is actually inside
16353 en embedded LaTeX fragement, let texmathp do its job.
16354 \\[org-cdlatex-mode-map]"
16355 (interactive)
16356 (let (p)
16357 (cond
16358 ((not (org-mode-p)) ad-do-it)
16359 ((eq this-command 'cdlatex-math-symbol)
16360 (setq ad-return-value t
16361 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16363 (let ((p (org-inside-LaTeX-fragment-p)))
16364 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16365 (setq ad-return-value t
16366 texmathp-why '("Org-mode embedded math" . 0))
16367 (if p ad-do-it)))))))))
16369 (defun turn-on-org-cdlatex ()
16370 "Unconditionally turn on `org-cdlatex-mode'."
16371 (org-cdlatex-mode 1))
16373 (defun org-inside-LaTeX-fragment-p ()
16374 "Test if point is inside a LaTeX fragment.
16375 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16376 sequence appearing also before point.
16377 Even though the matchers for math are configurable, this function assumes
16378 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16379 delimiters are skipped when they have been removed by customization.
16380 The return value is nil, or a cons cell with the delimiter and
16381 and the position of this delimiter.
16383 This function does a reasonably good job, but can locally be fooled by
16384 for example currency specifications. For example it will assume being in
16385 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16386 fragments that are properly closed, but during editing, we have to live
16387 with the uncertainty caused by missing closing delimiters. This function
16388 looks only before point, not after."
16389 (catch 'exit
16390 (let ((pos (point))
16391 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16392 (lim (progn
16393 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16394 (point)))
16395 dd-on str (start 0) m re)
16396 (goto-char pos)
16397 (when dodollar
16398 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16399 re (nth 1 (assoc "$" org-latex-regexps)))
16400 (while (string-match re str start)
16401 (cond
16402 ((= (match-end 0) (length str))
16403 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16404 ((= (match-end 0) (- (length str) 5))
16405 (throw 'exit nil))
16406 (t (setq start (match-end 0))))))
16407 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16408 (goto-char pos)
16409 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16410 (and (match-beginning 2) (throw 'exit nil))
16411 ;; count $$
16412 (while (re-search-backward "\\$\\$" lim t)
16413 (setq dd-on (not dd-on)))
16414 (goto-char pos)
16415 (if dd-on (cons "$$" m))))))
16418 (defun org-try-cdlatex-tab ()
16419 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16420 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16421 - inside a LaTeX fragment, or
16422 - after the first word in a line, where an abbreviation expansion could
16423 insert a LaTeX environment."
16424 (when org-cdlatex-mode
16425 (cond
16426 ((save-excursion
16427 (skip-chars-backward "a-zA-Z0-9*")
16428 (skip-chars-backward " \t")
16429 (bolp))
16430 (cdlatex-tab) t)
16431 ((org-inside-LaTeX-fragment-p)
16432 (cdlatex-tab) t)
16433 (t nil))))
16435 (defun org-cdlatex-underscore-caret (&optional arg)
16436 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16437 Revert to the normal definition outside of these fragments."
16438 (interactive "P")
16439 (if (org-inside-LaTeX-fragment-p)
16440 (call-interactively 'cdlatex-sub-superscript)
16441 (let (org-cdlatex-mode)
16442 (call-interactively (key-binding (vector last-input-event))))))
16444 (defun org-cdlatex-math-modify (&optional arg)
16445 "Execute `cdlatex-math-modify' in LaTeX fragments.
16446 Revert to the normal definition outside of these fragments."
16447 (interactive "P")
16448 (if (org-inside-LaTeX-fragment-p)
16449 (call-interactively 'cdlatex-math-modify)
16450 (let (org-cdlatex-mode)
16451 (call-interactively (key-binding (vector last-input-event))))))
16453 (defvar org-latex-fragment-image-overlays nil
16454 "List of overlays carrying the images of latex fragments.")
16455 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16457 (defun org-remove-latex-fragment-image-overlays ()
16458 "Remove all overlays with LaTeX fragment images in current buffer."
16459 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16460 (setq org-latex-fragment-image-overlays nil))
16462 (defun org-preview-latex-fragment (&optional subtree)
16463 "Preview the LaTeX fragment at point, or all locally or globally.
16464 If the cursor is in a LaTeX fragment, create the image and overlay
16465 it over the source code. If there is no fragment at point, display
16466 all fragments in the current text, from one headline to the next. With
16467 prefix SUBTREE, display all fragments in the current subtree. With a
16468 double prefix `C-u C-u', or when the cursor is before the first headline,
16469 display all fragments in the buffer.
16470 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16471 (interactive "P")
16472 (org-remove-latex-fragment-image-overlays)
16473 (save-excursion
16474 (save-restriction
16475 (let (beg end at msg)
16476 (cond
16477 ((or (equal subtree '(16))
16478 (not (save-excursion
16479 (re-search-backward (concat "^" outline-regexp) nil t))))
16480 (setq beg (point-min) end (point-max)
16481 msg "Creating images for buffer...%s"))
16482 ((equal subtree '(4))
16483 (org-back-to-heading)
16484 (setq beg (point) end (org-end-of-subtree t)
16485 msg "Creating images for subtree...%s"))
16487 (if (setq at (org-inside-LaTeX-fragment-p))
16488 (goto-char (max (point-min) (- (cdr at) 2)))
16489 (org-back-to-heading))
16490 (setq beg (point) end (progn (outline-next-heading) (point))
16491 msg (if at "Creating image...%s"
16492 "Creating images for entry...%s"))))
16493 (message msg "")
16494 (narrow-to-region beg end)
16495 (org-format-latex
16496 (concat "ltxpng/" (file-name-sans-extension
16497 (file-name-nondirectory
16498 buffer-file-name)))
16499 default-directory 'overlays msg at)
16500 (message msg "done. Use `C-c C-c' to remove images.")))))
16502 (defvar org-latex-regexps
16503 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16504 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16505 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16506 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16507 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16508 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16509 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16510 "Regular expressions for matching embedded LaTeX.")
16512 (defun org-format-latex (prefix &optional dir overlays msg at)
16513 "Replace LaTeX fragments with links to an image, and produce images."
16514 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16515 (let* ((prefixnodir (file-name-nondirectory prefix))
16516 (absprefix (expand-file-name prefix dir))
16517 (todir (file-name-directory absprefix))
16518 (opt org-format-latex-options)
16519 (matchers (plist-get opt :matchers))
16520 (re-list org-latex-regexps)
16521 (cnt 0) txt link beg end re e oldfiles
16522 m n block linkfile movefile ov)
16523 ;; Make sure the directory exists
16524 (or (file-directory-p todir) (make-directory todir))
16525 ;; Check if there are old images files with this prefix, and remove them
16526 (setq oldfiles (directory-files
16527 todir 'full
16528 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
16529 (while oldfiles (delete-file (pop oldfiles)))
16530 ;; Check the different regular expressions
16531 (while (setq e (pop re-list))
16532 (setq m (car e) re (nth 1 e) n (nth 2 e)
16533 block (if (nth 3 e) "\n\n" ""))
16534 (when (member m matchers)
16535 (goto-char (point-min))
16536 (while (re-search-forward re nil t)
16537 (when (or (not at) (equal (cdr at) (match-beginning n)))
16538 (setq txt (match-string n)
16539 beg (match-beginning n) end (match-end n)
16540 cnt (1+ cnt)
16541 linkfile (format "%s_%04d.png" prefix cnt)
16542 movefile (format "%s_%04d.png" absprefix cnt)
16543 link (concat block "[[file:" linkfile "]]" block))
16544 (if msg (message msg cnt))
16545 (goto-char beg)
16546 (org-create-formula-image
16547 txt movefile opt)
16548 (if overlays
16549 (progn
16550 (setq ov (org-make-overlay beg end))
16551 (if (featurep 'xemacs)
16552 (progn
16553 (org-overlay-put ov 'invisible t)
16554 (org-overlay-put
16555 ov 'end-glyph
16556 (make-glyph (vector 'png :file movefile))))
16557 (org-overlay-put
16558 ov 'display
16559 (list 'image :type 'png :file movefile :ascent 'center)))
16560 (push ov org-latex-fragment-image-overlays)
16561 (goto-char end))
16562 (delete-region beg end)
16563 (insert link))))))))
16565 ;; This function borrows from Ganesh Swami's latex2png.el
16566 (defun org-create-formula-image (string tofile options)
16567 (let* ((tmpdir (if (featurep 'xemacs)
16568 (temp-directory)
16569 temporary-file-directory))
16570 (texfilebase (make-temp-name
16571 (expand-file-name "orgtex" tmpdir)))
16573 ;(texfilebase (make-temp-file "orgtex"))
16574 ; (dummy (delete-file texfilebase))
16575 (texfile (concat texfilebase ".tex"))
16576 (dvifile (concat texfilebase ".dvi"))
16577 (pngfile (concat texfilebase ".png"))
16578 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16579 (fg (or (plist-get options :foreground) "Black"))
16580 (bg (or (plist-get options :background) "Transparent")))
16581 (with-temp-file texfile
16582 (insert "\\documentclass{article}
16583 \\usepackage{fullpage}
16584 \\usepackage{amssymb}
16585 \\usepackage[usenames]{color}
16586 \\usepackage{amsmath}
16587 \\usepackage{latexsym}
16588 \\usepackage[mathscr]{eucal}
16589 \\pagestyle{empty}
16590 \\begin{document}\n" string "\n\\end{document}\n"))
16591 (let ((dir default-directory))
16592 (condition-case nil
16593 (progn
16594 (cd tmpdir)
16595 (call-process "latex" nil nil nil texfile))
16596 (error nil))
16597 (cd dir))
16598 (if (not (file-exists-p dvifile))
16599 (progn (message "Failed to create dvi file from %s" texfile) nil)
16600 (call-process "dvipng" nil nil nil
16601 "-E" "-fg" fg "-bg" bg
16602 "-x" scale "-y" scale "-T" "tight"
16603 "-o" pngfile
16604 dvifile)
16605 (if (not (file-exists-p pngfile))
16606 (progn (message "Failed to create png file from %s" texfile) nil)
16607 ;; Use the requested file name and clean up
16608 (copy-file pngfile tofile 'replace)
16609 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16610 (delete-file (concat texfilebase e)))
16611 pngfile))))
16613 ;;; Key bindings
16615 ;; - Bindings in Org-mode map are currently
16616 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
16617 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
16618 ;; e (?) useful from outline-mode
16619 ;; i k @ expendable from outline-mode
16620 ;; 0123456789 % & ()_{} " ` free
16622 ;; Make `C-c C-x' a prefix key
16623 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
16625 ;; TAB key with modifiers
16626 (define-key org-mode-map "\C-i" 'org-cycle)
16627 (define-key org-mode-map [(tab)] 'org-cycle)
16628 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
16629 (define-key org-mode-map [(meta tab)] 'org-complete)
16630 (define-key org-mode-map "\M-\C-i" 'org-complete)
16631 ;; The following line is necessary under Suse GNU/Linux
16632 (unless (featurep 'xemacs)
16633 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
16634 (define-key org-mode-map [(shift tab)] 'org-shifttab)
16636 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
16637 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16638 (define-key org-mode-map [(meta return)] 'org-meta-return)
16640 ;; Cursor keys with modifiers
16641 (define-key org-mode-map [(meta left)] 'org-metaleft)
16642 (define-key org-mode-map [(meta right)] 'org-metaright)
16643 (define-key org-mode-map [(meta up)] 'org-metaup)
16644 (define-key org-mode-map [(meta down)] 'org-metadown)
16646 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16647 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
16648 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
16649 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
16651 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
16652 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
16653 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
16654 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
16656 ;; Extra keys for tty access. We only set them when really needed
16657 ;; because otherwise the menus don't show the simple keys
16659 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16660 (not window-system))
16661 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16662 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16663 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
16664 (define-key org-mode-map [?\e (return)] 'org-meta-return)
16665 (define-key org-mode-map [?\e (left)] 'org-metaleft)
16666 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
16667 (define-key org-mode-map [?\e (right)] 'org-metaright)
16668 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
16669 (define-key org-mode-map [?\e (up)] 'org-metaup)
16670 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
16671 (define-key org-mode-map [?\e (down)] 'org-metadown)
16672 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
16673 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16674 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16675 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16676 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16677 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
16678 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
16679 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
16680 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
16682 ;; All the other keys
16684 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16685 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
16686 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
16687 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
16688 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
16689 (define-key org-mode-map "\C-c\C-j" 'org-goto)
16690 (define-key org-mode-map "\C-c\C-t" 'org-todo)
16691 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
16692 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
16693 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
16694 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
16695 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
16696 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
16697 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
16698 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
16699 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
16700 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
16701 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
16702 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
16703 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
16704 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
16705 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16706 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16707 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16708 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16709 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
16710 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
16711 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16712 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
16713 (define-key org-mode-map "\C-c]" 'org-remove-file)
16714 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
16715 (define-key org-mode-map "\C-c^" 'org-sort)
16716 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16717 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
16718 (define-key org-mode-map "\C-m" 'org-return)
16719 (define-key org-mode-map "\C-c?" 'org-table-current-column)
16720 (define-key org-mode-map "\C-c " 'org-table-blank-field)
16721 (define-key org-mode-map "\C-c+" 'org-table-sum)
16722 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
16723 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
16724 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
16725 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16726 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
16727 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16728 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
16729 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
16730 (define-key org-mode-map "\C-c\C-e" 'org-export)
16731 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16733 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
16734 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16735 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16736 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16738 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16739 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16740 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16741 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16742 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16743 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16744 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16745 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16746 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16748 (when (featurep 'xemacs)
16749 (define-key org-mode-map 'button3 'popup-mode-menu))
16751 (defsubst org-table-p () (org-at-table-p))
16753 (defun org-self-insert-command (N)
16754 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16755 If the cursor is in a table looking at whitespace, the whitespace is
16756 overwritten, and the table is not marked as requiring realignment."
16757 (interactive "p")
16758 (if (and (org-table-p)
16759 (progn
16760 ;; check if we blank the field, and if that triggers align
16761 (and org-table-auto-blank-field
16762 (member last-command
16763 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
16764 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16765 ;; got extra space, this field does not determine column width
16766 (let (org-table-may-need-update) (org-table-blank-field))
16767 ;; no extra space, this field may determine column width
16768 (org-table-blank-field)))
16770 (eq N 1)
16771 (looking-at "[^|\n]* |"))
16772 (let (org-table-may-need-update)
16773 (goto-char (1- (match-end 0)))
16774 (delete-backward-char 1)
16775 (goto-char (match-beginning 0))
16776 (self-insert-command N))
16777 (setq org-table-may-need-update t)
16778 (self-insert-command N)))
16780 (defun org-delete-backward-char (N)
16781 "Like `delete-backward-char', insert whitespace at field end in tables.
16782 When deleting backwards, in tables this function will insert whitespace in
16783 front of the next \"|\" separator, to keep the table aligned. The table will
16784 still be marked for re-alignment if the field did fill the entire column,
16785 because, in this case the deletion might narrow the column."
16786 (interactive "p")
16787 (if (and (org-table-p)
16788 (eq N 1)
16789 (string-match "|" (buffer-substring (point-at-bol) (point)))
16790 (looking-at ".*?|"))
16791 (let ((pos (point))
16792 (noalign (looking-at "[^|\n\r]* |"))
16793 (c org-table-may-need-update))
16794 (backward-delete-char N)
16795 (skip-chars-forward "^|")
16796 (insert " ")
16797 (goto-char (1- pos))
16798 ;; noalign: if there were two spaces at the end, this field
16799 ;; does not determine the width of the column.
16800 (if noalign (setq org-table-may-need-update c)))
16801 (backward-delete-char N)))
16803 (defun org-delete-char (N)
16804 "Like `delete-char', but insert whitespace at field end in tables.
16805 When deleting characters, in tables this function will insert whitespace in
16806 front of the next \"|\" separator, to keep the table aligned. The table will
16807 still be marked for re-alignment if the field did fill the entire column,
16808 because, in this case the deletion might narrow the column."
16809 (interactive "p")
16810 (if (and (org-table-p)
16811 (not (bolp))
16812 (not (= (char-after) ?|))
16813 (eq N 1))
16814 (if (looking-at ".*?|")
16815 (let ((pos (point))
16816 (noalign (looking-at "[^|\n\r]* |"))
16817 (c org-table-may-need-update))
16818 (replace-match (concat
16819 (substring (match-string 0) 1 -1)
16820 " |"))
16821 (goto-char pos)
16822 ;; noalign: if there were two spaces at the end, this field
16823 ;; does not determine the width of the column.
16824 (if noalign (setq org-table-may-need-update c)))
16825 (delete-char N))
16826 (delete-char N)))
16828 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16829 (put 'org-self-insert-command 'delete-selection t)
16830 (put 'orgtbl-self-insert-command 'delete-selection t)
16831 (put 'org-delete-char 'delete-selection 'supersede)
16832 (put 'org-delete-backward-char 'delete-selection 'supersede)
16834 ;; How to do this: Measure non-white length of current string
16835 ;; If equal to column width, we should realign.
16837 (defun org-remap (map &rest commands)
16838 "In MAP, remap the functions given in COMMANDS.
16839 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16840 (let (new old)
16841 (while commands
16842 (setq old (pop commands) new (pop commands))
16843 (if (fboundp 'command-remapping)
16844 (define-key map (vector 'remap old) new)
16845 (substitute-key-definition old new map global-map)))))
16847 (when (eq org-enable-table-editor 'optimized)
16848 ;; If the user wants maximum table support, we need to hijack
16849 ;; some standard editing functions
16850 (org-remap org-mode-map
16851 'self-insert-command 'org-self-insert-command
16852 'delete-char 'org-delete-char
16853 'delete-backward-char 'org-delete-backward-char)
16854 (define-key org-mode-map "|" 'org-force-self-insert))
16856 (defun org-shiftcursor-error ()
16857 "Throw an error because Shift-Cursor command was applied in wrong context."
16858 (error "This command is active in special context like tables, headlines or timestamps"))
16860 (defun org-shifttab (&optional arg)
16861 "Global visibility cycling or move to previous table field.
16862 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16863 on context.
16864 See the individual commands for more information."
16865 (interactive "P")
16866 (cond
16867 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16868 (t (call-interactively 'org-global-cycle))))
16870 (defun org-shiftmetaleft ()
16871 "Promote subtree or delete table column.
16872 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
16873 See the individual commands for more information."
16874 (interactive)
16875 (cond
16876 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16877 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16878 ((org-at-item-p) (call-interactively 'org-outdent-item))
16879 (t (org-shiftcursor-error))))
16881 (defun org-shiftmetaright ()
16882 "Demote subtree or insert table column.
16883 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
16884 See the individual commands for more information."
16885 (interactive)
16886 (cond
16887 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16888 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16889 ((org-at-item-p) (call-interactively 'org-indent-item))
16890 (t (org-shiftcursor-error))))
16892 (defun org-shiftmetaup (&optional arg)
16893 "Move subtree up or kill table row.
16894 Calls `org-move-subtree-up' or `org-table-kill-row' or
16895 `org-move-item-up' depending on context. See the individual commands
16896 for more information."
16897 (interactive "P")
16898 (cond
16899 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16900 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16901 ((org-at-item-p) (call-interactively 'org-move-item-up))
16902 (t (org-shiftcursor-error))))
16903 (defun org-shiftmetadown (&optional arg)
16904 "Move subtree down or insert table row.
16905 Calls `org-move-subtree-down' or `org-table-insert-row' or
16906 `org-move-item-down', depending on context. See the individual
16907 commands for more information."
16908 (interactive "P")
16909 (cond
16910 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16911 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16912 ((org-at-item-p) (call-interactively 'org-move-item-down))
16913 (t (org-shiftcursor-error))))
16915 (defun org-metaleft (&optional arg)
16916 "Promote heading or move table column to left.
16917 Calls `org-do-promote' or `org-table-move-column', depending on context.
16918 With no specific context, calls the Emacs default `backward-word'.
16919 See the individual commands for more information."
16920 (interactive "P")
16921 (cond
16922 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16923 ((or (org-on-heading-p) (org-region-active-p))
16924 (call-interactively 'org-do-promote))
16925 ((org-at-item-p) (call-interactively 'org-outdent-item))
16926 (t (call-interactively 'backward-word))))
16928 (defun org-metaright (&optional arg)
16929 "Demote subtree or move table column to right.
16930 Calls `org-do-demote' or `org-table-move-column', depending on context.
16931 With no specific context, calls the Emacs default `forward-word'.
16932 See the individual commands for more information."
16933 (interactive "P")
16934 (cond
16935 ((org-at-table-p) (call-interactively 'org-table-move-column))
16936 ((or (org-on-heading-p) (org-region-active-p))
16937 (call-interactively 'org-do-demote))
16938 ((org-at-item-p) (call-interactively 'org-indent-item))
16939 (t (call-interactively 'forward-word))))
16941 (defun org-metaup (&optional arg)
16942 "Move subtree up or move table row up.
16943 Calls `org-move-subtree-up' or `org-table-move-row' or
16944 `org-move-item-up', depending on context. See the individual commands
16945 for more information."
16946 (interactive "P")
16947 (cond
16948 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16949 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16950 ((org-at-item-p) (call-interactively 'org-move-item-up))
16951 (t (org-shiftcursor-error))))
16953 (defun org-metadown (&optional arg)
16954 "Move subtree down or move table row down.
16955 Calls `org-move-subtree-down' or `org-table-move-row' or
16956 `org-move-item-down', depending on context. See the individual
16957 commands for more information."
16958 (interactive "P")
16959 (cond
16960 ((org-at-table-p) (call-interactively 'org-table-move-row))
16961 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16962 ((org-at-item-p) (call-interactively 'org-move-item-down))
16963 (t (org-shiftcursor-error))))
16965 (defun org-shiftup (&optional arg)
16966 "Increase item in timestamp or increase priority of current headline.
16967 Calls `org-timestamp-up' or `org-priority-up', depending on context.
16968 See the individual commands for more information."
16969 (interactive "P")
16970 (cond
16971 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
16972 ((org-on-heading-p) (call-interactively 'org-priority-up))
16973 ((org-at-item-p) (call-interactively 'org-previous-item))
16974 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
16976 (defun org-shiftdown (&optional arg)
16977 "Decrease item in timestamp or decrease priority of current headline.
16978 Calls `org-timestamp-down' or `org-priority-down', depending on context.
16979 See the individual commands for more information."
16980 (interactive "P")
16981 (cond
16982 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
16983 ((org-on-heading-p) (call-interactively 'org-priority-down))
16984 (t (call-interactively 'org-next-item))))
16986 (defun org-shiftright ()
16987 "Next TODO keyword or timestamp one day later, depending on context."
16988 (interactive)
16989 (cond
16990 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16991 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
16992 (t (org-shiftcursor-error))))
16994 (defun org-shiftleft ()
16995 "Previous TODO keyword or timestamp one day earlier, depending on context."
16996 (interactive)
16997 (cond
16998 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16999 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
17000 (t (org-shiftcursor-error))))
17002 (defun org-copy-special ()
17003 "Copy region in table or copy current subtree.
17004 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17005 See the individual commands for more information."
17006 (interactive)
17007 (call-interactively
17008 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17010 (defun org-cut-special ()
17011 "Cut region in table or cut current subtree.
17012 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17013 See the individual commands for more information."
17014 (interactive)
17015 (call-interactively
17016 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17018 (defun org-paste-special (arg)
17019 "Paste rectangular region into table, or past subtree relative to level.
17020 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17021 See the individual commands for more information."
17022 (interactive "P")
17023 (if (org-at-table-p)
17024 (org-table-paste-rectangle)
17025 (org-paste-subtree arg)))
17027 (defun org-ctrl-c-ctrl-c (&optional arg)
17028 "Set tags in headline, or update according to changed information at point.
17030 This command does many different things, depending on context:
17032 - If the cursor is in a headline, prompt for tags and insert them
17033 into the current line, aligned to `org-tags-column'. When called
17034 with prefix arg, realign all tags in the current buffer.
17036 - If the cursor is in one of the special #+KEYWORD lines, this
17037 triggers scanning the buffer for these lines and updating the
17038 information.
17040 - If the cursor is inside a table, realign the table. This command
17041 works even if the automatic table editor has been turned off.
17043 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17044 the entire table.
17046 - If the cursor is inside a table created by the table.el package,
17047 activate that table.
17049 - If the current buffer is a remember buffer, close note and file it.
17050 with a prefix argument, file it without further interaction to the default
17051 location.
17053 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17054 links in this buffer.
17056 - If the cursor is on a numbered item in a plain list, renumber the
17057 ordered list."
17058 (interactive "P")
17059 (let ((org-enable-table-editor t))
17060 (cond
17061 ((or org-clock-overlays
17062 org-occur-highlights
17063 org-latex-fragment-image-overlays)
17064 (org-remove-clock-overlays)
17065 (org-remove-occur-highlights)
17066 (org-remove-latex-fragment-image-overlays)
17067 (message "Temporary highlights/overlays removed from current buffer"))
17068 ((and (local-variable-p 'org-finish-function (current-buffer))
17069 (fboundp org-finish-function))
17070 (funcall org-finish-function))
17071 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17072 ((org-on-heading-p) (call-interactively 'org-set-tags))
17073 ((org-at-table.el-p)
17074 (require 'table)
17075 (beginning-of-line 1)
17076 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
17077 (call-interactively 'table-recognize-table))
17078 ((org-at-table-p)
17079 (org-table-maybe-eval-formula)
17080 (if arg
17081 (call-interactively 'org-table-recalculate)
17082 (org-table-maybe-recalculate-line))
17083 (call-interactively 'org-table-align))
17084 ((org-at-item-checkbox-p)
17085 (call-interactively 'org-toggle-checkbox))
17086 ((org-at-item-p)
17087 (call-interactively 'org-renumber-ordered-list))
17088 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
17089 (cond
17090 ((equal (match-string 1) "TBLFM")
17091 ;; Recalculate the table before this line
17092 (save-excursion
17093 (beginning-of-line 1)
17094 (skip-chars-backward " \r\n\t")
17095 (if (org-at-table-p)
17096 (org-call-with-arg 'org-table-recalculate t))))
17098 (call-interactively 'org-mode-restart))))
17099 (t (error "C-c C-c can do nothing useful at this location.")))))
17101 (defun org-mode-restart ()
17102 "Restart Org-mode, to scan again for special lines.
17103 Also updates the keyword regular expressions."
17104 (interactive)
17105 (let ((org-inhibit-startup t)) (org-mode))
17106 (message "Org-mode restarted to refresh keyword and special line setup"))
17108 (defun org-return ()
17109 "Goto next table row or insert a newline.
17110 Calls `org-table-next-row' or `newline', depending on context.
17111 See the individual commands for more information."
17112 (interactive)
17113 (cond
17114 ((org-at-table-p)
17115 (org-table-justify-field-maybe)
17116 (call-interactively 'org-table-next-row))
17117 (t (newline))))
17119 (defun org-meta-return (&optional arg)
17120 "Insert a new heading or wrap a region in a table.
17121 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17122 See the individual commands for more information."
17123 (interactive "P")
17124 (cond
17125 ((org-at-table-p)
17126 (call-interactively 'org-table-wrap-region))
17127 (t (call-interactively 'org-insert-heading))))
17129 ;;; Menu entries
17131 ;; Define the Org-mode menus
17132 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17133 '("Tbl"
17134 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
17135 ["Next Field" org-cycle (org-at-table-p)]
17136 ["Previous Field" org-shifttab (org-at-table-p)]
17137 ["Next Row" org-return (org-at-table-p)]
17138 "--"
17139 ["Blank Field" org-table-blank-field (org-at-table-p)]
17140 ["Edit Field" org-table-edit-field (org-at-table-p)]
17141 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17142 "--"
17143 ("Column"
17144 ["Move Column Left" org-metaleft (org-at-table-p)]
17145 ["Move Column Right" org-metaright (org-at-table-p)]
17146 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17147 ["Insert Column" org-shiftmetaright (org-at-table-p)]
17148 "--"
17149 ["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])
17150 ("Row"
17151 ["Move Row Up" org-metaup (org-at-table-p)]
17152 ["Move Row Down" org-metadown (org-at-table-p)]
17153 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17154 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17155 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17156 "--"
17157 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
17158 ("Rectangle"
17159 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17160 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17161 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17162 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17163 "--"
17164 ("Calculate"
17165 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17166 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17167 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
17168 "--"
17169 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17170 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17171 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17172 "--"
17173 ["Sum Column/Rectangle" org-table-sum
17174 (or (org-at-table-p) (org-region-active-p))]
17175 ["Which Column?" org-table-current-column (org-at-table-p)])
17176 ["Debug Formulas"
17177 (setq org-table-formula-debug (not org-table-formula-debug))
17178 :style toggle :selected org-table-formula-debug]
17179 "--"
17180 ["Create" org-table-create (and (not (org-at-table-p))
17181 org-enable-table-editor)]
17182 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17183 ["Import from File" org-table-import (not (org-at-table-p))]
17184 ["Export to File" org-table-export (org-at-table-p)]
17185 "--"
17186 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17188 (easy-menu-define org-org-menu org-mode-map "Org menu"
17189 '("Org"
17190 ("Show/Hide"
17191 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
17192 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
17193 ["Sparse Tree" org-occur t]
17194 ["Reveal Context" org-reveal t]
17195 ["Show All" show-all t])
17196 "--"
17197 ["New Heading" org-insert-heading t]
17198 ("Navigate Headings"
17199 ["Up" outline-up-heading t]
17200 ["Next" outline-next-visible-heading t]
17201 ["Previous" outline-previous-visible-heading t]
17202 ["Next Same Level" outline-forward-same-level t]
17203 ["Previous Same Level" outline-backward-same-level t]
17204 "--"
17205 ["Jump" org-goto t])
17206 ("Edit Structure"
17207 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17208 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17209 "--"
17210 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17211 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17212 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17213 "--"
17214 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17215 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17216 ["Demote Heading" org-metaright (not (org-at-table-p))]
17217 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17218 "--"
17219 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17220 "--"
17221 ["Convert to odd levels" org-convert-to-odd-levels t]
17222 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17223 ("Archive"
17224 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17225 ["Check and Tag Children" (org-toggle-archive-tag (4))
17226 :active t :keys "C-u C-c C-x C-a"]
17227 ["Sparse trees open ARCHIVE trees"
17228 (setq org-sparse-tree-open-archived-trees
17229 (not org-sparse-tree-open-archived-trees))
17230 :style toggle :selected org-sparse-tree-open-archived-trees]
17231 ["Cycling opens ARCHIVE trees"
17232 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
17233 :style toggle :selected org-cycle-open-archived-trees]
17234 ["Agenda includes ARCHIVE trees"
17235 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
17236 :style toggle :selected (not org-agenda-skip-archived-trees)]
17237 "--"
17238 ["Move Subtree to Archive" org-archive-subtree t]
17239 ["Check and Move Children" (org-archive-subtree '(4))
17240 :active t :keys "C-u C-c $"])
17241 "--"
17242 ("TODO Lists"
17243 ["TODO/DONE/-" org-todo t]
17244 ("Select keyword"
17245 ["Next keyword" org-shiftright (org-on-heading-p)]
17246 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17247 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
17248 ["Show TODO Tree" org-show-todo-tree t]
17249 ["Global TODO list" org-todo-list t]
17250 "--"
17251 ["Set Priority" org-priority t]
17252 ["Priority Up" org-shiftup t]
17253 ["Priority Down" org-shiftdown t]
17254 "--"
17255 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
17256 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
17257 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
17258 ; (or (org-on-heading-p) (org-at-item-p))]
17259 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
17260 ; (or (org-on-heading-p) (org-at-item-p))]
17261 ; ["Update Statistics" org-update-checkbox-count t]
17263 ("Dates and Scheduling"
17264 ["Timestamp" org-time-stamp t]
17265 ["Timestamp (inactive)" org-time-stamp-inactive t]
17266 ("Change Date"
17267 ["1 Day Later" org-shiftright t]
17268 ["1 Day Earlier" org-shiftleft t]
17269 ["1 ... Later" org-shiftup t]
17270 ["1 ... Earlier" org-shiftdown t])
17271 ["Compute Time Range" org-evaluate-time-range t]
17272 ["Schedule Item" org-schedule t]
17273 ["Deadline" org-deadline t]
17274 "--"
17275 ["Custom time format" org-toggle-time-stamp-overlays
17276 :style radio :selected org-display-custom-times]
17277 "--"
17278 ["Goto Calendar" org-goto-calendar t]
17279 ["Date from Calendar" org-date-from-calendar t])
17280 ("Logging work"
17281 ["Clock in" org-clock-in t]
17282 ["Clock out" org-clock-out t]
17283 ["Clock cancel" org-clock-cancel t]
17284 ["Display times" org-clock-display t]
17285 ["Create clock table" org-clock-report t]
17286 "--"
17287 ["Record DONE time"
17288 (progn (setq org-log-done (not org-log-done))
17289 (message "Switching to %s will %s record a timestamp"
17290 org-done-string
17291 (if org-log-done "automatically" "not")))
17292 :style toggle :selected org-log-done])
17293 "--"
17294 ["Agenda Command..." org-agenda t]
17295 ("File List for Agenda")
17296 ("Special views current file"
17297 ["TODO Tree" org-show-todo-tree t]
17298 ["Check Deadlines" org-check-deadlines t]
17299 ["Timeline" org-timeline t]
17300 ["Tags Tree" org-tags-sparse-tree t])
17301 "--"
17302 ("Hyperlinks"
17303 ["Store Link (Global)" org-store-link t]
17304 ["Insert Link" org-insert-link t]
17305 ["Follow Link" org-open-at-point t]
17306 "--"
17307 ["Descriptive Links"
17308 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17309 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
17310 ["Literal Links"
17311 (progn
17312 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17313 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
17314 "--"
17315 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
17316 (save-excursion (goto-char (point-min))
17317 (re-search-forward "<[a-z]+:" nil t))])
17318 "--"
17319 ["Export/Publish..." org-export t]
17320 ("LaTeX"
17321 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17322 :selected org-cdlatex-mode]
17323 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17324 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17325 ["Modify math symbol" org-cdlatex-math-modify
17326 (org-inside-LaTeX-fragment-p)]
17327 ["Export LaTeX fragments as images"
17328 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
17329 :style toggle :selected org-export-with-LaTeX-fragments])
17330 "--"
17331 ("Documentation"
17332 ["Show Version" org-version t]
17333 ["Info Documentation" org-info t])
17334 ("Customize"
17335 ["Browse Org Group" org-customize t]
17336 "--"
17337 ["Expand This Menu" org-create-customize-menu
17338 (fboundp 'customize-menu-create)])
17339 "--"
17340 ["Refresh setup" org-mode-restart t]
17343 (defun org-info (&optional node)
17344 "Read documentation for Org-mode in the info system.
17345 With optional NODE, go directly to that node."
17346 (interactive)
17347 (require 'info)
17348 (Info-goto-node (format "(org)%s" (or node ""))))
17350 (defun org-install-agenda-files-menu ()
17351 (let ((bl (buffer-list)))
17352 (save-excursion
17353 (while bl
17354 (set-buffer (pop bl))
17355 (if (org-mode-p) (setq bl nil)))
17356 (when (org-mode-p)
17357 (easy-menu-change
17358 '("Org") "File List for Agenda"
17359 (append
17360 (list
17361 ["Edit File List" (org-edit-agenda-file-list) t]
17362 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17363 ["Remove Current File from List" org-remove-file t]
17364 ["Cycle through agenda files" org-cycle-agenda-files t]
17365 "--")
17366 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17368 ;;; Documentation
17370 (defun org-customize ()
17371 "Call the customize function with org as argument."
17372 (interactive)
17373 (customize-browse 'org))
17375 (defun org-create-customize-menu ()
17376 "Create a full customization menu for Org-mode, insert it into the menu."
17377 (interactive)
17378 (if (fboundp 'customize-menu-create)
17379 (progn
17380 (easy-menu-change
17381 '("Org") "Customize"
17382 `(["Browse Org group" org-customize t]
17383 "--"
17384 ,(customize-menu-create 'org)
17385 ["Set" Custom-set t]
17386 ["Save" Custom-save t]
17387 ["Reset to Current" Custom-reset-current t]
17388 ["Reset to Saved" Custom-reset-saved t]
17389 ["Reset to Standard Settings" Custom-reset-standard t]))
17390 (message "\"Org\"-menu now contains full customization menu"))
17391 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17393 ;;; Miscellaneous stuff
17395 (defun org-context ()
17396 "Return a list of contexts of the current cursor position.
17397 If several contexts apply, all are returned.
17398 Each context entry is a list with a symbol naming the context, and
17399 two positions indicating start and end of the context. Possible
17400 contexts are:
17402 :headline anywhere in a headline
17403 :headline-stars on the leading stars in a headline
17404 :todo-keyword on a TODO keyword (including DONE) in a headline
17405 :tags on the TAGS in a headline
17406 :priority on the priority cookie in a headline
17407 :item on the first line of a plain list item
17408 :item-bullet on the bullet/number of a plain list item
17409 :checkbox on the checkbox in a plain list item
17410 :table in an org-mode table
17411 :table-special on a special filed in a table
17412 :table-table in a table.el table
17413 :link on a hyperline
17414 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17415 :target on a <<target>>
17416 :radio-target on a <<<radio-target>>>
17417 :latex-fragment on a LaTeX fragment
17418 :latex-preview on a LaTeX fragment with overlayed preview image
17420 This function expects the position to be visible because it uses font-lock
17421 faces as a help to recognize the following contexts: :table-special, :link,
17422 and :keyword."
17423 (let* ((f (get-text-property (point) 'face))
17424 (faces (if (listp f) f (list f)))
17425 (p (point)) clist o)
17426 ;; First the large context
17427 (cond
17428 ((org-on-heading-p)
17429 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17430 (when (progn
17431 (beginning-of-line 1)
17432 (looking-at org-todo-line-tags-regexp))
17433 (push (org-point-in-group p 1 :headline-stars) clist)
17434 (push (org-point-in-group p 2 :todo-keyword) clist)
17435 (push (org-point-in-group p 4 :tags) clist))
17436 (goto-char p)
17437 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
17438 (if (looking-at "\\[#[A-Z]\\]")
17439 (push (org-point-in-group p 0 :priority) clist)))
17441 ((org-at-item-p)
17442 (push (org-point-in-group p 2 :item-bullet) clist)
17443 (push (list :item (point-at-bol)
17444 (save-excursion (org-end-of-item) (point)))
17445 clist)
17446 (and (org-at-item-checkbox-p)
17447 (push (org-point-in-group p 0 :checkbox) clist)))
17449 ((org-at-table-p)
17450 (push (list :table (org-table-begin) (org-table-end)) clist)
17451 (if (memq 'org-formula faces)
17452 (push (list :table-special
17453 (previous-single-property-change p 'face)
17454 (next-single-property-change p 'face)) clist)))
17455 ((org-at-table-p 'any)
17456 (push (list :table-table) clist)))
17457 (goto-char p)
17459 ;; Now the small context
17460 (cond
17461 ((org-at-timestamp-p)
17462 (push (org-point-in-group p 0 :timestamp) clist))
17463 ((memq 'org-link faces)
17464 (push (list :link
17465 (previous-single-property-change p 'face)
17466 (next-single-property-change p 'face)) clist))
17467 ((memq 'org-special-keyword faces)
17468 (push (list :keyword
17469 (previous-single-property-change p 'face)
17470 (next-single-property-change p 'face)) clist))
17471 ((org-on-target-p)
17472 (push (org-point-in-group p 0 :target) clist)
17473 (goto-char (1- (match-beginning 0)))
17474 (if (looking-at org-radio-target-regexp)
17475 (push (org-point-in-group p 0 :radio-target) clist))
17476 (goto-char p))
17477 ((setq o (car (delq nil
17478 (mapcar
17479 (lambda (x)
17480 (if (memq x org-latex-fragment-image-overlays) x))
17481 (org-overlays-at (point))))))
17482 (push (list :latex-fragment
17483 (org-overlay-start o) (org-overlay-end o)) clist)
17484 (push (list :latex-preview
17485 (org-overlay-start o) (org-overlay-end o)) clist))
17486 ((org-inside-LaTeX-fragment-p)
17487 ;; FIXME: positions wrong.
17488 (push (list :latex-fragment (point) (point)) clist)))
17490 (setq clist (nreverse (delq nil clist)))
17491 clist))
17493 (defun org-point-in-group (point group &optional context)
17494 "Check if POINT is in match-group GROUP.
17495 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17496 match. If the match group does ot exist or point is not inside it,
17497 return nil."
17498 (and (match-beginning group)
17499 (>= point (match-beginning group))
17500 (<= point (match-end group))
17501 (if context
17502 (list context (match-beginning group) (match-end group))
17503 t)))
17505 (defun org-move-line-down (arg)
17506 "Move the current line down. With prefix argument, move it past ARG lines."
17507 (interactive "p")
17508 (let ((col (current-column))
17509 beg end pos)
17510 (beginning-of-line 1) (setq beg (point))
17511 (beginning-of-line 2) (setq end (point))
17512 (beginning-of-line (+ 1 arg))
17513 (setq pos (move-marker (make-marker) (point)))
17514 (insert (delete-and-extract-region beg end))
17515 (goto-char pos)
17516 (move-to-column col)))
17518 (defun org-move-line-up (arg)
17519 "Move the current line up. With prefix argument, move it past ARG lines."
17520 (interactive "p")
17521 (let ((col (current-column))
17522 beg end pos)
17523 (beginning-of-line 1) (setq beg (point))
17524 (beginning-of-line 2) (setq end (point))
17525 (beginning-of-line (- arg))
17526 (setq pos (move-marker (make-marker) (point)))
17527 (insert (delete-and-extract-region beg end))
17528 (goto-char pos)
17529 (move-to-column col)))
17531 (defun org-replace-escapes (string table)
17532 ;; FIXME: document and make safer
17533 (let (e)
17534 (while (setq e (pop table))
17535 (while (string-match (car e) string)
17536 (setq string (replace-match (cdr e) t t string))))
17537 string))
17539 ;; Paragraph filling stuff.
17540 ;; We want this to be just right, so use the full arsenal.
17542 (defun org-set-autofill-regexps ()
17543 (interactive)
17544 ;; In the paragraph separator we include headlines, because filling
17545 ;; text in a line directly attached to a headline would otherwise
17546 ;; fill the headline as well.
17547 (org-set-local 'comment-start-skip "^#+[ \t]*")
17548 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
17549 ;; The paragraph starter includes hand-formatted lists.
17550 (org-set-local 'paragraph-start
17551 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
17552 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17553 ;; But only if the user has not turned off tables or fixed-width regions
17554 (org-set-local
17555 'auto-fill-inhibit-regexp
17556 (concat "\\*\\|#\\+"
17557 "\\|[ \t]*" org-keyword-time-regexp
17558 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17559 (concat
17560 "\\|[ \t]*["
17561 (if org-enable-table-editor "|" "")
17562 (if org-enable-fixed-width-editor ":" "")
17563 "]"))))
17564 ;; We use our own fill-paragraph function, to make sure that tables
17565 ;; and fixed-width regions are not wrapped. That function will pass
17566 ;; through to `fill-paragraph' when appropriate.
17567 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17568 ; Adaptive filling: To get full control, first make sure that
17569 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17570 (org-set-local 'adaptive-fill-regexp "\000")
17571 (org-set-local 'adaptive-fill-function
17572 'org-adaptive-fill-function))
17574 (defun org-fill-paragraph (&optional justify)
17575 "Re-align a table, pass through to fill-paragraph if no table."
17576 (let ((table-p (org-at-table-p))
17577 (table.el-p (org-at-table.el-p)))
17578 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
17579 (table.el-p t) ; skip table.el tables
17580 (table-p (org-table-align) t) ; align org-mode tables
17581 (t nil)))) ; call paragraph-fill
17583 ;; For reference, this is the default value of adaptive-fill-regexp
17584 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17586 (defun org-adaptive-fill-function ()
17587 "Return a fill prefix for org-mode files.
17588 In particular, this makes sure hanging paragraphs for hand-formatted lists
17589 work correctly."
17590 ;;FIXME (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
17591 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?\|#\\+[ \t]+")
17592 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
17594 ;; Functions needed for Emacs/XEmacs region compatibility
17596 (defun org-add-hook (hook function &optional append local)
17597 "Add-hook, compatible with both Emacsen."
17598 (if (and local (featurep 'xemacs))
17599 (add-local-hook hook function append)
17600 (add-hook hook function append local)))
17602 (defun org-region-active-p ()
17603 "Is `transient-mark-mode' on and the region active?
17604 Works on both Emacs and XEmacs."
17605 (if org-ignore-region
17607 (if (featurep 'xemacs)
17608 (and zmacs-regions (region-active-p))
17609 (and transient-mark-mode mark-active))))
17611 (defun org-add-to-invisibility-spec (arg)
17612 "Add elements to `buffer-invisibility-spec'.
17613 See documentation for `buffer-invisibility-spec' for the kind of elements
17614 that can be added."
17615 (cond
17616 ((fboundp 'add-to-invisibility-spec)
17617 (add-to-invisibility-spec arg))
17618 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
17619 (setq buffer-invisibility-spec (list arg)))
17621 (setq buffer-invisibility-spec
17622 (cons arg buffer-invisibility-spec)))))
17624 (defun org-remove-from-invisibility-spec (arg)
17625 "Remove elements from `buffer-invisibility-spec'."
17626 (if (fboundp 'remove-from-invisibility-spec)
17627 (remove-from-invisibility-spec arg)
17628 (if (consp buffer-invisibility-spec)
17629 (setq buffer-invisibility-spec
17630 (delete arg buffer-invisibility-spec)))))
17632 (defun org-in-invisibility-spec-p (arg)
17633 "Is ARG a member of `buffer-invisibility-spec'?"
17634 (if (consp buffer-invisibility-spec)
17635 (member arg buffer-invisibility-spec)
17636 nil))
17638 (defun org-image-file-name-regexp ()
17639 "Return regexp matching the file names of images."
17640 (if (fboundp 'image-file-name-regexp)
17641 (image-file-name-regexp)
17642 (let ((image-file-name-extensions
17643 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17644 "xbm" "xpm" "pbm" "pgm" "ppm")))
17645 (concat "\\."
17646 (regexp-opt (nconc (mapcar 'upcase
17647 image-file-name-extensions)
17648 image-file-name-extensions)
17650 "\\'"))))
17652 ;; Functions extending outline functionality
17654 ;; C-a should go to the beginning of a *visible* line, also in the
17655 ;; new outline.el. I guess this should be patched into Emacs?
17656 (defun org-beginning-of-line ()
17657 "Go to the beginning of the current line. If that is invisible, continue
17658 to a visible line beginning. This makes the function of C-a more intuitive."
17659 (interactive)
17660 (beginning-of-line 1)
17661 (if (bobp)
17663 (backward-char 1)
17664 (if (org-invisible-p)
17665 (while (and (not (bobp)) (org-invisible-p))
17666 (backward-char 1)
17667 (beginning-of-line 1))
17668 (forward-char 1))))
17670 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17672 (defun org-invisible-p ()
17673 "Check if point is at a character currently not visible."
17674 ;; Early versions of noutline don't have `outline-invisible-p'.
17675 (if (fboundp 'outline-invisible-p)
17676 (outline-invisible-p)
17677 (get-char-property (point) 'invisible)))
17679 (defun org-invisible-p2 ()
17680 "Check if point is at a character currently not visible."
17681 (save-excursion
17682 (if (and (eolp) (not (bobp))) (backward-char 1))
17683 ;; Early versions of noutline don't have `outline-invisible-p'.
17684 (if (fboundp 'outline-invisible-p)
17685 (outline-invisible-p)
17686 (get-char-property (point) 'invisible))))
17688 (defalias 'org-back-to-heading 'outline-back-to-heading)
17689 (defalias 'org-on-heading-p 'outline-on-heading-p)
17691 (defun org-on-target-p ()
17692 (let ((pos (point)))
17693 (save-excursion
17694 (skip-chars-forward "<")
17695 (and (re-search-backward "<<" nil t)
17696 (or (looking-at org-radio-target-regexp)
17697 (looking-at org-target-regexp))
17698 (<= (match-beginning 0) pos)
17699 (>= (1+ (match-end 0)) pos)))))
17701 (defun org-up-heading-all (arg)
17702 "Move to the heading line of which the present line is a subheading.
17703 This function considers both visible and invisible heading lines.
17704 With argument, move up ARG levels."
17705 (if (fboundp 'outline-up-heading-all)
17706 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17707 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17709 (defun org-goto-sibling (&optional previous)
17710 "Goto the next sibling, even if it is invisible.
17711 When PREVIOUS is set, go to the previous sibling instead. Returns t
17712 when a sibling was found. When none is found, return nil and don't
17713 move point."
17714 (let ((fun (if previous 're-search-backward 're-search-forward))
17715 (pos (point))
17716 (re (concat "^" outline-regexp))
17717 level l)
17718 (org-back-to-heading t)
17719 (setq level (funcall outline-level))
17720 (catch 'exit
17721 (or previous (forward-char 1))
17722 (while (funcall fun re nil t)
17723 (setq l (funcall outline-level))
17724 (when (< l level) (goto-char pos) (throw 'exit nil))
17725 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17726 (goto-char pos)
17727 nil)))
17729 (defun org-show-hidden-entry ()
17730 "Show an entry where even the heading is hidden."
17731 (save-excursion
17732 (org-show-entry)))
17734 (defun org-flag-heading (flag &optional entry)
17735 "Flag the current heading. FLAG non-nil means make invisible.
17736 When ENTRY is non-nil, show the entire entry."
17737 (save-excursion
17738 (org-back-to-heading t)
17739 ;; Check if we should show the entire entry
17740 (if entry
17741 (progn
17742 (org-show-entry)
17743 (save-excursion
17744 (and (outline-next-heading)
17745 (org-flag-heading nil))))
17746 (outline-flag-region (max 1 (1- (point)))
17747 (save-excursion (outline-end-of-heading) (point))
17748 flag))))
17750 (defun org-end-of-subtree (&optional invisible-OK)
17751 ;; This is an exact copy of the original function, but it uses
17752 ;; `org-back-to-heading', to make it work also in invisible
17753 ;; trees. And is uses an invisible-OK argument.
17754 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17755 (org-back-to-heading invisible-OK)
17756 (let ((first t)
17757 (level (funcall outline-level)))
17758 (while (and (not (eobp))
17759 (or first (> (funcall outline-level) level)))
17760 (setq first nil)
17761 (outline-next-heading))
17762 (if (memq (preceding-char) '(?\n ?\^M))
17763 (progn
17764 ;; Go to end of line before heading
17765 (forward-char -1)
17766 (if (memq (preceding-char) '(?\n ?\^M))
17767 ;; leave blank line before heading
17768 (forward-char -1)))))
17769 (point))
17771 (defun org-show-subtree ()
17772 "Show everything after this heading at deeper levels."
17773 (outline-flag-region
17774 (point)
17775 (save-excursion
17776 (outline-end-of-subtree) (outline-next-heading) (point))
17777 nil))
17779 (defun org-show-entry ()
17780 "Show the body directly following this heading.
17781 Show the heading too, if it is currently invisible."
17782 (interactive)
17783 (save-excursion
17784 (org-back-to-heading t)
17785 (outline-flag-region
17786 (max 1 (1- (point)))
17787 (save-excursion
17788 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
17789 (or (match-beginning 1) (point-max)))
17790 nil)))
17792 (defun org-make-options-regexp (kwds)
17793 "Make a regular expression for keyword lines."
17794 (concat
17796 "#?[ \t]*\\+\\("
17797 (mapconcat 'regexp-quote kwds "\\|")
17798 "\\):[ \t]*"
17799 "\\(.+\\)"))
17801 ;; Make `bookmark-jump' show the jump location if it was hidden.
17802 (eval-after-load "bookmark"
17803 '(if (boundp 'bookmark-after-jump-hook)
17804 ;; We can use the hook
17805 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17806 ;; Hook not available, use advice
17807 (defadvice bookmark-jump (after org-make-visible activate)
17808 "Make the position visible."
17809 (org-bookmark-jump-unhide))))
17811 (defun org-bookmark-jump-unhide ()
17812 "Unhide the current position, to show the bookmark location."
17813 (and (org-mode-p)
17814 (or (org-invisible-p)
17815 (save-excursion (goto-char (max (point-min) (1- (point))))
17816 (org-invisible-p)))
17817 (org-show-context 'bookmark-jump)))
17819 ;; Make session.el ignore our circular variable
17820 (eval-after-load "session"
17821 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17823 ;;; Experimental code
17825 ;;; Finish up
17827 (provide 'org)
17829 (run-hooks 'org-load-hook)
17831 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17832 ;;; org.el ends here