Release 5.16a
[org-mode/org-tableheadings.git] / org.el
blobcc7eb612b9f2c2a28d0f426a3cce7cdbcd7521e2
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.16a
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 3, 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://orgmode.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 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.16a"
88 "The version number of the file org.el.")
89 (defun org-version ()
90 (interactive)
91 (message "Org-mode version %s" org-version))
93 ;;; Compatibility constants
94 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
95 (defconst org-format-transports-properties-p
96 (let ((x "a"))
97 (add-text-properties 0 1 '(test t) x)
98 (get-text-property 0 'test (format "%s" x)))
99 "Does format transport text properties?")
101 (defmacro org-unmodified (&rest body)
102 "Execute body without changing buffer-modified-p."
103 `(set-buffer-modified-p
104 (prog1 (buffer-modified-p) ,@body)))
106 (defmacro org-re (s)
107 "Replace posix classes in regular expression."
108 (if (featurep 'xemacs)
109 (let ((ss s))
110 (save-match-data
111 (while (string-match "\\[:alnum:\\]" ss)
112 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
113 (while (string-match "\\[:alpha:\\]" ss)
114 (setq ss (replace-match "a-zA-Z" t t ss)))
115 ss))
118 (defmacro org-preserve-lc (&rest body)
119 `(let ((_line (org-current-line))
120 (_col (current-column)))
121 (unwind-protect
122 (progn ,@body)
123 (goto-line _line)
124 (move-to-column _col))))
126 (defmacro org-without-partial-completion (&rest body)
127 `(let ((pc-mode (and (boundp 'partial-completion-mode)
128 partial-completion-mode)))
129 (unwind-protect
130 (progn
131 (if pc-mode (partial-completion-mode -1))
132 ,@body)
133 (if pc-mode (partial-completion-mode 1)))))
135 ;;; The custom variables
137 (defgroup org nil
138 "Outline-based notes management and organizer."
139 :tag "Org"
140 :group 'outlines
141 :group 'hypermedia
142 :group 'calendar)
144 ;; FIXME: Needs a separate group...
145 (defcustom org-completion-fallback-command 'hippie-expand
146 "The expansion command called by \\[org-complete] in normal context.
147 Normal means, no org-mode-specific context."
148 :group 'org
149 :type 'function)
151 (defgroup org-startup nil
152 "Options concerning startup of Org-mode."
153 :tag "Org Startup"
154 :group 'org)
156 (defcustom org-startup-folded t
157 "Non-nil means, entering Org-mode will switch to OVERVIEW.
158 This can also be configured on a per-file basis by adding one of
159 the following lines anywhere in the buffer:
161 #+STARTUP: fold
162 #+STARTUP: nofold
163 #+STARTUP: content"
164 :group 'org-startup
165 :type '(choice
166 (const :tag "nofold: show all" nil)
167 (const :tag "fold: overview" t)
168 (const :tag "content: all headlines" content)))
170 (defcustom org-startup-truncated t
171 "Non-nil means, entering Org-mode will set `truncate-lines'.
172 This is useful since some lines containing links can be very long and
173 uninteresting. Also tables look terrible when wrapped."
174 :group 'org-startup
175 :type 'boolean)
177 (defcustom org-startup-align-all-tables nil
178 "Non-nil means, align all tables when visiting a file.
179 This is useful when the column width in tables is forced with <N> cookies
180 in table fields. Such tables will look correct only after the first re-align.
181 This can also be configured on a per-file basis by adding one of
182 the following lines anywhere in the buffer:
183 #+STARTUP: align
184 #+STARTUP: noalign"
185 :group 'org-startup
186 :type 'boolean)
188 (defcustom org-insert-mode-line-in-empty-file nil
189 "Non-nil means insert the first line setting Org-mode in empty files.
190 When the function `org-mode' is called interactively in an empty file, this
191 normally means that the file name does not automatically trigger Org-mode.
192 To ensure that the file will always be in Org-mode in the future, a
193 line enforcing Org-mode will be inserted into the buffer, if this option
194 has been set."
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-replace-disputed-keys nil
199 "Non-nil means use alternative key bindings for some keys.
200 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
201 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
202 If you want to use Org-mode together with one of these other modes,
203 or more generally if you would like to move some Org-mode commands to
204 other keys, set this variable and configure the keys with the variable
205 `org-disputed-keys'.
207 This option is only relevant at load-time of Org-mode, and must be set
208 *before* org.el is loaded. Changing it requires a restart of Emacs to
209 become effective."
210 :group 'org-startup
211 :type 'boolean)
213 (if (fboundp 'defvaralias)
214 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
216 (defcustom org-disputed-keys
217 '(([(shift up)] . [(meta p)])
218 ([(shift down)] . [(meta n)])
219 ([(shift left)] . [(meta -)])
220 ([(shift right)] . [(meta +)])
221 ([(control shift right)] . [(meta shift +)])
222 ([(control shift left)] . [(meta shift -)]))
223 "Keys for which Org-mode and other modes compete.
224 This is an alist, cars are the default keys, second element specifies
225 the alternative to use when `org-replace-disputed-keys' is t.
227 Keys can be specified in any syntax supported by `define-key'.
228 The value of this option takes effect only at Org-mode's startup,
229 therefore you'll have to restart Emacs to apply it after changing."
230 :group 'org-startup
231 :type 'alist)
233 (defun org-key (key)
234 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
235 Or return the original if not disputed."
236 (if org-replace-disputed-keys
237 (let* ((nkey (key-description key))
238 (x (org-find-if (lambda (x)
239 (equal (key-description (car x)) nkey))
240 org-disputed-keys)))
241 (if x (cdr x) key))
242 key))
244 (defun org-find-if (predicate seq)
245 (catch 'exit
246 (while seq
247 (if (funcall predicate (car seq))
248 (throw 'exit (car seq))
249 (pop seq)))))
251 (defun org-defkey (keymap key def)
252 "Define a key, possibly translated, as returned by `org-key'."
253 (define-key keymap (org-key key) def))
255 (defcustom org-ellipsis nil
256 "The ellipsis to use in the Org-mode outline.
257 When nil, just use the standard three dots. When a string, use that instead,
258 When a face, use the standart 3 dots, but with the specified face.
259 The change affects only Org-mode (which will then use its own display table).
260 Changing this requires executing `M-x org-mode' in a buffer to become
261 effective."
262 :group 'org-startup
263 :type '(choice (const :tag "Default" nil)
264 (face :tag "Face" :value org-warning)
265 (string :tag "String" :value "...#")))
267 (defvar org-display-table nil
268 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
270 (defgroup org-keywords nil
271 "Keywords in Org-mode."
272 :tag "Org Keywords"
273 :group 'org)
275 (defcustom org-deadline-string "DEADLINE:"
276 "String to mark deadline entries.
277 A deadline is this string, followed by a time stamp. Should be a word,
278 terminated by a colon. You can insert a schedule keyword and
279 a timestamp with \\[org-deadline].
280 Changes become only effective after restarting Emacs."
281 :group 'org-keywords
282 :type 'string)
284 (defcustom org-scheduled-string "SCHEDULED:"
285 "String to mark scheduled TODO entries.
286 A schedule is this string, followed by a time stamp. Should be a word,
287 terminated by a colon. You can insert a schedule keyword and
288 a timestamp with \\[org-schedule].
289 Changes become only effective after restarting Emacs."
290 :group 'org-keywords
291 :type 'string)
293 (defcustom org-closed-string "CLOSED:"
294 "String used as the prefix for timestamps logging closing a TODO entry."
295 :group 'org-keywords
296 :type 'string)
298 (defcustom org-clock-string "CLOCK:"
299 "String used as prefix for timestamps clocking work hours on an item."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-comment-string "COMMENT"
304 "Entries starting with this keyword will never be exported.
305 An entry can be toggled between COMMENT and normal with
306 \\[org-toggle-comment].
307 Changes become only effective after restarting Emacs."
308 :group 'org-keywords
309 :type 'string)
311 (defcustom org-quote-string "QUOTE"
312 "Entries starting with this keyword will be exported in fixed-width font.
313 Quoting applies only to the text in the entry following the headline, and does
314 not extend beyond the next headline, even if that is lower level.
315 An entry can be toggled between QUOTE and normal with
316 \\[org-toggle-fixed-width-section]."
317 :group 'org-keywords
318 :type 'string)
320 (defconst org-repeat-re
321 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
322 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
323 "Regular expression for specifying repeated events.
324 After a match, group 1 contains the repeat expression.")
326 (defgroup org-structure nil
327 "Options concerning the general structure of Org-mode files."
328 :tag "Org Structure"
329 :group 'org)
331 (defgroup org-reveal-location nil
332 "Options about how to make context of a location visible."
333 :tag "Org Reveal Location"
334 :group 'org-structure)
336 (defconst org-context-choice
337 '(choice
338 (const :tag "Always" t)
339 (const :tag "Never" nil)
340 (repeat :greedy t :tag "Individual contexts"
341 (cons
342 (choice :tag "Context"
343 (const agenda)
344 (const org-goto)
345 (const occur-tree)
346 (const tags-tree)
347 (const link-search)
348 (const mark-goto)
349 (const bookmark-jump)
350 (const isearch)
351 (const default))
352 (boolean))))
353 "Contexts for the reveal options.")
355 (defcustom org-show-hierarchy-above '((default . t))
356 "Non-nil means, show full hierarchy when revealing a location.
357 Org-mode often shows locations in an org-mode file which might have
358 been invisible before. When this is set, the hierarchy of headings
359 above the exposed location is shown.
360 Turning this off for example for sparse trees makes them very compact.
361 Instead of t, this can also be an alist specifying this option for different
362 contexts. Valid contexts are
363 agenda when exposing an entry from the agenda
364 org-goto when using the command `org-goto' on key C-c C-j
365 occur-tree when using the command `org-occur' on key C-c /
366 tags-tree when constructing a sparse tree based on tags matches
367 link-search when exposing search matches associated with a link
368 mark-goto when exposing the jump goal of a mark
369 bookmark-jump when exposing a bookmark location
370 isearch when exiting from an incremental search
371 default default for all contexts not set explicitly"
372 :group 'org-reveal-location
373 :type org-context-choice)
375 (defcustom org-show-following-heading '((default . nil))
376 "Non-nil means, show following heading when revealing a location.
377 Org-mode often shows locations in an org-mode file which might have
378 been invisible before. When this is set, the heading following the
379 match is shown.
380 Turning this off for example for sparse trees makes them very compact,
381 but makes it harder to edit the location of the match. In such a case,
382 use the command \\[org-reveal] to show more context.
383 Instead of t, this can also be an alist specifying this option for different
384 contexts. See `org-show-hierarchy-above' for valid contexts."
385 :group 'org-reveal-location
386 :type org-context-choice)
388 (defcustom org-show-siblings '((default . nil) (isearch t))
389 "Non-nil means, show all sibling heading when revealing a location.
390 Org-mode often shows locations in an org-mode file which might have
391 been invisible before. When this is set, the sibling of the current entry
392 heading are all made visible. If `org-show-hierarchy-above' is t,
393 the same happens on each level of the hierarchy above the current entry.
395 By default this is on for the isearch context, off for all other contexts.
396 Turning this off for example for sparse trees makes them very compact,
397 but makes it harder to edit the location of the match. In such a case,
398 use the command \\[org-reveal] to show more context.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. See `org-show-hierarchy-above' for valid contexts."
401 :group 'org-reveal-location
402 :type org-context-choice)
404 (defcustom org-show-entry-below '((default . nil))
405 "Non-nil means, show the entry below a headline when revealing a location.
406 Org-mode often shows locations in an org-mode file which might have
407 been invisible before. When this is set, the text below the headline that is
408 exposed is also shown.
410 By default this is off for all contexts.
411 Instead of t, this can also be an alist specifying this option for different
412 contexts. See `org-show-hierarchy-above' for valid contexts."
413 :group 'org-reveal-location
414 :type org-context-choice)
416 (defgroup org-cycle nil
417 "Options concerning visibility cycling in Org-mode."
418 :tag "Org Cycle"
419 :group 'org-structure)
421 (defcustom org-drawers '("PROPERTIES" "CLOCK")
422 "Names of drawers. Drawers are not opened by cycling on the headline above.
423 Drawers only open with a TAB on the drawer line itself. A drawer looks like
424 this:
425 :DRAWERNAME:
426 .....
427 :END:
428 The drawer \"PROPERTIES\" is special for capturing properties through
429 the property API.
431 Drawers can be defined on the per-file basis with a line like:
433 #+DRAWERS: HIDDEN STATE PROPERTIES"
434 :group 'org-structure
435 :type '(repeat (string :tag "Drawer Name")))
437 (defcustom org-cycle-global-at-bob nil
438 "Cycle globally if cursor is at beginning of buffer and not at a headline.
439 This makes it possible to do global cycling without having to use S-TAB or
440 C-u TAB. For this special case to work, the first line of the buffer
441 must not be a headline - it may be empty ot some other text. When used in
442 this way, `org-cycle-hook' is disables temporarily, to make sure the
443 cursor stays at the beginning of the buffer.
444 When this option is nil, don't do anything special at the beginning
445 of the buffer."
446 :group 'org-cycle
447 :type 'boolean)
449 (defcustom org-cycle-emulate-tab t
450 "Where should `org-cycle' emulate TAB.
451 nil Never
452 white Only in completely white lines
453 whitestart Only at the beginning of lines, before the first non-white char.
454 t Everywhere except in headlines
455 exc-hl-bol Everywhere except at the start of a headline
456 If TAB is used in a place where it does not emulate TAB, the current subtree
457 visibility is cycled."
458 :group 'org-cycle
459 :type '(choice (const :tag "Never" nil)
460 (const :tag "Only in completely white lines" white)
461 (const :tag "Before first char in a line" whitestart)
462 (const :tag "Everywhere except in headlines" t)
463 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
466 (defcustom org-cycle-separator-lines 2
467 "Number of empty lines needed to keep an empty line between collapsed trees.
468 If you leave an empty line between the end of a subtree and the following
469 headline, this empty line is hidden when the subtree is folded.
470 Org-mode will leave (exactly) one empty line visible if the number of
471 empty lines is equal or larger to the number given in this variable.
472 So the default 2 means, at least 2 empty lines after the end of a subtree
473 are needed to produce free space between a collapsed subtree and the
474 following headline.
476 Special case: when 0, never leave empty lines in collapsed view."
477 :group 'org-cycle
478 :type 'integer)
480 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
481 org-cycle-hide-drawers
482 org-cycle-show-empty-lines
483 org-optimize-window-after-visibility-change)
484 "Hook that is run after `org-cycle' has changed the buffer visibility.
485 The function(s) in this hook must accept a single argument which indicates
486 the new state that was set by the most recent `org-cycle' command. The
487 argument is a symbol. After a global state change, it can have the values
488 `overview', `content', or `all'. After a local state change, it can have
489 the values `folded', `children', or `subtree'."
490 :group 'org-cycle
491 :type 'hook)
493 (defgroup org-edit-structure nil
494 "Options concerning structure editing in Org-mode."
495 :tag "Org Edit Structure"
496 :group 'org-structure)
498 (defcustom org-special-ctrl-a/e nil
499 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
500 When t, `C-a' will bring back the cursor to the beginning of the
501 headline text, i.e. after the stars and after a possible TODO keyword.
502 In an item, this will be the position after the bullet.
503 When the cursor is already at that position, another `C-a' will bring
504 it to the beginning of the line.
505 `C-e' will jump to the end of the headline, ignoring the presence of tags
506 in the headline. A second `C-e' will then jump to the true end of the
507 line, after any tags.
508 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
509 and only a directly following, identical keypress will bring the cursor
510 to the special positions."
511 :group 'org-edit-structure
512 :type '(choice
513 (const :tag "off" nil)
514 (const :tag "after bullet first" t)
515 (const :tag "border first" reversed)))
517 (if (fboundp 'defvaralias)
518 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
520 (defcustom org-odd-levels-only nil
521 "Non-nil means, skip even levels and only use odd levels for the outline.
522 This has the effect that two stars are being added/taken away in
523 promotion/demotion commands. It also influences how levels are
524 handled by the exporters.
525 Changing it requires restart of `font-lock-mode' to become effective
526 for fontification also in regions already fontified.
527 You may also set this on a per-file basis by adding one of the following
528 lines to the buffer:
530 #+STARTUP: odd
531 #+STARTUP: oddeven"
532 :group 'org-edit-structure
533 :group 'org-font-lock
534 :type 'boolean)
536 (defcustom org-adapt-indentation t
537 "Non-nil means, adapt indentation when promoting and demoting.
538 When this is set and the *entire* text in an entry is indented, the
539 indentation is increased by one space in a demotion command, and
540 decreased by one in a promotion command. If any line in the entry
541 body starts at column 0, indentation is not changed at all."
542 :group 'org-edit-structure
543 :type 'boolean)
545 (defcustom org-blank-before-new-entry '((heading . nil)
546 (plain-list-item . nil))
547 "Should `org-insert-heading' leave a blank line before new heading/item?
548 The value is an alist, with `heading' and `plain-list-item' as car,
549 and a boolean flag as cdr."
550 :group 'org-edit-structure
551 :type '(list
552 (cons (const heading) (boolean))
553 (cons (const plain-list-item) (boolean))))
555 (defcustom org-insert-heading-hook nil
556 "Hook being run after inserting a new heading."
557 :group 'org-edit-structure
558 :type 'hook)
560 (defcustom org-enable-fixed-width-editor t
561 "Non-nil means, lines starting with \":\" are treated as fixed-width.
562 This currently only means, they are never auto-wrapped.
563 When nil, such lines will be treated like ordinary lines.
564 See also the QUOTE keyword."
565 :group 'org-edit-structure
566 :type 'boolean)
568 (defgroup org-sparse-trees nil
569 "Options concerning sparse trees in Org-mode."
570 :tag "Org Sparse Trees"
571 :group 'org-structure)
573 (defcustom org-highlight-sparse-tree-matches t
574 "Non-nil means, highlight all matches that define a sparse tree.
575 The highlights will automatically disappear the next time the buffer is
576 changed by an edit command."
577 :group 'org-sparse-trees
578 :type 'boolean)
580 (defcustom org-remove-highlights-with-change t
581 "Non-nil means, any change to the buffer will remove temporary highlights.
582 Such highlights are created by `org-occur' and `org-clock-display'.
583 When nil, `C-c C-c needs to be used to get rid of the highlights.
584 The highlights created by `org-preview-latex-fragment' always need
585 `C-c C-c' to be removed."
586 :group 'org-sparse-trees
587 :group 'org-time
588 :type 'boolean)
591 (defcustom org-occur-hook '(org-first-headline-recenter)
592 "Hook that is run after `org-occur' has constructed a sparse tree.
593 This can be used to recenter the window to show as much of the structure
594 as possible."
595 :group 'org-sparse-trees
596 :type 'hook)
598 (defgroup org-plain-lists nil
599 "Options concerning plain lists in Org-mode."
600 :tag "Org Plain lists"
601 :group 'org-structure)
603 (defcustom org-cycle-include-plain-lists nil
604 "Non-nil means, include plain lists into visibility cycling.
605 This means that during cycling, plain list items will *temporarily* be
606 interpreted as outline headlines with a level given by 1000+i where i is the
607 indentation of the bullet. In all other operations, plain list items are
608 not seen as headlines. For example, you cannot assign a TODO keyword to
609 such an item."
610 :group 'org-plain-lists
611 :type 'boolean)
613 (defcustom org-plain-list-ordered-item-terminator t
614 "The character that makes a line with leading number an ordered list item.
615 Valid values are ?. and ?\). To get both terminators, use t. While
616 ?. may look nicer, it creates the danger that a line with leading
617 number may be incorrectly interpreted as an item. ?\) therefore is
618 the safe choice."
619 :group 'org-plain-lists
620 :type '(choice (const :tag "dot like in \"2.\"" ?.)
621 (const :tag "paren like in \"2)\"" ?\))
622 (const :tab "both" t)))
624 (defcustom org-auto-renumber-ordered-lists t
625 "Non-nil means, automatically renumber ordered plain lists.
626 Renumbering happens when the sequence have been changed with
627 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
628 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
629 :group 'org-plain-lists
630 :type 'boolean)
632 (defcustom org-provide-checkbox-statistics t
633 "Non-nil means, update checkbox statistics after insert and toggle.
634 When this is set, checkbox statistics is updated each time you either insert
635 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
636 with \\[org-ctrl-c-ctrl-c\\]."
637 :group 'org-plain-lists
638 :type 'boolean)
640 (defgroup org-archive nil
641 "Options concerning archiving in Org-mode."
642 :tag "Org Archive"
643 :group 'org-structure)
645 (defcustom org-archive-tag "ARCHIVE"
646 "The tag that marks a subtree as archived.
647 An archived subtree does not open during visibility cycling, and does
648 not contribute to the agenda listings.
649 After changing this, font-lock must be restarted in the relevant buffers to
650 get the proper fontification."
651 :group 'org-archive
652 :group 'org-keywords
653 :type 'string)
655 (defcustom org-agenda-skip-archived-trees t
656 "Non-nil means, the agenda will skip any items located in archived trees.
657 An archived tree is a tree marked with the tag ARCHIVE."
658 :group 'org-archive
659 :group 'org-agenda-skip
660 :type 'boolean)
662 (defcustom org-cycle-open-archived-trees nil
663 "Non-nil means, `org-cycle' will open archived trees.
664 An archived tree is a tree marked with the tag ARCHIVE.
665 When nil, archived trees will stay folded. You can still open them with
666 normal outline commands like `show-all', but not with the cycling commands."
667 :group 'org-archive
668 :group 'org-cycle
669 :type 'boolean)
671 (defcustom org-sparse-tree-open-archived-trees nil
672 "Non-nil means sparse tree construction shows matches in archived trees.
673 When nil, matches in these trees are highlighted, but the trees are kept in
674 collapsed state."
675 :group 'org-archive
676 :group 'org-sparse-trees
677 :type 'boolean)
679 (defcustom org-archive-location "%s_archive::"
680 "The location where subtrees should be archived.
681 This string consists of two parts, separated by a double-colon.
683 The first part is a file name - when omitted, archiving happens in the same
684 file. %s will be replaced by the current file name (without directory part).
685 Archiving to a different file is useful to keep archived entries from
686 contributing to the Org-mode Agenda.
688 The part after the double colon is a headline. The archived entries will be
689 filed under that headline. When omitted, the subtrees are simply filed away
690 at the end of the file, as top-level entries.
692 Here are a few examples:
693 \"%s_archive::\"
694 If the current file is Projects.org, archive in file
695 Projects.org_archive, as top-level trees. This is the default.
697 \"::* Archived Tasks\"
698 Archive in the current file, under the top-level headline
699 \"* Archived Tasks\".
701 \"~/org/archive.org::\"
702 Archive in file ~/org/archive.org (absolute path), as top-level trees.
704 \"basement::** Finished Tasks\"
705 Archive in file ./basement (relative path), as level 3 trees
706 below the level 2 heading \"** Finished Tasks\".
708 You may set this option on a per-file basis by adding to the buffer a
709 line like
711 #+ARCHIVE: basement::** Finished Tasks"
712 :group 'org-archive
713 :type 'string)
715 (defcustom org-archive-mark-done t
716 "Non-nil means, mark entries as DONE when they are moved to the archive file.
717 This can be a string to set the keyword to use. When t, Org-mode will
718 use the first keyword in its list that means done."
719 :group 'org-archive
720 :type '(choice
721 (const :tag "No" nil)
722 (const :tag "Yes" t)
723 (string :tag "Use this keyword")))
725 (defcustom org-archive-stamp-time t
726 "Non-nil means, add a time stamp to entries moved to an archive file.
727 This variable is obsolete and has no effect anymore, instead add ot remove
728 `time' from the variablle `org-archive-save-context-info'."
729 :group 'org-archive
730 :type 'boolean)
732 (defcustom org-archive-save-context-info '(time file category todo itags)
733 "Parts of context info that should be stored as properties when archiving.
734 When a subtree is moved to an archive file, it looses information given by
735 context, like inherited tags, the category, and possibly also the TODO
736 state (depending on the variable `org-archive-mark-done').
737 This variable can be a list of any of the following symbols:
739 time The time of archiving.
740 file The file where the entry originates.
741 itags The local tags, in the headline of the subtree.
742 ltags The tags the subtree inherits from further up the hierarchy.
743 todo The pre-archive TODO state.
744 category The category, taken from file name or #+CATEGORY lines.
746 For each symbol present in the list, a property will be created in
747 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
748 information."
749 :group 'org-archive
750 :type '(set :greedy t
751 (const :tag "Time" time)
752 (const :tag "File" file)
753 (const :tag "Category" category)
754 (const :tag "TODO state" todo)
755 (const :tag "TODO state" priority)
756 (const :tag "Inherited tags" itags)
757 (const :tag "Local tags" ltags)))
759 (defgroup org-imenu-and-speedbar nil
760 "Options concerning imenu and speedbar in Org-mode."
761 :tag "Org Imenu and Speedbar"
762 :group 'org-structure)
764 (defcustom org-imenu-depth 2
765 "The maximum level for Imenu access to Org-mode headlines.
766 This also applied for speedbar access."
767 :group 'org-imenu-and-speedbar
768 :type 'number)
770 (defgroup org-table nil
771 "Options concerning tables in Org-mode."
772 :tag "Org Table"
773 :group 'org)
775 (defcustom org-enable-table-editor 'optimized
776 "Non-nil means, lines starting with \"|\" are handled by the table editor.
777 When nil, such lines will be treated like ordinary lines.
779 When equal to the symbol `optimized', the table editor will be optimized to
780 do the following:
781 - Automatic overwrite mode in front of whitespace in table fields.
782 This makes the structure of the table stay in tact as long as the edited
783 field does not exceed the column width.
784 - Minimize the number of realigns. Normally, the table is aligned each time
785 TAB or RET are pressed to move to another field. With optimization this
786 happens only if changes to a field might have changed the column width.
787 Optimization requires replacing the functions `self-insert-command',
788 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
789 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
790 very good at guessing when a re-align will be necessary, but you can always
791 force one with \\[org-ctrl-c-ctrl-c].
793 If you would like to use the optimized version in Org-mode, but the
794 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
796 This variable can be used to turn on and off the table editor during a session,
797 but in order to toggle optimization, a restart is required.
799 See also the variable `org-table-auto-blank-field'."
800 :group 'org-table
801 :type '(choice
802 (const :tag "off" nil)
803 (const :tag "on" t)
804 (const :tag "on, optimized" optimized)))
806 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
807 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
808 In the optimized version, the table editor takes over all simple keys that
809 normally just insert a character. In tables, the characters are inserted
810 in a way to minimize disturbing the table structure (i.e. in overwrite mode
811 for empty fields). Outside tables, the correct binding of the keys is
812 restored.
814 The default for this option is t if the optimized version is also used in
815 Org-mode. See the variable `org-enable-table-editor' for details. Changing
816 this variable requires a restart of Emacs to become effective."
817 :group 'org-table
818 :type 'boolean)
820 (defcustom orgtbl-radio-table-templates
821 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
822 % END RECEIVE ORGTBL %n
823 \\begin{comment}
824 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
825 | | |
826 \\end{comment}\n")
827 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
828 @c END RECEIVE ORGTBL %n
829 @ignore
830 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
831 | | |
832 @end ignore\n")
833 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
834 <!-- END RECEIVE ORGTBL %n -->
835 <!--
836 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
837 | | |
838 -->\n"))
839 "Templates for radio tables in different major modes.
840 All occurrences of %n in a template will be replaced with the name of the
841 table, obtained by prompting the user."
842 :group 'org-table
843 :type '(repeat
844 (list (symbol :tag "Major mode")
845 (string :tag "Format"))))
847 (defgroup org-table-settings nil
848 "Settings for tables in Org-mode."
849 :tag "Org Table Settings"
850 :group 'org-table)
852 (defcustom org-table-default-size "5x2"
853 "The default size for newly created tables, Columns x Rows."
854 :group 'org-table-settings
855 :type 'string)
857 (defcustom org-table-number-regexp
858 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
859 "Regular expression for recognizing numbers in table columns.
860 If a table column contains mostly numbers, it will be aligned to the
861 right. If not, it will be aligned to the left.
863 The default value of this option is a regular expression which allows
864 anything which looks remotely like a number as used in scientific
865 context. For example, all of the following will be considered a
866 number:
867 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
869 Other options offered by the customize interface are more restrictive."
870 :group 'org-table-settings
871 :type '(choice
872 (const :tag "Positive Integers"
873 "^[0-9]+$")
874 (const :tag "Integers"
875 "^[-+]?[0-9]+$")
876 (const :tag "Floating Point Numbers"
877 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
878 (const :tag "Floating Point Number or Integer"
879 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
880 (const :tag "Exponential, Floating point, Integer"
881 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
882 (const :tag "Very General Number-Like, including hex"
883 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
884 (string :tag "Regexp:")))
886 (defcustom org-table-number-fraction 0.5
887 "Fraction of numbers in a column required to make the column align right.
888 In a column all non-white fields are considered. If at least this
889 fraction of fields is matched by `org-table-number-fraction',
890 alignment to the right border applies."
891 :group 'org-table-settings
892 :type 'number)
894 (defgroup org-table-editing nil
895 "Behavior of tables during editing in Org-mode."
896 :tag "Org Table Editing"
897 :group 'org-table)
899 (defcustom org-table-automatic-realign t
900 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
901 When nil, aligning is only done with \\[org-table-align], or after column
902 removal/insertion."
903 :group 'org-table-editing
904 :type 'boolean)
906 (defcustom org-table-auto-blank-field t
907 "Non-nil means, automatically blank table field when starting to type into it.
908 This only happens when typing immediately after a field motion
909 command (TAB, S-TAB or RET).
910 Only relevant when `org-enable-table-editor' is equal to `optimized'."
911 :group 'org-table-editing
912 :type 'boolean)
914 (defcustom org-table-tab-jumps-over-hlines t
915 "Non-nil means, tab in the last column of a table with jump over a hline.
916 If a horizontal separator line is following the current line,
917 `org-table-next-field' can either create a new row before that line, or jump
918 over the line. When this option is nil, a new line will be created before
919 this line."
920 :group 'org-table-editing
921 :type 'boolean)
923 (defcustom org-table-tab-recognizes-table.el t
924 "Non-nil means, TAB will automatically notice a table.el table.
925 When it sees such a table, it moves point into it and - if necessary -
926 calls `table-recognize-table'."
927 :group 'org-table-editing
928 :type 'boolean)
930 (defgroup org-table-calculation nil
931 "Options concerning tables in Org-mode."
932 :tag "Org Table Calculation"
933 :group 'org-table)
935 (defcustom org-table-use-standard-references t
936 "Should org-mode work with table refrences like B3 instead of @3$2?
937 Possible values are:
938 nil never use them
939 from accept as input, do not present for editing
940 t: accept as input and present for editing"
941 :group 'org-table-calculation
942 :type '(choice
943 (const :tag "Never, don't even check unser input for them" nil)
944 (const :tag "Always, both as user input, and when editing" t)
945 (const :tag "Convert user input, don't offer during editing" 'from)))
947 (defcustom org-table-copy-increment t
948 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
949 :group 'org-table-calculation
950 :type 'boolean)
952 (defcustom org-calc-default-modes
953 '(calc-internal-prec 12
954 calc-float-format (float 5)
955 calc-angle-mode deg
956 calc-prefer-frac nil
957 calc-symbolic-mode nil
958 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
959 calc-display-working-message t
961 "List with Calc mode settings for use in calc-eval for table formulas.
962 The list must contain alternating symbols (Calc modes variables and values).
963 Don't remove any of the default settings, just change the values. Org-mode
964 relies on the variables to be present in the list."
965 :group 'org-table-calculation
966 :type 'plist)
968 (defcustom org-table-formula-evaluate-inline t
969 "Non-nil means, TAB and RET evaluate a formula in current table field.
970 If the current field starts with an equal sign, it is assumed to be a formula
971 which should be evaluated as described in the manual and in the documentation
972 string of the command `org-table-eval-formula'. This feature requires the
973 Emacs calc package.
974 When this variable is nil, formula calculation is only available through
975 the command \\[org-table-eval-formula]."
976 :group 'org-table-calculation
977 :type 'boolean)
979 (defcustom org-table-formula-use-constants t
980 "Non-nil means, interpret constants in formulas in tables.
981 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
982 by the value given in `org-table-formula-constants', or by a value obtained
983 from the `constants.el' package."
984 :group 'org-table-calculation
985 :type 'boolean)
987 (defcustom org-table-formula-constants nil
988 "Alist with constant names and values, for use in table formulas.
989 The car of each element is a name of a constant, without the `$' before it.
990 The cdr is the value as a string. For example, if you'd like to use the
991 speed of light in a formula, you would configure
993 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
995 and then use it in an equation like `$1*$c'.
997 Constants can also be defined on a per-file basis using a line like
999 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1000 :group 'org-table-calculation
1001 :type '(repeat
1002 (cons (string :tag "name")
1003 (string :tag "value"))))
1005 (defvar org-table-formula-constants-local nil
1006 "Local version of `org-table-formula-constants'.")
1007 (make-variable-buffer-local 'org-table-formula-constants-local)
1009 (defcustom org-table-allow-automatic-line-recalculation t
1010 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1011 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1012 :group 'org-table-calculation
1013 :type 'boolean)
1015 (defgroup org-link nil
1016 "Options concerning links in Org-mode."
1017 :tag "Org Link"
1018 :group 'org)
1020 (defvar org-link-abbrev-alist-local nil
1021 "Buffer-local version of `org-link-abbrev-alist', which see.
1022 The value of this is taken from the #+LINK lines.")
1023 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1025 (defcustom org-link-abbrev-alist nil
1026 "Alist of link abbreviations.
1027 The car of each element is a string, to be replaced at the start of a link.
1028 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1029 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1031 [[linkkey:tag][description]]
1033 If REPLACE is a string, the tag will simply be appended to create the link.
1034 If the string contains \"%s\", the tag will be inserted there.
1036 REPLACE may also be a function that will be called with the tag as the
1037 only argument to create the link, which should be returned as a string.
1039 See the manual for examples."
1040 :group 'org-link
1041 :type 'alist)
1043 (defcustom org-descriptive-links t
1044 "Non-nil means, hide link part and only show description of bracket links.
1045 Bracket links are like [[link][descritpion]]. This variable sets the initial
1046 state in new org-mode buffers. The setting can then be toggled on a
1047 per-buffer basis from the Org->Hyperlinks menu."
1048 :group 'org-link
1049 :type 'boolean)
1051 (defcustom org-link-file-path-type 'adaptive
1052 "How the path name in file links should be stored.
1053 Valid values are:
1055 relative relative to the current directory, i.e. the directory of the file
1056 into which the link is being inserted.
1057 absolute absolute path, if possible with ~ for home directory.
1058 noabbrev absolute path, no abbreviation of home directory.
1059 adaptive Use relative path for files in the current directory and sub-
1060 directories of it. For other files, use an absolute path."
1061 :group 'org-link
1062 :type '(choice
1063 (const relative)
1064 (const absolute)
1065 (const noabbrev)
1066 (const adaptive)))
1068 (defcustom org-activate-links '(bracket angle plain radio tag date)
1069 "Types of links that should be activated in Org-mode files.
1070 This is a list of symbols, each leading to the activation of a certain link
1071 type. In principle, it does not hurt to turn on most link types - there may
1072 be a small gain when turning off unused link types. The types are:
1074 bracket The recommended [[link][description]] or [[link]] links with hiding.
1075 angular Links in angular brackes that may contain whitespace like
1076 <bbdb:Carsten Dominik>.
1077 plain Plain links in normal text, no whitespace, like http://google.com.
1078 radio Text that is matched by a radio target, see manual for details.
1079 tag Tag settings in a headline (link to tag search).
1080 date Time stamps (link to calendar).
1082 Changing this variable requires a restart of Emacs to become effective."
1083 :group 'org-link
1084 :type '(set (const :tag "Double bracket links (new style)" bracket)
1085 (const :tag "Angular bracket links (old style)" angular)
1086 (const :tag "plain text links" plain)
1087 (const :tag "Radio target matches" radio)
1088 (const :tag "Tags" tag)
1089 (const :tag "Tags" target)
1090 (const :tag "Timestamps" date)))
1092 (defgroup org-link-store nil
1093 "Options concerning storing links in Org-mode"
1094 :tag "Org Store Link"
1095 :group 'org-link)
1097 (defcustom org-email-link-description-format "Email %c: %.30s"
1098 "Format of the description part of a link to an email or usenet message.
1099 The following %-excapes will be replaced by corresponding information:
1101 %F full \"From\" field
1102 %f name, taken from \"From\" field, address if no name
1103 %T full \"To\" field
1104 %t first name in \"To\" field, address if no name
1105 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1106 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1107 %s subject
1108 %m message-id.
1110 You may use normal field width specification between the % and the letter.
1111 This is for example useful to limit the length of the subject.
1113 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1114 :group 'org-link-store
1115 :type 'string)
1117 (defcustom org-from-is-user-regexp
1118 (let (r1 r2)
1119 (when (and user-mail-address (not (string= user-mail-address "")))
1120 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1121 (when (and user-full-name (not (string= user-full-name "")))
1122 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1123 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1124 "Regexp mached against the \"From:\" header of an email or usenet message.
1125 It should match if the message is from the user him/herself."
1126 :group 'org-link-store
1127 :type 'regexp)
1129 (defcustom org-context-in-file-links t
1130 "Non-nil means, file links from `org-store-link' contain context.
1131 A search string will be added to the file name with :: as separator and
1132 used to find the context when the link is activated by the command
1133 `org-open-at-point'.
1134 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1135 negates this setting for the duration of the command."
1136 :group 'org-link-store
1137 :type 'boolean)
1139 (defcustom org-keep-stored-link-after-insertion nil
1140 "Non-nil means, keep link in list for entire session.
1142 The command `org-store-link' adds a link pointing to the current
1143 location to an internal list. These links accumulate during a session.
1144 The command `org-insert-link' can be used to insert links into any
1145 Org-mode file (offering completion for all stored links). When this
1146 option is nil, every link which has been inserted once using \\[org-insert-link]
1147 will be removed from the list, to make completing the unused links
1148 more efficient."
1149 :group 'org-link-store
1150 :type 'boolean)
1152 (defcustom org-usenet-links-prefer-google nil
1153 "Non-nil means, `org-store-link' will create web links to Google groups.
1154 When nil, Gnus will be used for such links.
1155 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1156 negates this setting for the duration of the command."
1157 :group 'org-link-store
1158 :type 'boolean)
1160 (defgroup org-link-follow nil
1161 "Options concerning following links in Org-mode"
1162 :tag "Org Follow Link"
1163 :group 'org-link)
1165 (defcustom org-tab-follows-link nil
1166 "Non-nil means, on links TAB will follow the link.
1167 Needs to be set before org.el is loaded."
1168 :group 'org-link-follow
1169 :type 'boolean)
1171 (defcustom org-return-follows-link nil
1172 "Non-nil means, on links RET will follow the link.
1173 Needs to be set before org.el is loaded."
1174 :group 'org-link-follow
1175 :type 'boolean)
1177 (defcustom org-mouse-1-follows-link t
1178 "Non-nil means, mouse-1 on a link will follow the link.
1179 A longer mouse click will still set point. Does not wortk on XEmacs.
1180 Needs to be set before org.el is loaded."
1181 :group 'org-link-follow
1182 :type 'boolean)
1184 (defcustom org-mark-ring-length 4
1185 "Number of different positions to be recorded in the ring
1186 Changing this requires a restart of Emacs to work correctly."
1187 :group 'org-link-follow
1188 :type 'interger)
1190 (defcustom org-link-frame-setup
1191 '((vm . vm-visit-folder-other-frame)
1192 (gnus . gnus-other-frame)
1193 (file . find-file-other-window))
1194 "Setup the frame configuration for following links.
1195 When following a link with Emacs, it may often be useful to display
1196 this link in another window or frame. This variable can be used to
1197 set this up for the different types of links.
1198 For VM, use any of
1199 `vm-visit-folder'
1200 `vm-visit-folder-other-frame'
1201 For Gnus, use any of
1202 `gnus'
1203 `gnus-other-frame'
1204 For FILE, use any of
1205 `find-file'
1206 `find-file-other-window'
1207 `find-file-other-frame'
1208 For the calendar, use the variable `calendar-setup'.
1209 For BBDB, it is currently only possible to display the matches in
1210 another window."
1211 :group 'org-link-follow
1212 :type '(list
1213 (cons (const vm)
1214 (choice
1215 (const vm-visit-folder)
1216 (const vm-visit-folder-other-window)
1217 (const vm-visit-folder-other-frame)))
1218 (cons (const gnus)
1219 (choice
1220 (const gnus)
1221 (const gnus-other-frame)))
1222 (cons (const file)
1223 (choice
1224 (const find-file)
1225 (const find-file-other-window)
1226 (const find-file-other-frame)))))
1228 (defcustom org-display-internal-link-with-indirect-buffer nil
1229 "Non-nil means, use indirect buffer to display infile links.
1230 Activating internal links (from one location in a file to another location
1231 in the same file) normally just jumps to the location. When the link is
1232 activated with a C-u prefix (or with mouse-3), the link is displayed in
1233 another window. When this option is set, the other window actually displays
1234 an indirect buffer clone of the current buffer, to avoid any visibility
1235 changes to the current buffer."
1236 :group 'org-link-follow
1237 :type 'boolean)
1239 (defcustom org-open-non-existing-files nil
1240 "Non-nil means, `org-open-file' will open non-existing files.
1241 When nil, an error will be generated."
1242 :group 'org-link-follow
1243 :type 'boolean)
1245 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1246 "Function and arguments to call for following mailto links.
1247 This is a list with the first element being a lisp function, and the
1248 remaining elements being arguments to the function. In string arguments,
1249 %a will be replaced by the address, and %s will be replaced by the subject
1250 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1251 :group 'org-link-follow
1252 :type '(choice
1253 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1254 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1255 (const :tag "message-mail" (message-mail "%a" "%s"))
1256 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1258 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1259 "Non-nil means, ask for confirmation before executing shell links.
1260 Shell links can be dangerous: just think about a link
1262 [[shell:rm -rf ~/*][Google Search]]
1264 This link would show up in your Org-mode document as \"Google Search\",
1265 but really it would remove your entire home directory.
1266 Therefore we advise against setting this variable to nil.
1267 Just change it to `y-or-n-p' of you want to confirm with a
1268 single keystroke rather than having to type \"yes\"."
1269 :group 'org-link-follow
1270 :type '(choice
1271 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1272 (const :tag "with y-or-n (faster)" y-or-n-p)
1273 (const :tag "no confirmation (dangerous)" nil)))
1275 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1276 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1277 Elisp links can be dangerous: just think about a link
1279 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1281 This link would show up in your Org-mode document as \"Google Search\",
1282 but really it would remove your entire home directory.
1283 Therefore we advise against setting this variable to nil.
1284 Just change it to `y-or-n-p' of you want to confirm with a
1285 single keystroke rather than having to type \"yes\"."
1286 :group 'org-link-follow
1287 :type '(choice
1288 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1289 (const :tag "with y-or-n (faster)" y-or-n-p)
1290 (const :tag "no confirmation (dangerous)" nil)))
1292 (defconst org-file-apps-defaults-gnu
1293 '((remote . emacs)
1294 (t . mailcap))
1295 "Default file applications on a UNIX or GNU/Linux system.
1296 See `org-file-apps'.")
1298 (defconst org-file-apps-defaults-macosx
1299 '((remote . emacs)
1300 (t . "open %s")
1301 ("ps" . "gv %s")
1302 ("ps.gz" . "gv %s")
1303 ("eps" . "gv %s")
1304 ("eps.gz" . "gv %s")
1305 ("dvi" . "xdvi %s")
1306 ("fig" . "xfig %s"))
1307 "Default file applications on a MacOS X system.
1308 The system \"open\" is known as a default, but we use X11 applications
1309 for some files for which the OS does not have a good default.
1310 See `org-file-apps'.")
1312 (defconst org-file-apps-defaults-windowsnt
1313 (list
1314 '(remote . emacs)
1315 (cons t
1316 (list (if (featurep 'xemacs)
1317 'mswindows-shell-execute
1318 'w32-shell-execute)
1319 "open" 'file)))
1320 "Default file applications on a Windows NT system.
1321 The system \"open\" is used for most files.
1322 See `org-file-apps'.")
1324 (defcustom org-file-apps
1326 ("txt" . emacs)
1327 ("tex" . emacs)
1328 ("ltx" . emacs)
1329 ("org" . emacs)
1330 ("el" . emacs)
1331 ("bib" . emacs)
1333 "External applications for opening `file:path' items in a document.
1334 Org-mode uses system defaults for different file types, but
1335 you can use this variable to set the application for a given file
1336 extension. The entries in this list are cons cells where the car identifies
1337 files and the cdr the corresponding command. Possible values for the
1338 file identifier are
1339 \"ext\" A string identifying an extension
1340 `directory' Matches a directory
1341 `remote' Matches a remote file, accessible through tramp or efs.
1342 Remote files most likely should be visited through Emacs
1343 because external applications cannot handle such paths.
1344 t Default for all remaining files
1346 Possible values for the command are:
1347 `emacs' The file will be visited by the current Emacs process.
1348 `default' Use the default application for this file type.
1349 string A command to be executed by a shell; %s will be replaced
1350 by the path to the file.
1351 sexp A Lisp form which will be evaluated. The file path will
1352 be available in the Lisp variable `file'.
1353 For more examples, see the system specific constants
1354 `org-file-apps-defaults-macosx'
1355 `org-file-apps-defaults-windowsnt'
1356 `org-file-apps-defaults-gnu'."
1357 :group 'org-link-follow
1358 :type '(repeat
1359 (cons (choice :value ""
1360 (string :tag "Extension")
1361 (const :tag "Default for unrecognized files" t)
1362 (const :tag "Remote file" remote)
1363 (const :tag "Links to a directory" directory))
1364 (choice :value ""
1365 (const :tag "Visit with Emacs" emacs)
1366 (const :tag "Use system default" default)
1367 (string :tag "Command")
1368 (sexp :tag "Lisp form")))))
1370 (defcustom org-mhe-search-all-folders nil
1371 "Non-nil means, that the search for the mh-message will be extended to
1372 all folders if the message cannot be found in the folder given in the link.
1373 Searching all folders is very efficient with one of the search engines
1374 supported by MH-E, but will be slow with pick."
1375 :group 'org-link-follow
1376 :type 'boolean)
1378 (defgroup org-remember nil
1379 "Options concerning interaction with remember.el."
1380 :tag "Org Remember"
1381 :group 'org)
1383 (defcustom org-directory "~/org"
1384 "Directory with org files.
1385 This directory will be used as default to prompt for org files.
1386 Used by the hooks for remember.el."
1387 :group 'org-remember
1388 :type 'directory)
1390 (defcustom org-default-notes-file "~/.notes"
1391 "Default target for storing notes.
1392 Used by the hooks for remember.el. This can be a string, or nil to mean
1393 the value of `remember-data-file'.
1394 You can set this on a per-template basis with the variable
1395 `org-remember-templates'."
1396 :group 'org-remember
1397 :type '(choice
1398 (const :tag "Default from remember-data-file" nil)
1399 file))
1401 (defcustom org-remember-store-without-prompt t
1402 "Non-nil means, `C-c C-c' stores remember note without further promts.
1403 In this case, you need `C-u C-c C-c' to get the prompts for
1404 note file and headline.
1405 When this variable is nil, `C-c C-c' give you the prompts, and
1406 `C-u C-c C-c' trigger the fasttrack."
1407 :group 'org-remember
1408 :type 'boolean)
1410 (defcustom org-remember-default-headline ""
1411 "The headline that should be the default location in the notes file.
1412 When filing remember notes, the cursor will start at that position.
1413 You can set this on a per-template basis with the variable
1414 `org-remember-templates'."
1415 :group 'org-remember
1416 :type 'string)
1418 (defcustom org-remember-templates nil
1419 "Templates for the creation of remember buffers.
1420 When nil, just let remember make the buffer.
1421 When not nil, this is a list of 5-element lists. In each entry, the first
1422 element is a the name of the template, It should be a single short word.
1423 The second element is a character, a unique key to select this template.
1424 The third element is the template. The forth element is optional and can
1425 specify a destination file for remember items created with this template.
1426 The default file is given by `org-default-notes-file'. An optional fifth
1427 element can specify the headline in that file that should be offered
1428 first when the user is asked to file the entry. The default headline is
1429 given in the variable `org-remember-default-headline'.
1431 The template specifies the structure of the remember buffer. It should have
1432 a first line starting with a star, to act as the org-mode headline.
1433 Furthermore, the following %-escapes will be replaced with content:
1435 %^{prompt} prompt the user for a string and replace this sequence with it.
1436 %t time stamp, date only
1437 %T time stamp with date and time
1438 %u, %U like the above, but inactive time stamps
1439 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1440 You may define a prompt like %^{Please specify birthday}t
1441 %n user name (taken from `user-full-name')
1442 %a annotation, normally the link created with org-store-link
1443 %i initial content, the region when remember is called with C-u.
1444 If %i is indented, the entire inserted text will be indented
1445 as well.
1447 %? After completing the template, position cursor here.
1449 Apart from these general escapes, you can access information specific to the
1450 link type that is created. For example, calling `remember' in emails or gnus
1451 will record the author and the subject of the message, which you can access
1452 with %:author and %:subject, respectively. Here is a complete list of what
1453 is recorded for each link type.
1455 Link type | Available information
1456 -------------------+------------------------------------------------------
1457 bbdb | %:type %:name %:company
1458 vm, wl, mh, rmail | %:type %:subject %:message-id
1459 | %:from %:fromname %:fromaddress
1460 | %:to %:toname %:toaddress
1461 | %:fromto (either \"to NAME\" or \"from NAME\")
1462 gnus | %:group, for messages also all email fields
1463 w3, w3m | %:type %:url
1464 info | %:type %:file %:node
1465 calendar | %:type %:date"
1466 :group 'org-remember
1467 :get (lambda (var) ; Make sure all entries have 5 elements
1468 (mapcar (lambda (x)
1469 (if (not (stringp (car x))) (setq x (cons "" x)))
1470 (cond ((= (length x) 4) (append x '("")))
1471 ((= (length x) 3) (append x '("" "")))
1472 (t x)))
1473 (default-value var)))
1474 :type '(repeat
1475 :tag "enabled"
1476 (list :value ("" ?a "\n" nil nil)
1477 (string :tag "Name")
1478 (character :tag "Selection Key")
1479 (string :tag "Template")
1480 (choice
1481 (file :tag "Destination file")
1482 (const :tag "Prompt for file" nil))
1483 (choice
1484 (string :tag "Destination headline")
1485 (const :tag "Selection interface for heading")))))
1487 (defcustom org-reverse-note-order nil
1488 "Non-nil means, store new notes at the beginning of a file or entry.
1489 When nil, new notes will be filed to the end of a file or entry.
1490 This can also be a list with cons cells of regular expressions that
1491 are matched against file names, and values."
1492 :group 'org-remember
1493 :type '(choice
1494 (const :tag "Reverse always" t)
1495 (const :tag "Reverse never" nil)
1496 (repeat :tag "By file name regexp"
1497 (cons regexp boolean))))
1499 (defcustom org-refile-targets '((nil . (:level . 1)))
1500 "Targets for refiling entries with \\[org-refile].
1501 This is list of cons cells. Each cell contains:
1502 - a specification of the files to be considered, either a list of files,
1503 or a symbol whose function or value fields will be used to retrieve
1504 a file name or a list of file names. Nil means, refile to a different
1505 heading in the current buffer.
1506 - A specification of how to find candidate refile targets. This may be
1507 any of
1508 - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
1509 This tag has to be present in all target headlines, inheritance will
1510 not be considered.
1511 - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
1512 todo keyword.
1513 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1514 headlines that are refiling targets.
1515 - a cons cell (:level . N). Any headline of level N is considered a target."
1516 ;; FIXME: what if there are a var and func with same name???
1517 :group 'org
1518 :type '(repeat
1519 (cons
1520 (choice :value org-agenda-files
1521 (const :tag "All agenda files" org-agenda-files)
1522 (const :tag "Current buffer" nil)
1523 (function) (variable) (file))
1524 (choice :tag "Identify target headline by"
1525 (cons :tag "Specific tag" (const :tag) (string))
1526 (cons :tag "TODO keyword" (const :todo) (string))
1527 (cons :tag "Regular expression" (const :regexp) (regexp))
1528 (cons :tag "Level number" (const :level) (integer))))))
1530 (defgroup org-todo nil
1531 "Options concerning TODO items in Org-mode."
1532 :tag "Org TODO"
1533 :group 'org)
1535 (defgroup org-progress nil
1536 "Options concerning Progress logging in Org-mode."
1537 :tag "Org Progress"
1538 :group 'org-time)
1540 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1541 "List of TODO entry keyword sequences and their interpretation.
1542 \\<org-mode-map>This is a list of sequences.
1544 Each sequence starts with a symbol, either `sequence' or `type',
1545 indicating if the keywords should be interpreted as a sequence of
1546 action steps, or as different types of TODO items. The first
1547 keywords are states requiring action - these states will select a headline
1548 for inclusion into the global TODO list Org-mode produces. If one of
1549 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1550 signify that no further action is necessary. If \"|\" is not found,
1551 the last keyword is treated as the only DONE state of the sequence.
1553 The command \\[org-todo] cycles an entry through these states, and one
1554 additional state where no keyword is present. For details about this
1555 cycling, see the manual.
1557 TODO keywords and interpretation can also be set on a per-file basis with
1558 the special #+SEQ_TODO and #+TYP_TODO lines.
1560 For backward compatibility, this variable may also be just a list
1561 of keywords - in this case the interptetation (sequence or type) will be
1562 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1563 :group 'org-todo
1564 :group 'org-keywords
1565 :type '(choice
1566 (repeat :tag "Old syntax, just keywords"
1567 (string :tag "Keyword"))
1568 (repeat :tag "New syntax"
1569 (cons
1570 (choice
1571 :tag "Interpretation"
1572 (const :tag "Sequence (cycling hits every state)" sequence)
1573 (const :tag "Type (cycling directly to DONE)" type))
1574 (repeat
1575 (string :tag "Keyword"))))))
1577 (defvar org-todo-keywords-1 nil)
1578 (make-variable-buffer-local 'org-todo-keywords-1)
1579 (defvar org-todo-keywords-for-agenda nil)
1580 (defvar org-done-keywords-for-agenda nil)
1581 (defvar org-not-done-keywords nil)
1582 (make-variable-buffer-local 'org-not-done-keywords)
1583 (defvar org-done-keywords nil)
1584 (make-variable-buffer-local 'org-done-keywords)
1585 (defvar org-todo-heads nil)
1586 (make-variable-buffer-local 'org-todo-heads)
1587 (defvar org-todo-sets nil)
1588 (make-variable-buffer-local 'org-todo-sets)
1589 (defvar org-todo-log-states nil)
1590 (make-variable-buffer-local 'org-todo-log-states)
1591 (defvar org-todo-kwd-alist nil)
1592 (make-variable-buffer-local 'org-todo-kwd-alist)
1593 (defvar org-todo-key-alist nil)
1594 (make-variable-buffer-local 'org-todo-key-alist)
1595 (defvar org-todo-key-trigger nil)
1596 (make-variable-buffer-local 'org-todo-key-trigger)
1598 (defcustom org-todo-interpretation 'sequence
1599 "Controls how TODO keywords are interpreted.
1600 This variable is in principle obsolete and is only used for
1601 backward compatibility, if the interpretation of todo keywords is
1602 not given already in `org-todo-keywords'. See that variable for
1603 more information."
1604 :group 'org-todo
1605 :group 'org-keywords
1606 :type '(choice (const sequence)
1607 (const type)))
1609 (defcustom org-use-fast-todo-selection 'prefix
1610 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1611 This variable describes if and under what circumstances the cycling
1612 mechanism for TODO keywords will be replaced by a single-key, direct
1613 selection scheme.
1615 When nil, fast selection is never used.
1617 When the symbol `prefix', it will be used when `org-todo' is called with
1618 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1619 in an agenda buffer.
1621 When t, fast selection is used by default. In this case, the prefix
1622 argument forces cycling instead.
1624 In all cases, the special interface is only used if access keys have actually
1625 been assigned by the user, i.e. if keywords in the configuration are followed
1626 by a letter in parenthesis, like TODO(t)."
1627 :group 'org-todo
1628 :type '(choice
1629 (const :tag "Never" nil)
1630 (const :tag "By default" t)
1631 (const :tag "Only with C-u C-c C-t" prefix)))
1633 (defcustom org-after-todo-state-change-hook nil
1634 "Hook which is run after the state of a TODO item was changed.
1635 The new state (a string with a TODO keyword, or nil) is available in the
1636 Lisp variable `state'."
1637 :group 'org-todo
1638 :type 'hook)
1640 (defcustom org-log-done nil
1641 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1642 When the state of an entry is changed from nothing or a DONE state to
1643 a not-done TODO state, remove a previous closing date.
1645 This can also be a list of symbols indicating under which conditions
1646 the time stamp recording the action should be annotated with a short note.
1647 Valid members of this list are
1649 done Offer to record a note when marking entries done
1650 state Offer to record a note whenever changing the TODO state
1651 of an item. This is only relevant if TODO keywords are
1652 interpreted as sequence, see variable `org-todo-interpretation'.
1653 When `state' is set, this includes tracking `done'.
1654 clock-out Offer to record a note when clocking out of an item.
1656 A separate window will then pop up and allow you to type a note.
1657 After finishing with C-c C-c, the note will be added directly after the
1658 timestamp, as a plain list item. See also the variable
1659 `org-log-note-headings'.
1661 Logging can also be configured on a per-file basis by adding one of
1662 the following lines anywhere in the buffer:
1664 #+STARTUP: logdone
1665 #+STARTUP: nologging
1666 #+STARTUP: lognotedone
1667 #+STARTUP: lognotestate
1668 #+STARTUP: lognoteclock-out
1670 You can have local logging settings for a subtree by setting the LOGGING
1671 property to one or more of these keywords."
1672 :group 'org-todo
1673 :group 'org-progress
1674 :type '(choice
1675 (const :tag "off" nil)
1676 (const :tag "on" t)
1677 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1678 (const :tag "when item is marked DONE" done)
1679 (const :tag "when TODO state changes" state)
1680 (const :tag "when clocking out" clock-out))))
1682 (defcustom org-log-done-with-time t
1683 "Non-nil means, the CLOSED time stamp will contain date and time.
1684 When nil, only the date will be recorded."
1685 :group 'org-progress
1686 :type 'boolean)
1688 (defcustom org-log-note-headings
1689 '((done . "CLOSING NOTE %t")
1690 (state . "State %-12s %t")
1691 (clock-out . ""))
1692 "Headings for notes added when clocking out or closing TODO items.
1693 The value is an alist, with the car being a symbol indicating the note
1694 context, and the cdr is the heading to be used. The heading may also be the
1695 empty string.
1696 %t in the heading will be replaced by a time stamp.
1697 %s will be replaced by the new TODO state, in double quotes.
1698 %u will be replaced by the user name.
1699 %U will be replaced by the full user name."
1700 :group 'org-todo
1701 :group 'org-progress
1702 :type '(list :greedy t
1703 (cons (const :tag "Heading when closing an item" done) string)
1704 (cons (const :tag
1705 "Heading when changing todo state (todo sequence only)"
1706 state) string)
1707 (cons (const :tag "Heading when clocking out" clock-out) string)))
1709 (defcustom org-log-states-order-reversed t
1710 "Non-nil means, the latest state change note will be directly after heading.
1711 When nil, the notes will be orderer according to time."
1712 :group 'org-todo
1713 :group 'org-progress
1714 :type 'boolean)
1716 (defcustom org-log-repeat t
1717 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1718 When nil, no note will be taken.
1719 This option can also be set with on a per-file-basis with
1721 #+STARTUP: logrepeat
1722 #+STARTUP: nologrepeat
1724 You can have local logging settings for a subtree by setting the LOGGING
1725 property to one or more of these keywords."
1726 :group 'org-todo
1727 :group 'org-progress
1728 :type 'boolean)
1730 (defcustom org-clock-into-drawer 2
1731 "Should clocking info be wrapped into a drawer?
1732 When t, clocking info will always be inserted into a :CLOCK: drawer.
1733 If necessary, the drawer will be created.
1734 When nil, the drawer will not be created, but used when present.
1735 When an integer and the number of clocking entries in an item
1736 reaches or exceeds this number, a drawer will be created."
1737 :group 'org-todo
1738 :group 'org-progress
1739 :type '(choice
1740 (const :tag "Always" t)
1741 (const :tag "Only when drawer exists" nil)
1742 (integer :tag "When at least N clock entries")))
1744 (defcustom org-clock-out-when-done t
1745 "When t, the clock will be stopped when the relevant entry is marked DONE.
1746 Nil means, clock will keep running until stopped explicitly with
1747 `C-c C-x C-o', or until the clock is started in a different item."
1748 :group 'org-progress
1749 :type 'boolean)
1751 (defgroup org-priorities nil
1752 "Priorities in Org-mode."
1753 :tag "Org Priorities"
1754 :group 'org-todo)
1756 (defcustom org-highest-priority ?A
1757 "The highest priority of TODO items. A character like ?A, ?B etc.
1758 Must have a smaller ASCII number than `org-lowest-priority'."
1759 :group 'org-priorities
1760 :type 'character)
1762 (defcustom org-lowest-priority ?C
1763 "The lowest priority of TODO items. A character like ?A, ?B etc.
1764 Must have a larger ASCII number than `org-highest-priority'."
1765 :group 'org-priorities
1766 :type 'character)
1768 (defcustom org-default-priority ?B
1769 "The default priority of TODO items.
1770 This is the priority an item get if no explicit priority is given."
1771 :group 'org-priorities
1772 :type 'character)
1774 (defcustom org-priority-start-cycle-with-default t
1775 "Non-nil means, start with default priority when starting to cycle.
1776 When this is nil, the first step in the cycle will be (depending on the
1777 command used) one higher or lower that the default priority."
1778 :group 'org-priorities
1779 :type 'boolean)
1781 (defgroup org-time nil
1782 "Options concerning time stamps and deadlines in Org-mode."
1783 :tag "Org Time"
1784 :group 'org)
1786 (defcustom org-insert-labeled-timestamps-at-point nil
1787 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1788 When nil, these labeled time stamps are forces into the second line of an
1789 entry, just after the headline. When scheduling from the global TODO list,
1790 the time stamp will always be forced into the second line."
1791 :group 'org-time
1792 :type 'boolean)
1794 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1795 "Formats for `format-time-string' which are used for time stamps.
1796 It is not recommended to change this constant.")
1798 (defcustom org-time-stamp-rounding-minutes 0
1799 "Number of minutes to round time stamps to upon insertion.
1800 When zero, insert the time unmodified. Useful rounding numbers
1801 should be factors of 60, so for example 5, 10, 15.
1802 When this is not zero, you can still force an exact time-stamp by using
1803 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1804 :group 'org-time
1805 :type 'integer)
1807 (defcustom org-display-custom-times nil
1808 "Non-nil means, overlay custom formats over all time stamps.
1809 The formats are defined through the variable `org-time-stamp-custom-formats'.
1810 To turn this on on a per-file basis, insert anywhere in the file:
1811 #+STARTUP: customtime"
1812 :group 'org-time
1813 :set 'set-default
1814 :type 'sexp)
1815 (make-variable-buffer-local 'org-display-custom-times)
1817 (defcustom org-time-stamp-custom-formats
1818 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1819 "Custom formats for time stamps. See `format-time-string' for the syntax.
1820 These are overlayed over the default ISO format if the variable
1821 `org-display-custom-times' is set. Time like %H:%M should be at the
1822 end of the second format."
1823 :group 'org-time
1824 :type 'sexp)
1826 (defun org-time-stamp-format (&optional long inactive)
1827 "Get the right format for a time string."
1828 (let ((f (if long (cdr org-time-stamp-formats)
1829 (car org-time-stamp-formats))))
1830 (if inactive
1831 (concat "[" (substring f 1 -1) "]")
1832 f)))
1834 (defcustom org-read-date-prefer-future t
1835 "Non-nil means, assume future for incomplete date input from user.
1836 This affects the following situations:
1837 1. The user gives a day, but no month.
1838 For example, if today is the 15th, and you enter \"3\", Org-mode will
1839 read this as the third of *next* month. However, if you enter \"17\",
1840 it will be considered as *this* month.
1841 2. The user gives a month but not a year.
1842 For example, if it is april and you enter \"feb 2\", this will be read
1843 as feb 2, *next* year. \"May 5\", however, will be this year.
1845 When this option is nil, the current month and year will always be used
1846 as defaults."
1847 :group 'org-time
1848 :type 'boolean)
1850 (defcustom org-read-date-display-live t
1851 "Non-nil means, display current interpretation of date prompt live.
1852 This display will be in an overlay, in the minibuffer."
1853 :group 'org-time
1854 :type 'boolean)
1856 (defcustom org-read-date-popup-calendar t
1857 "Non-nil means, pop up a calendar when prompting for a date.
1858 In the calendar, the date can be selected with mouse-1. However, the
1859 minibuffer will also be active, and you can simply enter the date as well.
1860 When nil, only the minibuffer will be available."
1861 :group 'org-time
1862 :type 'boolean)
1863 (if (fboundp 'defvaralias)
1864 (defvaralias 'org-popup-calendar-for-date-prompt
1865 'org-read-date-popup-calendar))
1867 (defcustom org-extend-today-until 0
1868 "The hour when your day really ends.
1869 This has influence for the following applications:
1870 - When switching the agenda to \"today\". It it is still earlier than
1871 the time given here, the day recognized as TODAY is actually yesterday.
1872 - When a date is read from the user and it is still before the time given
1873 here, the current date and time will be assumed to be yesterday, 23:59.
1875 FIXME:
1876 IMPORTANT: This is still a very experimental feature, it may disappear
1877 again or it may be extended to mean more things."
1878 :group 'org-time
1879 :type 'number)
1881 (defcustom org-edit-timestamp-down-means-later nil
1882 "Non-nil means, S-down will increase the time in a time stamp.
1883 When nil, S-up will increase."
1884 :group 'org-time
1885 :type 'boolean)
1887 (defcustom org-calendar-follow-timestamp-change t
1888 "Non-nil means, make the calendar window follow timestamp changes.
1889 When a timestamp is modified and the calendar window is visible, it will be
1890 moved to the new date."
1891 :group 'org-time
1892 :type 'boolean)
1894 (defcustom org-clock-heading-function nil
1895 "When non-nil, should be a function to create `org-clock-heading'.
1896 This is the string shown in the mode line when a clock is running.
1897 The function is called with point at the beginning of the headline."
1898 :group 'org-time ; FIXME: Should we have a separate group????
1899 :type 'function)
1901 (defgroup org-tags nil
1902 "Options concerning tags in Org-mode."
1903 :tag "Org Tags"
1904 :group 'org)
1906 (defcustom org-tag-alist nil
1907 "List of tags allowed in Org-mode files.
1908 When this list is nil, Org-mode will base TAG input on what is already in the
1909 buffer.
1910 The value of this variable is an alist, the car of each entry must be a
1911 keyword as a string, the cdr may be a character that is used to select
1912 that tag through the fast-tag-selection interface.
1913 See the manual for details."
1914 :group 'org-tags
1915 :type '(repeat
1916 (choice
1917 (cons (string :tag "Tag name")
1918 (character :tag "Access char"))
1919 (const :tag "Start radio group" (:startgroup))
1920 (const :tag "End radio group" (:endgroup)))))
1922 (defcustom org-use-fast-tag-selection 'auto
1923 "Non-nil means, use fast tag selection scheme.
1924 This is a special interface to select and deselect tags with single keys.
1925 When nil, fast selection is never used.
1926 When the symbol `auto', fast selection is used if and only if selection
1927 characters for tags have been configured, either through the variable
1928 `org-tag-alist' or through a #+TAGS line in the buffer.
1929 When t, fast selection is always used and selection keys are assigned
1930 automatically if necessary."
1931 :group 'org-tags
1932 :type '(choice
1933 (const :tag "Always" t)
1934 (const :tag "Never" nil)
1935 (const :tag "When selection characters are configured" 'auto)))
1937 (defcustom org-fast-tag-selection-single-key nil
1938 "Non-nil means, fast tag selection exits after first change.
1939 When nil, you have to press RET to exit it.
1940 During fast tag selection, you can toggle this flag with `C-c'.
1941 This variable can also have the value `expert'. In this case, the window
1942 displaying the tags menu is not even shown, until you press C-c again."
1943 :group 'org-tags
1944 :type '(choice
1945 (const :tag "No" nil)
1946 (const :tag "Yes" t)
1947 (const :tag "Expert" expert)))
1949 (defvar org-fast-tag-selection-include-todo nil
1950 "Non-nil means, fast tags selection interface will also offer TODO states.
1951 This is an undocumented feature, you should not rely on it.")
1953 (defcustom org-tags-column -80
1954 "The column to which tags should be indented in a headline.
1955 If this number is positive, it specifies the column. If it is negative,
1956 it means that the tags should be flushright to that column. For example,
1957 -80 works well for a normal 80 character screen."
1958 :group 'org-tags
1959 :type 'integer)
1961 (defcustom org-auto-align-tags t
1962 "Non-nil means, realign tags after pro/demotion of TODO state change.
1963 These operations change the length of a headline and therefore shift
1964 the tags around. With this options turned on, after each such operation
1965 the tags are again aligned to `org-tags-column'."
1966 :group 'org-tags
1967 :type 'boolean)
1969 (defcustom org-use-tag-inheritance t
1970 "Non-nil means, tags in levels apply also for sublevels.
1971 When nil, only the tags directly given in a specific line apply there.
1972 If you turn off this option, you very likely want to turn on the
1973 companion option `org-tags-match-list-sublevels'."
1974 :group 'org-tags
1975 :type 'boolean)
1977 (defcustom org-tags-match-list-sublevels nil
1978 "Non-nil means list also sublevels of headlines matching tag search.
1979 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1980 the sublevels of a headline matching a tag search often also match
1981 the same search. Listing all of them can create very long lists.
1982 Setting this variable to nil causes subtrees of a match to be skipped.
1983 This option is off by default, because inheritance in on. If you turn
1984 inheritance off, you very likely want to turn this option on.
1986 As a special case, if the tag search is restricted to TODO items, the
1987 value of this variable is ignored and sublevels are always checked, to
1988 make sure all corresponding TODO items find their way into the list."
1989 :group 'org-tags
1990 :type 'boolean)
1992 (defvar org-tags-history nil
1993 "History of minibuffer reads for tags.")
1994 (defvar org-last-tags-completion-table nil
1995 "The last used completion table for tags.")
1996 (defvar org-after-tags-change-hook nil
1997 "Hook that is run after the tags in a line have changed.")
1999 (defgroup org-properties nil
2000 "Options concerning properties in Org-mode."
2001 :tag "Org Properties"
2002 :group 'org)
2004 (defcustom org-property-format "%-10s %s"
2005 "How property key/value pairs should be formatted by `indent-line'.
2006 When `indent-line' hits a property definition, it will format the line
2007 according to this format, mainly to make sure that the values are
2008 lined-up with respect to each other."
2009 :group 'org-properties
2010 :type 'string)
2012 (defcustom org-use-property-inheritance nil
2013 "Non-nil means, properties apply also for sublevels.
2014 This setting is only relevant during property searches, not when querying
2015 an entry with `org-entry-get'. To retrieve a property with inheritance,
2016 you need to call `org-entry-get' with the inheritance flag.
2017 Turning this on can cause significant overhead when doing a search, so
2018 this is turned off by default.
2019 When nil, only the properties directly given in the current entry count.
2020 The value may also be a list of properties that shouldhave inheritance.
2022 However, note that some special properties use inheritance under special
2023 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2024 and the properties ending in \"_ALL\" when they are used as descriptor
2025 for valid values of a property."
2026 :group 'org-properties
2027 :type '(choice
2028 (const :tag "Not" nil)
2029 (const :tag "Always" nil)
2030 (repeat :tag "Specific properties")))
2032 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2033 "The default column format, if no other format has been defined.
2034 This variable can be set on the per-file basis by inserting a line
2036 #+COLUMNS: %25ITEM ....."
2037 :group 'org-properties
2038 :type 'string)
2040 (defcustom org-global-properties nil
2041 "List of property/value pairs that can be inherited by any entry.
2042 You can set buffer-local values for this by adding lines like
2044 #+PROPERTY: NAME VALUE"
2045 :group 'org-properties
2046 :type '(repeat
2047 (cons (string :tag "Property")
2048 (string :tag "Value"))))
2050 (defvar org-local-properties nil
2051 "List of property/value pairs that can be inherited by any entry.
2052 Valid for the current buffer.
2053 This variable is populated from #+PROPERTY lines.")
2055 (defgroup org-agenda nil
2056 "Options concerning agenda views in Org-mode."
2057 :tag "Org Agenda"
2058 :group 'org)
2060 (defvar org-category nil
2061 "Variable used by org files to set a category for agenda display.
2062 Such files should use a file variable to set it, for example
2064 # -*- mode: org; org-category: \"ELisp\"
2066 or contain a special line
2068 #+CATEGORY: ELisp
2070 If the file does not specify a category, then file's base name
2071 is used instead.")
2072 (make-variable-buffer-local 'org-category)
2074 (defcustom org-agenda-files nil
2075 "The files to be used for agenda display.
2076 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2077 \\[org-remove-file]. You can also use customize to edit the list.
2079 If an entry is a directory, all files in that directory that are matched by
2080 `org-agenda-file-regexp' will be part of the file list.
2082 If the value of the variable is not a list but a single file name, then
2083 the list of agenda files is actually stored and maintained in that file, one
2084 agenda file per line."
2085 :group 'org-agenda
2086 :type '(choice
2087 (repeat :tag "List of files and directories" file)
2088 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2090 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2091 "Regular expression to match files for `org-agenda-files'.
2092 If any element in the list in that variable contains a directory instead
2093 of a normal file, all files in that directory that are matched by this
2094 regular expression will be included."
2095 :group 'org-agenda
2096 :type 'regexp)
2098 (defcustom org-agenda-skip-unavailable-files nil
2099 "t means to just skip non-reachable files in `org-agenda-files'.
2100 Nil means to remove them, after a query, from the list."
2101 :group 'org-agenda
2102 :type 'boolean)
2104 (defcustom org-agenda-multi-occur-extra-files nil
2105 "List of extra files to be searched by `org-occur-in-agenda-files'.
2106 The files in `org-agenda-files' are always searched."
2107 :group 'org-agenda
2108 :type '(repeat file))
2110 (defcustom org-agenda-confirm-kill 1
2111 "When set, remote killing from the agenda buffer needs confirmation.
2112 When t, a confirmation is always needed. When a number N, confirmation is
2113 only needed when the text to be killed contains more than N non-white lines."
2114 :group 'org-agenda
2115 :type '(choice
2116 (const :tag "Never" nil)
2117 (const :tag "Always" t)
2118 (number :tag "When more than N lines")))
2120 (defcustom org-calendar-to-agenda-key [?c]
2121 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2122 The command `org-calendar-goto-agenda' will be bound to this key. The
2123 default is the character `c' because then `c' can be used to switch back and
2124 forth between agenda and calendar."
2125 :group 'org-agenda
2126 :type 'sexp)
2128 (defcustom org-agenda-compact-blocks nil
2129 "Non-nil means, make the block agenda more compact.
2130 This is done by leaving out unnecessary lines."
2131 :group 'org-agenda
2132 :type nil)
2134 (defgroup org-agenda-export nil
2135 "Options concerning exporting agenda views in Org-mode."
2136 :tag "Org Agenda Export"
2137 :group 'org-agenda)
2139 (defcustom org-agenda-with-colors t
2140 "Non-nil means, use colors in agenda views."
2141 :group 'org-agenda-export
2142 :type 'boolean)
2144 (defcustom org-agenda-exporter-settings nil
2145 "Alist of variable/value pairs that should be active during agenda export.
2146 This is a good place to set uptions for ps-print and for htmlize."
2147 :group 'org-agenda-export
2148 :type '(repeat
2149 (list
2150 (variable)
2151 (sexp :tag "Value"))))
2153 (defcustom org-agenda-export-html-style ""
2154 "The style specification for exported HTML Agenda files.
2155 If this variable contains a string, it will replace the default <style>
2156 section as produced by `htmlize'.
2157 Since there are different ways of setting style information, this variable
2158 needs to contain the full HTML structure to provide a style, including the
2159 surrounding HTML tags. The style specifications should include definitions
2160 the fonts used by the agenda, here is an example:
2162 <style type=\"text/css\">
2163 p { font-weight: normal; color: gray; }
2164 .org-agenda-structure {
2165 font-size: 110%;
2166 color: #003399;
2167 font-weight: 600;
2169 .org-todo {
2170 color: #cc6666;Week-agenda:
2171 font-weight: bold;
2173 .org-done {
2174 color: #339933;
2176 .title { text-align: center; }
2177 .todo, .deadline { color: red; }
2178 .done { color: green; }
2179 </style>
2181 or, if you want to keep the style in a file,
2183 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2185 As the value of this option simply gets inserted into the HTML <head> header,
2186 you can \"misuse\" it to also add other text to the header. However,
2187 <style>...</style> is required, if not present the variable will be ignored."
2188 :group 'org-agenda-export
2189 :group 'org-export-html
2190 :type 'string)
2192 (defgroup org-agenda-custom-commands nil
2193 "Options concerning agenda views in Org-mode."
2194 :tag "Org Agenda Custom Commands"
2195 :group 'org-agenda)
2197 (defcustom org-agenda-custom-commands nil
2198 "Custom commands for the agenda.
2199 These commands will be offered on the splash screen displayed by the
2200 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2202 (key desc type match options files)
2204 key The key (one or more characters as a string) to be associated
2205 with the command.
2206 desc A description of the commend, when omitted or nil, a default
2207 description is built using MATCH.
2208 type The command type, any of the following symbols:
2209 todo Entries with a specific TODO keyword, in all agenda files.
2210 tags Tags match in all agenda files.
2211 tags-todo Tags match in all agenda files, TODO entries only.
2212 todo-tree Sparse tree of specific TODO keyword in *current* file.
2213 tags-tree Sparse tree with all tags matches in *current* file.
2214 occur-tree Occur sparse tree for *current* file.
2215 ... A user-defined function.
2216 match What to search for:
2217 - a single keyword for TODO keyword searches
2218 - a tags match expression for tags searches
2219 - a regular expression for occur searches
2220 options A list of option settings, similar to that in a let form, so like
2221 this: ((opt1 val1) (opt2 val2) ...)
2222 files A list of files file to write the produced agenda buffer to
2223 with the command `org-store-agenda-views'.
2224 If a file name ends in \".html\", an HTML version of the buffer
2225 is written out. If it ends in \".ps\", a postscript version is
2226 produced. Otherwide, only the plain text is written to the file.
2228 You can also define a set of commands, to create a composite agenda buffer.
2229 In this case, an entry looks like this:
2231 (key desc (cmd1 cmd2 ...) general-options file)
2233 where
2235 desc A description string to be displayed in the dispatcher menu.
2236 cmd An agenda command, similar to the above. However, tree commands
2237 are no allowed, but instead you can get agenda and global todo list.
2238 So valid commands for a set are:
2239 (agenda)
2240 (alltodo)
2241 (stuck)
2242 (todo \"match\" options files)
2243 (tags \"match\" options files)
2244 (tags-todo \"match\" options files)
2246 Each command can carry a list of options, and another set of options can be
2247 given for the whole set of commands. Individual command options take
2248 precedence over the general options.
2250 When using several characters as key to a command, the first characters
2251 are prefix commands. For the dispatcher to display useful information, you
2252 should provide a description for the prefix, like
2254 (setq org-agenda-custom-commands
2255 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2256 (\"hl\" tags \"+HOME+Lisa\")
2257 (\"hp\" tags \"+HOME+Peter\")
2258 (\"hk\" tags \"+HOME+Kim\")))"
2259 :group 'org-agenda-custom-commands
2260 :type '(repeat
2261 (choice :value ("a" "" tags "" nil)
2262 (list :tag "Single command"
2263 (string :tag "Access Key(s) ")
2264 (option (string :tag "Description"))
2265 (choice
2266 (const :tag "Agenda" agenda)
2267 (const :tag "TODO list" alltodo)
2268 (const :tag "Stuck projects" stuck)
2269 (const :tag "Tags search (all agenda files)" tags)
2270 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2271 (const :tag "TODO keyword search (all agenda files)" todo)
2272 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2273 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2274 (const :tag "Occur tree (current buffer)" occur-tree)
2275 (sexp :tag "Other, user-defined function"))
2276 (string :tag "Match")
2277 (repeat :tag "Local options"
2278 (list (variable :tag "Option") (sexp :tag "Value")))
2279 (option (repeat :tag "Export" (file :tag "Export to"))))
2280 (list :tag "Command series, all agenda files"
2281 (string :tag "Access Key(s)")
2282 (string :tag "Description ")
2283 (repeat
2284 (choice
2285 (const :tag "Agenda" (agenda))
2286 (const :tag "TODO list" (alltodo))
2287 (const :tag "Stuck projects" (stuck))
2288 (list :tag "Tags search"
2289 (const :format "" tags)
2290 (string :tag "Match")
2291 (repeat :tag "Local options"
2292 (list (variable :tag "Option")
2293 (sexp :tag "Value"))))
2295 (list :tag "Tags search, TODO entries only"
2296 (const :format "" tags-todo)
2297 (string :tag "Match")
2298 (repeat :tag "Local options"
2299 (list (variable :tag "Option")
2300 (sexp :tag "Value"))))
2302 (list :tag "TODO keyword search"
2303 (const :format "" todo)
2304 (string :tag "Match")
2305 (repeat :tag "Local options"
2306 (list (variable :tag "Option")
2307 (sexp :tag "Value"))))
2309 (list :tag "Other, user-defined function"
2310 (symbol :tag "function")
2311 (string :tag "Match")
2312 (repeat :tag "Local options"
2313 (list (variable :tag "Option")
2314 (sexp :tag "Value"))))))
2316 (repeat :tag "General options"
2317 (list (variable :tag "Option")
2318 (sexp :tag "Value")))
2319 (option (repeat :tag "Export" (file :tag "Export to"))))
2320 (cons :tag "Prefix key documentation"
2321 (string :tag "Access Key(s)")
2322 (string :tag "Description ")))))
2324 (defcustom org-stuck-projects
2325 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2326 "How to identify stuck projects.
2327 This is a list of four items:
2328 1. A tags/todo matcher string that is used to identify a project.
2329 The entire tree below a headline matched by this is considered one project.
2330 2. A list of TODO keywords identifying non-stuck projects.
2331 If the project subtree contains any headline with one of these todo
2332 keywords, the project is considered to be not stuck. If you specify
2333 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2334 3. A list of tags identifying non-stuck projects.
2335 If the project subtree contains any headline with one of these tags,
2336 the project is considered to be not stuck. If you specify \"*\" as
2337 a tag, any tag will mark the project unstuck.
2338 4. An arbitrary regular expression matching non-stuck projects.
2340 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2341 or `C-c a #' to produce the list."
2342 :group 'org-agenda-custom-commands
2343 :type '(list
2344 (string :tag "Tags/TODO match to identify a project")
2345 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2346 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2347 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2350 (defgroup org-agenda-skip nil
2351 "Options concerning skipping parts of agenda files."
2352 :tag "Org Agenda Skip"
2353 :group 'org-agenda)
2355 (defcustom org-agenda-todo-list-sublevels t
2356 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2357 When nil, the sublevels of a TODO entry are not checked, resulting in
2358 potentially much shorter TODO lists."
2359 :group 'org-agenda-skip
2360 :group 'org-todo
2361 :type 'boolean)
2363 (defcustom org-agenda-todo-ignore-with-date nil
2364 "Non-nil means, don't show entries with a date in the global todo list.
2365 You can use this if you prefer to mark mere appointments with a TODO keyword,
2366 but don't want them to show up in the TODO list.
2367 When this is set, it also covers deadlines and scheduled items, the settings
2368 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2369 will be ignored."
2370 :group 'org-agenda-skip
2371 :group 'org-todo
2372 :type 'boolean)
2374 (defcustom org-agenda-todo-ignore-scheduled nil
2375 "Non-nil means, don't show scheduled entries in the global todo list.
2376 The idea behind this is that by scheduling it, you have already taken care
2377 of this item.
2378 See also `org-agenda-todo-ignore-with-date'."
2379 :group 'org-agenda-skip
2380 :group 'org-todo
2381 :type 'boolean)
2383 (defcustom org-agenda-todo-ignore-deadlines nil
2384 "Non-nil means, don't show near deadline entries in the global todo list.
2385 Near means closer than `org-deadline-warning-days' days.
2386 The idea behind this is that such items will appear in the agenda anyway.
2387 See also `org-agenda-todo-ignore-with-date'."
2388 :group 'org-agenda-skip
2389 :group 'org-todo
2390 :type 'boolean)
2392 (defcustom org-agenda-skip-scheduled-if-done nil
2393 "Non-nil means don't show scheduled items in agenda when they are done.
2394 This is relevant for the daily/weekly agenda, not for the TODO list. And
2395 it applies only to the actual date of the scheduling. Warnings about
2396 an item with a past scheduling dates are always turned off when the item
2397 is DONE."
2398 :group 'org-agenda-skip
2399 :type 'boolean)
2401 (defcustom org-agenda-skip-deadline-if-done nil
2402 "Non-nil means don't show deadines when the corresponding item is done.
2403 When nil, the deadline is still shown and should give you a happy feeling.
2404 This is relevant for the daily/weekly agenda. And it applied only to the
2405 actualy date of the deadline. Warnings about approching and past-due
2406 deadlines are always turned off when the item is DONE."
2407 :group 'org-agenda-skip
2408 :type 'boolean)
2410 (defcustom org-agenda-skip-timestamp-if-done nil
2411 "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2412 :group 'org-agenda-skip
2413 :type 'boolean)
2415 (defcustom org-timeline-show-empty-dates 3
2416 "Non-nil means, `org-timeline' also shows dates without an entry.
2417 When nil, only the days which actually have entries are shown.
2418 When t, all days between the first and the last date are shown.
2419 When an integer, show also empty dates, but if there is a gap of more than
2420 N days, just insert a special line indicating the size of the gap."
2421 :group 'org-agenda-skip
2422 :type '(choice
2423 (const :tag "None" nil)
2424 (const :tag "All" t)
2425 (number :tag "at most")))
2428 (defgroup org-agenda-startup nil
2429 "Options concerning initial settings in the Agenda in Org Mode."
2430 :tag "Org Agenda Startup"
2431 :group 'org-agenda)
2433 (defcustom org-finalize-agenda-hook nil
2434 "Hook run just before displaying an agenda buffer."
2435 :group 'org-agenda-startup
2436 :type 'hook)
2438 (defcustom org-agenda-mouse-1-follows-link nil
2439 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2440 A longer mouse click will still set point. Does not wortk on XEmacs.
2441 Needs to be set before org.el is loaded."
2442 :group 'org-agenda-startup
2443 :type 'boolean)
2445 (defcustom org-agenda-start-with-follow-mode nil
2446 "The initial value of follow-mode in a newly created agenda window."
2447 :group 'org-agenda-startup
2448 :type 'boolean)
2450 (defgroup org-agenda-windows nil
2451 "Options concerning the windows used by the Agenda in Org Mode."
2452 :tag "Org Agenda Windows"
2453 :group 'org-agenda)
2455 (defcustom org-agenda-window-setup 'reorganize-frame
2456 "How the agenda buffer should be displayed.
2457 Possible values for this option are:
2459 current-window Show agenda in the current window, keeping all other windows.
2460 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2461 other-window Use `switch-to-buffer-other-window' to display agenda.
2462 reorganize-frame Show only two windows on the current frame, the current
2463 window and the agenda.
2464 See also the variable `org-agenda-restore-windows-after-quit'."
2465 :group 'org-agenda-windows
2466 :type '(choice
2467 (const current-window)
2468 (const other-frame)
2469 (const other-window)
2470 (const reorganize-frame)))
2472 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2473 "The min and max height of the agenda window as a fraction of frame height.
2474 The value of the variable is a cons cell with two numbers between 0 and 1.
2475 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2476 :group 'org-agenda-windows
2477 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2479 (defcustom org-agenda-restore-windows-after-quit nil
2480 "Non-nil means, restore window configuration open exiting agenda.
2481 Before the window configuration is changed for displaying the agenda,
2482 the current status is recorded. When the agenda is exited with
2483 `q' or `x' and this option is set, the old state is restored. If
2484 `org-agenda-window-setup' is `other-frame', the value of this
2485 option will be ignored.."
2486 :group 'org-agenda-windows
2487 :type 'boolean)
2489 (defcustom org-indirect-buffer-display 'other-window
2490 "How should indirect tree buffers be displayed?
2491 This applies to indirect buffers created with the commands
2492 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2493 Valid values are:
2494 current-window Display in the current window
2495 other-window Just display in another window.
2496 dedicated-frame Create one new frame, and re-use it each time.
2497 new-frame Make a new frame each time. Note that in this case
2498 previously-made indirect buffers are kept, and you need to
2499 kill these buffers yourself."
2500 :group 'org-structure
2501 :group 'org-agenda-windows
2502 :type '(choice
2503 (const :tag "In current window" current-window)
2504 (const :tag "In current frame, other window" other-window)
2505 (const :tag "Each time a new frame" new-frame)
2506 (const :tag "One dedicated frame" dedicated-frame)))
2508 (defgroup org-agenda-daily/weekly nil
2509 "Options concerning the daily/weekly agenda."
2510 :tag "Org Agenda Daily/Weekly"
2511 :group 'org-agenda)
2513 (defcustom org-agenda-ndays 7
2514 "Number of days to include in overview display.
2515 Should be 1 or 7."
2516 :group 'org-agenda-daily/weekly
2517 :type 'number)
2519 (defcustom org-agenda-start-on-weekday 1
2520 "Non-nil means, start the overview always on the specified weekday.
2521 0 denotes Sunday, 1 denotes Monday etc.
2522 When nil, always start on the current day."
2523 :group 'org-agenda-daily/weekly
2524 :type '(choice (const :tag "Today" nil)
2525 (number :tag "Weekday No.")))
2527 (defcustom org-agenda-show-all-dates t
2528 "Non-nil means, `org-agenda' shows every day in the selected range.
2529 When nil, only the days which actually have entries are shown."
2530 :group 'org-agenda-daily/weekly
2531 :type 'boolean)
2533 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2534 "Format string for displaying dates in the agenda.
2535 Used by the daily/weekly agenda and by the timeline. This should be
2536 a format string understood by `format-time-string', or a function returning
2537 the formatted date as a string. The function must take a single argument,
2538 a calendar-style date list like (month day year)."
2539 :group 'org-agenda-daily/weekly
2540 :type '(choice
2541 (string :tag "Format string")
2542 (function :tag "Function")))
2544 (defun org-agenda-format-date-aligned (date)
2545 "Format a date string for display in the daily/weekly agenda, or timeline.
2546 This function makes sure that dates are aligned for easy reading."
2547 (format "%-9s %2d %s %4d"
2548 (calendar-day-name date)
2549 (extract-calendar-day date)
2550 (calendar-month-name (extract-calendar-month date))
2551 (extract-calendar-year date)))
2553 (defcustom org-agenda-include-diary nil
2554 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2555 :group 'org-agenda-daily/weekly
2556 :type 'boolean)
2558 (defcustom org-agenda-include-all-todo nil
2559 "Set means weekly/daily agenda will always contain all TODO entries.
2560 The TODO entries will be listed at the top of the agenda, before
2561 the entries for specific days."
2562 :group 'org-agenda-daily/weekly
2563 :type 'boolean)
2565 (defcustom org-agenda-repeating-timestamp-show-all t
2566 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2567 When nil, only one occurence is shown, either today or the
2568 nearest into the future."
2569 :group 'org-agenda-daily/weekly
2570 :type 'boolean)
2572 (defcustom org-deadline-warning-days 14
2573 "No. of days before expiration during which a deadline becomes active.
2574 This variable governs the display in sparse trees and in the agenda.
2575 When negative, it means use this number (the absolute value of it)
2576 even if a deadline has a different individual lead time specified."
2577 :group 'org-time
2578 :group 'org-agenda-daily/weekly
2579 :type 'number)
2581 (defcustom org-scheduled-past-days 10000
2582 "No. of days to continue listing scheduled items that are not marked DONE.
2583 When an item is scheduled on a date, it shows up in the agenda on this
2584 day and will be listed until it is marked done for the number of days
2585 given here."
2586 :group 'org-agenda-daily/weekly
2587 :type 'number)
2589 (defgroup org-agenda-time-grid nil
2590 "Options concerning the time grid in the Org-mode Agenda."
2591 :tag "Org Agenda Time Grid"
2592 :group 'org-agenda)
2594 (defcustom org-agenda-use-time-grid t
2595 "Non-nil means, show a time grid in the agenda schedule.
2596 A time grid is a set of lines for specific times (like every two hours between
2597 8:00 and 20:00). The items scheduled for a day at specific times are
2598 sorted in between these lines.
2599 For details about when the grid will be shown, and what it will look like, see
2600 the variable `org-agenda-time-grid'."
2601 :group 'org-agenda-time-grid
2602 :type 'boolean)
2604 (defcustom org-agenda-time-grid
2605 '((daily today require-timed)
2606 "----------------"
2607 (800 1000 1200 1400 1600 1800 2000))
2609 "The settings for time grid for agenda display.
2610 This is a list of three items. The first item is again a list. It contains
2611 symbols specifying conditions when the grid should be displayed:
2613 daily if the agenda shows a single day
2614 weekly if the agenda shows an entire week
2615 today show grid on current date, independent of daily/weekly display
2616 require-timed show grid only if at least one item has a time specification
2618 The second item is a string which will be places behing the grid time.
2620 The third item is a list of integers, indicating the times that should have
2621 a grid line."
2622 :group 'org-agenda-time-grid
2623 :type
2624 '(list
2625 (set :greedy t :tag "Grid Display Options"
2626 (const :tag "Show grid in single day agenda display" daily)
2627 (const :tag "Show grid in weekly agenda display" weekly)
2628 (const :tag "Always show grid for today" today)
2629 (const :tag "Show grid only if any timed entries are present"
2630 require-timed)
2631 (const :tag "Skip grid times already present in an entry"
2632 remove-match))
2633 (string :tag "Grid String")
2634 (repeat :tag "Grid Times" (integer :tag "Time"))))
2636 (defgroup org-agenda-sorting nil
2637 "Options concerning sorting in the Org-mode Agenda."
2638 :tag "Org Agenda Sorting"
2639 :group 'org-agenda)
2641 (defconst org-sorting-choice
2642 '(choice
2643 (const time-up) (const time-down)
2644 (const category-keep) (const category-up) (const category-down)
2645 (const tag-down) (const tag-up)
2646 (const priority-up) (const priority-down))
2647 "Sorting choices.")
2649 (defcustom org-agenda-sorting-strategy
2650 '((agenda time-up category-keep priority-down)
2651 (todo category-keep priority-down)
2652 (tags category-keep priority-down))
2653 "Sorting structure for the agenda items of a single day.
2654 This is a list of symbols which will be used in sequence to determine
2655 if an entry should be listed before another entry. The following
2656 symbols are recognized:
2658 time-up Put entries with time-of-day indications first, early first
2659 time-down Put entries with time-of-day indications first, late first
2660 category-keep Keep the default order of categories, corresponding to the
2661 sequence in `org-agenda-files'.
2662 category-up Sort alphabetically by category, A-Z.
2663 category-down Sort alphabetically by category, Z-A.
2664 tag-up Sort alphabetically by last tag, A-Z.
2665 tag-down Sort alphabetically by last tag, Z-A.
2666 priority-up Sort numerically by priority, high priority last.
2667 priority-down Sort numerically by priority, high priority first.
2669 The different possibilities will be tried in sequence, and testing stops
2670 if one comparison returns a \"not-equal\". For example, the default
2671 '(time-up category-keep priority-down)
2672 means: Pull out all entries having a specified time of day and sort them,
2673 in order to make a time schedule for the current day the first thing in the
2674 agenda listing for the day. Of the entries without a time indication, keep
2675 the grouped in categories, don't sort the categories, but keep them in
2676 the sequence given in `org-agenda-files'. Within each category sort by
2677 priority.
2679 Leaving out `category-keep' would mean that items will be sorted across
2680 categories by priority.
2682 Instead of a single list, this can also be a set of list for specific
2683 contents, with a context symbol in the car of the list, any of
2684 `agenda', `todo', `tags' for the corresponding agenda views."
2685 :group 'org-agenda-sorting
2686 :type `(choice
2687 (repeat :tag "General" org-sorting-choice)
2688 (list :tag "Individually"
2689 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2690 (repeat ,org-sorting-choice))
2691 (cons (const :tag "Strategy for TODO lists" todo)
2692 (repeat ,org-sorting-choice))
2693 (cons (const :tag "Strategy for Tags matches" tags)
2694 (repeat ,org-sorting-choice)))))
2696 (defcustom org-sort-agenda-notime-is-late t
2697 "Non-nil means, items without time are considered late.
2698 This is only relevant for sorting. When t, items which have no explicit
2699 time like 15:30 will be considered as 99:01, i.e. later than any items which
2700 do have a time. When nil, the default time is before 0:00. You can use this
2701 option to decide if the schedule for today should come before or after timeless
2702 agenda entries."
2703 :group 'org-agenda-sorting
2704 :type 'boolean)
2706 (defgroup org-agenda-line-format nil
2707 "Options concerning the entry prefix in the Org-mode agenda display."
2708 :tag "Org Agenda Line Format"
2709 :group 'org-agenda)
2711 (defcustom org-agenda-prefix-format
2712 '((agenda . " %-12:c%?-12t% s")
2713 (timeline . " % s")
2714 (todo . " %-12:c")
2715 (tags . " %-12:c"))
2716 "Format specifications for the prefix of items in the agenda views.
2717 An alist with four entries, for the different agenda types. The keys to the
2718 sublists are `agenda', `timeline', `todo', and `tags'. The values
2719 are format strings.
2720 This format works similar to a printf format, with the following meaning:
2722 %c the category of the item, \"Diary\" for entries from the diary, or
2723 as given by the CATEGORY keyword or derived from the file name.
2724 %T the *last* tag of the item. Last because inherited tags come
2725 first in the list.
2726 %t the time-of-day specification if one applies to the entry, in the
2727 format HH:MM
2728 %s Scheduling/Deadline information, a short string
2730 All specifiers work basically like the standard `%s' of printf, but may
2731 contain two additional characters: A question mark just after the `%' and
2732 a whitespace/punctuation character just before the final letter.
2734 If the first character after `%' is a question mark, the entire field
2735 will only be included if the corresponding value applies to the
2736 current entry. This is useful for fields which should have fixed
2737 width when present, but zero width when absent. For example,
2738 \"%?-12t\" will result in a 12 character time field if a time of the
2739 day is specified, but will completely disappear in entries which do
2740 not contain a time.
2742 If there is punctuation or whitespace character just before the final
2743 format letter, this character will be appended to the field value if
2744 the value is not empty. For example, the format \"%-12:c\" leads to
2745 \"Diary: \" if the category is \"Diary\". If the category were be
2746 empty, no additional colon would be interted.
2748 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2749 - Indent the line with two space characters
2750 - Give the category in a 12 chars wide field, padded with whitespace on
2751 the right (because of `-'). Append a colon if there is a category
2752 (because of `:').
2753 - If there is a time-of-day, put it into a 12 chars wide field. If no
2754 time, don't put in an empty field, just skip it (because of '?').
2755 - Finally, put the scheduling information and append a whitespace.
2757 As another example, if you don't want the time-of-day of entries in
2758 the prefix, you could use:
2760 (setq org-agenda-prefix-format \" %-11:c% s\")
2762 See also the variables `org-agenda-remove-times-when-in-prefix' and
2763 `org-agenda-remove-tags'."
2764 :type '(choice
2765 (string :tag "General format")
2766 (list :greedy t :tag "View dependent"
2767 (cons (const agenda) (string :tag "Format"))
2768 (cons (const timeline) (string :tag "Format"))
2769 (cons (const todo) (string :tag "Format"))
2770 (cons (const tags) (string :tag "Format"))))
2771 :group 'org-agenda-line-format)
2773 (defvar org-prefix-format-compiled nil
2774 "The compiled version of the most recently used prefix format.
2775 See the variable `org-agenda-prefix-format'.")
2777 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2778 "Text preceeding scheduled items in the agenda view.
2779 THis is a list with two strings. The first applies when the item is
2780 scheduled on the current day. The second applies when it has been scheduled
2781 previously, it may contain a %d to capture how many days ago the item was
2782 scheduled."
2783 :group 'org-agenda-line-format
2784 :type '(list
2785 (string :tag "Scheduled today ")
2786 (string :tag "Scheduled previously")))
2788 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2789 "Text preceeding deadline items in the agenda view.
2790 This is a list with two strings. The first applies when the item has its
2791 deadline on the current day. The second applies when it is in the past or
2792 in the future, it may contain %d to capture how many days away the deadline
2793 is (was)."
2794 :group 'org-agenda-line-format
2795 :type '(list
2796 (string :tag "Deadline today ")
2797 (string :tag "Deadline relative")))
2799 (defcustom org-agenda-remove-times-when-in-prefix t
2800 "Non-nil means, remove duplicate time specifications in agenda items.
2801 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2802 time-of-day specification in a headline or diary entry is extracted and
2803 placed into the prefix. If this option is non-nil, the original specification
2804 \(a timestamp or -range, or just a plain time(range) specification like
2805 11:30-4pm) will be removed for agenda display. This makes the agenda less
2806 cluttered.
2807 The option can be t or nil. It may also be the symbol `beg', indicating
2808 that the time should only be removed what it is located at the beginning of
2809 the headline/diary entry."
2810 :group 'org-agenda-line-format
2811 :type '(choice
2812 (const :tag "Always" t)
2813 (const :tag "Never" nil)
2814 (const :tag "When at beginning of entry" beg)))
2817 (defcustom org-agenda-default-appointment-duration nil
2818 "Default duration for appointments that only have a starting time.
2819 When nil, no duration is specified in such cases.
2820 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2821 :group 'org-agenda-line-format
2822 :type '(choice
2823 (integer :tag "Minutes")
2824 (const :tag "No default duration")))
2827 (defcustom org-agenda-remove-tags nil
2828 "Non-nil means, remove the tags from the headline copy in the agenda.
2829 When this is the symbol `prefix', only remove tags when
2830 `org-agenda-prefix-format' contains a `%T' specifier."
2831 :group 'org-agenda-line-format
2832 :type '(choice
2833 (const :tag "Always" t)
2834 (const :tag "Never" nil)
2835 (const :tag "When prefix format contains %T" prefix)))
2837 (if (fboundp 'defvaralias)
2838 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2839 'org-agenda-remove-tags))
2841 (defcustom org-agenda-tags-column -80
2842 "Shift tags in agenda items to this column.
2843 If this number is positive, it specifies the column. If it is negative,
2844 it means that the tags should be flushright to that column. For example,
2845 -80 works well for a normal 80 character screen."
2846 :group 'org-agenda-line-format
2847 :type 'integer)
2849 (if (fboundp 'defvaralias)
2850 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2852 (defcustom org-agenda-fontify-priorities t
2853 "Non-nil means, highlight low and high priorities in agenda.
2854 When t, the highest priority entries are bold, lowest priority italic.
2855 This may also be an association list of priority faces. The face may be
2856 a names face, or a list like `(:background \"Red\")'."
2857 :group 'org-agenda-line-format
2858 :type '(choice
2859 (const :tag "Never" nil)
2860 (const :tag "Defaults" t)
2861 (repeat :tag "Specify"
2862 (list (character :tag "Priority" :value ?A)
2863 (sexp :tag "face")))))
2865 (defgroup org-latex nil
2866 "Options for embedding LaTeX code into Org-mode"
2867 :tag "Org LaTeX"
2868 :group 'org)
2870 (defcustom org-format-latex-options
2871 '(:foreground default :background default :scale 1.0
2872 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2873 :matchers ("begin" "$" "$$" "\\(" "\\["))
2874 "Options for creating images from LaTeX fragments.
2875 This is a property list with the following properties:
2876 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2877 `default' means use the forground of the default face.
2878 :background the background color, or \"Transparent\".
2879 `default' means use the background of the default face.
2880 :scale a scaling factor for the size of the images
2881 :html-foreground, :html-background, :html-scale
2882 The same numbers for HTML export.
2883 :matchers a list indicating which matchers should be used to
2884 find LaTeX fragments. Valid members of this list are:
2885 \"begin\" find environments
2886 \"$\" find math expressions surrounded by $...$
2887 \"$$\" find math expressions surrounded by $$....$$
2888 \"\\(\" find math expressions surrounded by \\(...\\)
2889 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2890 :group 'org-latex
2891 :type 'plist)
2893 (defcustom org-format-latex-header "\\documentclass{article}
2894 \\usepackage{fullpage} % do not remove
2895 \\usepackage{amssymb}
2896 \\usepackage[usenames]{color}
2897 \\usepackage{amsmath}
2898 \\usepackage{latexsym}
2899 \\usepackage[mathscr]{eucal}
2900 \\pagestyle{empty} % do not remove"
2901 "The document header used for processing LaTeX fragments."
2902 :group 'org-latex
2903 :type 'string)
2905 (defgroup org-export nil
2906 "Options for exporting org-listings."
2907 :tag "Org Export"
2908 :group 'org)
2910 (defgroup org-export-general nil
2911 "General options for exporting Org-mode files."
2912 :tag "Org Export General"
2913 :group 'org-export)
2915 ;; FIXME
2916 (defvar org-export-publishing-directory nil)
2918 (defcustom org-export-with-special-strings t
2919 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2920 When this option is turned on, these strings will be exported as:
2922 Org HTML LaTeX
2923 -----+----------+--------
2924 \\- &shy; \\-
2925 -- &ndash; --
2926 --- &mdash; ---
2927 ... &hellip; \ldots
2929 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2930 :group 'org-export-translation
2931 :type 'boolean)
2933 (defcustom org-export-language-setup
2934 '(("en" "Author" "Date" "Table of Contents")
2935 ("cs" "Autor" "Datum" "Obsah")
2936 ("da" "Ophavsmand" "Dato" "Indhold")
2937 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2938 ("es" "Autor" "Fecha" "\xcdndice")
2939 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2940 ("it" "Autore" "Data" "Indice")
2941 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2942 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2943 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2944 "Terms used in export text, translated to different languages.
2945 Use the variable `org-export-default-language' to set the language,
2946 or use the +OPTION lines for a per-file setting."
2947 :group 'org-export-general
2948 :type '(repeat
2949 (list
2950 (string :tag "HTML language tag")
2951 (string :tag "Author")
2952 (string :tag "Date")
2953 (string :tag "Table of Contents"))))
2955 (defcustom org-export-default-language "en"
2956 "The default language of HTML export, as a string.
2957 This should have an association in `org-export-language-setup'."
2958 :group 'org-export-general
2959 :type 'string)
2961 (defcustom org-export-skip-text-before-1st-heading t
2962 "Non-nil means, skip all text before the first headline when exporting.
2963 When nil, that text is exported as well."
2964 :group 'org-export-general
2965 :type 'boolean)
2967 (defcustom org-export-headline-levels 3
2968 "The last level which is still exported as a headline.
2969 Inferior levels will produce itemize lists when exported.
2970 Note that a numeric prefix argument to an exporter function overrides
2971 this setting.
2973 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2974 :group 'org-export-general
2975 :type 'number)
2977 (defcustom org-export-with-section-numbers t
2978 "Non-nil means, add section numbers to headlines when exporting.
2980 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2981 :group 'org-export-general
2982 :type 'boolean)
2984 (defcustom org-export-with-toc t
2985 "Non-nil means, create a table of contents in exported files.
2986 The TOC contains headlines with levels up to`org-export-headline-levels'.
2987 When an integer, include levels up to N in the toc, this may then be
2988 different from `org-export-headline-levels', but it will not be allowed
2989 to be larger than the number of headline levels.
2990 When nil, no table of contents is made.
2992 Headlines which contain any TODO items will be marked with \"(*)\" in
2993 ASCII export, and with red color in HTML output, if the option
2994 `org-export-mark-todo-in-toc' is set.
2996 In HTML output, the TOC will be clickable.
2998 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2999 or \"toc:3\"."
3000 :group 'org-export-general
3001 :type '(choice
3002 (const :tag "No Table of Contents" nil)
3003 (const :tag "Full Table of Contents" t)
3004 (integer :tag "TOC to level")))
3006 (defcustom org-export-mark-todo-in-toc nil
3007 "Non-nil means, mark TOC lines that contain any open TODO items."
3008 :group 'org-export-general
3009 :type 'boolean)
3011 (defcustom org-export-preserve-breaks nil
3012 "Non-nil means, preserve all line breaks when exporting.
3013 Normally, in HTML output paragraphs will be reformatted. In ASCII
3014 export, line breaks will always be preserved, regardless of this variable.
3016 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3017 :group 'org-export-general
3018 :type 'boolean)
3020 (defcustom org-export-with-archived-trees 'headline
3021 "Whether subtrees with the ARCHIVE tag should be exported.
3022 This can have three different values
3023 nil Do not export, pretend this tree is not present
3024 t Do export the entire tree
3025 headline Only export the headline, but skip the tree below it."
3026 :group 'org-export-general
3027 :group 'org-archive
3028 :type '(choice
3029 (const :tag "not at all" nil)
3030 (const :tag "headline only" 'headline)
3031 (const :tag "entirely" t)))
3033 (defcustom org-export-author-info t
3034 "Non-nil means, insert author name and email into the exported file.
3036 This option can also be set with the +OPTIONS line,
3037 e.g. \"author-info:nil\"."
3038 :group 'org-export-general
3039 :type 'boolean)
3041 (defcustom org-export-time-stamp-file t
3042 "Non-nil means, insert a time stamp into the exported file.
3043 The time stamp shows when the file was created.
3045 This option can also be set with the +OPTIONS line,
3046 e.g. \"timestamp:nil\"."
3047 :group 'org-export-general
3048 :type 'boolean)
3050 (defcustom org-export-with-timestamps t
3051 "If nil, do not export time stamps and associated keywords."
3052 :group 'org-export-general
3053 :type 'boolean)
3055 (defcustom org-export-remove-timestamps-from-toc t
3056 "If nil, remove timestamps from the table of contents entries."
3057 :group 'org-export-general
3058 :type 'boolean)
3060 (defcustom org-export-with-tags 'not-in-toc
3061 "If nil, do not export tags, just remove them from headlines.
3062 If this is the symbol `not-in-toc', tags will be removed from table of
3063 contents entries, but still be shown in the headlines of the document.
3065 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3066 :group 'org-export-general
3067 :type '(choice
3068 (const :tag "Off" nil)
3069 (const :tag "Not in TOC" not-in-toc)
3070 (const :tag "On" t)))
3072 (defcustom org-export-with-drawers nil
3073 "Non-nil means, export with drawers like the property drawer.
3074 When t, all drawers are exported. This may also be a list of
3075 drawer names to export."
3076 :group 'org-export-general
3077 :type '(choice
3078 (const :tag "All drawers" t)
3079 (const :tag "None" nil)
3080 (repeat :tag "Selected drawers"
3081 (string :tag "Drawer name"))))
3083 (defgroup org-export-translation nil
3084 "Options for translating special ascii sequences for the export backends."
3085 :tag "Org Export Translation"
3086 :group 'org-export)
3088 (defcustom org-export-with-emphasize t
3089 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3090 If the export target supports emphasizing text, the word will be
3091 typeset in bold, italic, or underlined, respectively. Works only for
3092 single words, but you can say: I *really* *mean* *this*.
3093 Not all export backends support this.
3095 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3096 :group 'org-export-translation
3097 :type 'boolean)
3099 (defcustom org-export-with-footnotes t
3100 "If nil, export [1] as a footnote marker.
3101 Lines starting with [1] will be formatted as footnotes.
3103 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3104 :group 'org-export-translation
3105 :type 'boolean)
3107 (defcustom org-export-with-sub-superscripts t
3108 "Non-nil means, interpret \"_\" and \"^\" for export.
3109 When this option is turned on, you can use TeX-like syntax for sub- and
3110 superscripts. Several characters after \"_\" or \"^\" will be
3111 considered as a single item - so grouping with {} is normally not
3112 needed. For example, the following things will be parsed as single
3113 sub- or superscripts.
3115 10^24 or 10^tau several digits will be considered 1 item.
3116 10^-12 or 10^-tau a leading sign with digits or a word
3117 x^2-y^3 will be read as x^2 - y^3, because items are
3118 terminated by almost any nonword/nondigit char.
3119 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3121 Still, ambiguity is possible - so when in doubt use {} to enclose the
3122 sub/superscript. If you set this variable to the symbol `{}',
3123 the braces are *required* in order to trigger interpretations as
3124 sub/superscript. This can be helpful in documents that need \"_\"
3125 frequently in plain text.
3127 Not all export backends support this, but HTML does.
3129 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3130 :group 'org-export-translation
3131 :type '(choice
3132 (const :tag "Always interpret" t)
3133 (const :tag "Only with braces" {})
3134 (const :tag "Never interpret" nil)))
3136 (defcustom org-export-with-special-strings t
3137 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3138 When this option is turned on, these strings will be exported as:
3140 \\- : &shy;
3141 -- : &ndash;
3142 --- : &mdash;
3144 Not all export backends support this, but HTML does.
3146 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3147 :group 'org-export-translation
3148 :type 'boolean)
3150 (defcustom org-export-with-TeX-macros t
3151 "Non-nil means, interpret simple TeX-like macros when exporting.
3152 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3153 No only real TeX macros will work here, but the standard HTML entities
3154 for math can be used as macro names as well. For a list of supported
3155 names in HTML export, see the constant `org-html-entities'.
3156 Not all export backends support this.
3158 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3159 :group 'org-export-translation
3160 :group 'org-export-latex
3161 :type 'boolean)
3163 (defcustom org-export-with-LaTeX-fragments nil
3164 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3165 When set, the exporter will find LaTeX environments if the \\begin line is
3166 the first non-white thing on a line. It will also find the math delimiters
3167 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3168 display math.
3170 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3171 :group 'org-export-translation
3172 :group 'org-export-latex
3173 :type 'boolean)
3175 (defcustom org-export-with-fixed-width t
3176 "Non-nil means, lines starting with \":\" will be in fixed width font.
3177 This can be used to have pre-formatted text, fragments of code etc. For
3178 example:
3179 : ;; Some Lisp examples
3180 : (while (defc cnt)
3181 : (ding))
3182 will be looking just like this in also HTML. See also the QUOTE keyword.
3183 Not all export backends support this.
3185 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3186 :group 'org-export-translation
3187 :type 'boolean)
3189 (defcustom org-match-sexp-depth 3
3190 "Number of stacked braces for sub/superscript matching.
3191 This has to be set before loading org.el to be effective."
3192 :group 'org-export-translation
3193 :type 'integer)
3195 (defgroup org-export-tables nil
3196 "Options for exporting tables in Org-mode."
3197 :tag "Org Export Tables"
3198 :group 'org-export)
3200 (defcustom org-export-with-tables t
3201 "If non-nil, lines starting with \"|\" define a table.
3202 For example:
3204 | Name | Address | Birthday |
3205 |-------------+----------+-----------|
3206 | Arthur Dent | England | 29.2.2100 |
3208 Not all export backends support this.
3210 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3211 :group 'org-export-tables
3212 :type 'boolean)
3214 (defcustom org-export-highlight-first-table-line t
3215 "Non-nil means, highlight the first table line.
3216 In HTML export, this means use <th> instead of <td>.
3217 In tables created with table.el, this applies to the first table line.
3218 In Org-mode tables, all lines before the first horizontal separator
3219 line will be formatted with <th> tags."
3220 :group 'org-export-tables
3221 :type 'boolean)
3223 (defcustom org-export-table-remove-special-lines t
3224 "Remove special lines and marking characters in calculating tables.
3225 This removes the special marking character column from tables that are set
3226 up for spreadsheet calculations. It also removes the entire lines
3227 marked with `!', `_', or `^'. The lines with `$' are kept, because
3228 the values of constants may be useful to have."
3229 :group 'org-export-tables
3230 :type 'boolean)
3232 (defcustom org-export-prefer-native-exporter-for-tables nil
3233 "Non-nil means, always export tables created with table.el natively.
3234 Natively means, use the HTML code generator in table.el.
3235 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3236 the table does not use row- or column-spanning). This has the
3237 advantage, that the automatic HTML conversions for math symbols and
3238 sub/superscripts can be applied. Org-mode's HTML generator is also
3239 much faster."
3240 :group 'org-export-tables
3241 :type 'boolean)
3243 (defgroup org-export-ascii nil
3244 "Options specific for ASCII export of Org-mode files."
3245 :tag "Org Export ASCII"
3246 :group 'org-export)
3248 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3249 "Characters for underlining headings in ASCII export.
3250 In the given sequence, these characters will be used for level 1, 2, ..."
3251 :group 'org-export-ascii
3252 :type '(repeat character))
3254 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3255 "Bullet characters for headlines converted to lists in ASCII export.
3256 The first character is is used for the first lest level generated in this
3257 way, and so on. If there are more levels than characters given here,
3258 the list will be repeated.
3259 Note that plain lists will keep the same bullets as the have in the
3260 Org-mode file."
3261 :group 'org-export-ascii
3262 :type '(repeat character))
3264 (defgroup org-export-xml nil
3265 "Options specific for XML export of Org-mode files."
3266 :tag "Org Export XML"
3267 :group 'org-export)
3269 (defgroup org-export-html nil
3270 "Options specific for HTML export of Org-mode files."
3271 :tag "Org Export HTML"
3272 :group 'org-export)
3274 (defcustom org-export-html-coding-system nil
3276 :group 'org-export-html
3277 :type 'coding-system)
3279 (defcustom org-export-html-extension "html"
3280 "The extension for exported HTML files."
3281 :group 'org-export-html
3282 :type 'string)
3284 (defcustom org-export-html-style
3285 "<style type=\"text/css\">
3286 html {
3287 font-family: Times, serif;
3288 font-size: 12pt;
3290 .title { text-align: center; }
3291 .todo { color: red; }
3292 .done { color: green; }
3293 .timestamp { color: grey }
3294 .timestamp-kwd { color: CadetBlue }
3295 .tag { background-color:lightblue; font-weight:normal }
3296 .target { background-color: lavender; }
3297 pre {
3298 border: 1pt solid #AEBDCC;
3299 background-color: #F3F5F7;
3300 padding: 5pt;
3301 font-family: courier, monospace;
3303 table { border-collapse: collapse; }
3304 td, th {
3305 vertical-align: top;
3306 <!--border: 1pt solid #ADB9CC;-->
3308 </style>"
3309 "The default style specification for exported HTML files.
3310 Since there are different ways of setting style information, this variable
3311 needs to contain the full HTML structure to provide a style, including the
3312 surrounding HTML tags. The style specifications should include definitions
3313 for new classes todo, done, title, and deadline. For example, legal values
3314 would be:
3316 <style type=\"text/css\">
3317 p { font-weight: normal; color: gray; }
3318 h1 { color: black; }
3319 .title { text-align: center; }
3320 .todo, .deadline { color: red; }
3321 .done { color: green; }
3322 </style>
3324 or, if you want to keep the style in a file,
3326 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3328 As the value of this option simply gets inserted into the HTML <head> header,
3329 you can \"misuse\" it to add arbitrary text to the header."
3330 :group 'org-export-html
3331 :type 'string)
3334 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3335 "Format for typesetting the document title in HTML export."
3336 :group 'org-export-html
3337 :type 'string)
3339 (defcustom org-export-html-toplevel-hlevel 2
3340 "The <H> level for level 1 headings in HTML export."
3341 :group 'org-export-html
3342 :type 'string)
3344 (defcustom org-export-html-link-org-files-as-html t
3345 "Non-nil means, make file links to `file.org' point to `file.html'.
3346 When org-mode is exporting an org-mode file to HTML, links to
3347 non-html files are directly put into a href tag in HTML.
3348 However, links to other Org-mode files (recognized by the
3349 extension `.org.) should become links to the corresponding html
3350 file, assuming that the linked org-mode file will also be
3351 converted to HTML.
3352 When nil, the links still point to the plain `.org' file."
3353 :group 'org-export-html
3354 :type 'boolean)
3356 (defcustom org-export-html-inline-images 'maybe
3357 "Non-nil means, inline images into exported HTML pages.
3358 This is done using an <img> tag. When nil, an anchor with href is used to
3359 link to the image. If this option is `maybe', then images in links with
3360 an empty description will be inlined, while images with a description will
3361 be linked only."
3362 :group 'org-export-html
3363 :type '(choice (const :tag "Never" nil)
3364 (const :tag "Always" t)
3365 (const :tag "When there is no description" maybe)))
3367 ;; FIXME: rename
3368 (defcustom org-export-html-expand t
3369 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3370 When nil, these tags will be exported as plain text and therefore
3371 not be interpreted by a browser.
3373 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3374 :group 'org-export-html
3375 :type 'boolean)
3377 (defcustom org-export-html-table-tag
3378 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3379 "The HTML tag that is used to start a table.
3380 This must be a <table> tag, but you may change the options like
3381 borders and spacing."
3382 :group 'org-export-html
3383 :type 'string)
3385 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3386 "The opening tag for table header fields.
3387 This is customizable so that alignment options can be specified."
3388 :group 'org-export-tables
3389 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3391 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3392 "The opening tag for table data fields.
3393 This is customizable so that alignment options can be specified."
3394 :group 'org-export-tables
3395 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3397 (defcustom org-export-html-with-timestamp nil
3398 "If non-nil, write `org-export-html-html-helper-timestamp'
3399 into the exported HTML text. Otherwise, the buffer will just be saved
3400 to a file."
3401 :group 'org-export-html
3402 :type 'boolean)
3404 (defcustom org-export-html-html-helper-timestamp
3405 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3406 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3407 :group 'org-export-html
3408 :type 'string)
3410 (defgroup org-export-icalendar nil
3411 "Options specific for iCalendar export of Org-mode files."
3412 :tag "Org Export iCalendar"
3413 :group 'org-export)
3415 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3416 "The file name for the iCalendar file covering all agenda files.
3417 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3418 The file name should be absolute, the file will be overwritten without warning."
3419 :group 'org-export-icalendar
3420 :type 'file)
3422 (defcustom org-icalendar-include-todo nil
3423 "Non-nil means, export to iCalendar files should also cover TODO items."
3424 :group 'org-export-icalendar
3425 :type '(choice
3426 (const :tag "None" nil)
3427 (const :tag "Unfinished" t)
3428 (const :tag "All" all)))
3430 (defcustom org-icalendar-include-sexps t
3431 "Non-nil means, export to iCalendar files should also cover sexp entries.
3432 These are entries like in the diary, but directly in an Org-mode file."
3433 :group 'org-export-icalendar
3434 :type 'boolean)
3436 (defcustom org-icalendar-include-body 100
3437 "Amount of text below headline to be included in iCalendar export.
3438 This is a number of characters that should maximally be included.
3439 Properties, scheduling and clocking lines will always be removed.
3440 The text will be inserted into the DESCRIPTION field."
3441 :group 'org-export-icalendar
3442 :type '(choice
3443 (const :tag "Nothing" nil)
3444 (const :tag "Everything" t)
3445 (integer :tag "Max characters")))
3447 (defcustom org-icalendar-combined-name "OrgMode"
3448 "Calendar name for the combined iCalendar representing all agenda files."
3449 :group 'org-export-icalendar
3450 :type 'string)
3452 (defgroup org-font-lock nil
3453 "Font-lock settings for highlighting in Org-mode."
3454 :tag "Org Font Lock"
3455 :group 'org)
3457 (defcustom org-level-color-stars-only nil
3458 "Non-nil means fontify only the stars in each headline.
3459 When nil, the entire headline is fontified.
3460 Changing it requires restart of `font-lock-mode' to become effective
3461 also in regions already fontified."
3462 :group 'org-font-lock
3463 :type 'boolean)
3465 (defcustom org-hide-leading-stars nil
3466 "Non-nil means, hide the first N-1 stars in a headline.
3467 This works by using the face `org-hide' for these stars. This
3468 face is white for a light background, and black for a dark
3469 background. You may have to customize the face `org-hide' to
3470 make this work.
3471 Changing it requires restart of `font-lock-mode' to become effective
3472 also in regions already fontified.
3473 You may also set this on a per-file basis by adding one of the following
3474 lines to the buffer:
3476 #+STARTUP: hidestars
3477 #+STARTUP: showstars"
3478 :group 'org-font-lock
3479 :type 'boolean)
3481 (defcustom org-fontify-done-headline nil
3482 "Non-nil means, change the face of a headline if it is marked DONE.
3483 Normally, only the TODO/DONE keyword indicates the state of a headline.
3484 When this is non-nil, the headline after the keyword is set to the
3485 `org-headline-done' as an additional indication."
3486 :group 'org-font-lock
3487 :type 'boolean)
3489 (defcustom org-fontify-emphasized-text t
3490 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3491 Changing this variable requires a restart of Emacs to take effect."
3492 :group 'org-font-lock
3493 :type 'boolean)
3495 (defcustom org-highlight-latex-fragments-and-specials nil
3496 "Non-nil means, fontify what is treated specially by the exporters."
3497 :group 'org-font-lock
3498 :type 'boolean)
3500 (defcustom org-hide-emphasis-markers nil
3501 "Non-nil mean font-lock should hide the emphasis marker characters."
3502 :group 'org-font-lock
3503 :type 'boolean)
3505 (defvar org-emph-re nil
3506 "Regular expression for matching emphasis.")
3507 (defvar org-verbatim-re nil
3508 "Regular expression for matching verbatim text.")
3509 (defvar org-emphasis-regexp-components) ; defined just below
3510 (defvar org-emphasis-alist) ; defined just below
3511 (defun org-set-emph-re (var val)
3512 "Set variable and compute the emphasis regular expression."
3513 (set var val)
3514 (when (and (boundp 'org-emphasis-alist)
3515 (boundp 'org-emphasis-regexp-components)
3516 org-emphasis-alist org-emphasis-regexp-components)
3517 (let* ((e org-emphasis-regexp-components)
3518 (pre (car e))
3519 (post (nth 1 e))
3520 (border (nth 2 e))
3521 (body (nth 3 e))
3522 (nl (nth 4 e))
3523 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3524 (body1 (concat body "*?"))
3525 (markers (mapconcat 'car org-emphasis-alist ""))
3526 (vmarkers (mapconcat
3527 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3528 org-emphasis-alist "")))
3529 ;; make sure special characters appear at the right position in the class
3530 (if (string-match "\\^" markers)
3531 (setq markers (concat (replace-match "" t t markers) "^")))
3532 (if (string-match "-" markers)
3533 (setq markers (concat (replace-match "" t t markers) "-")))
3534 (if (string-match "\\^" vmarkers)
3535 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3536 (if (string-match "-" vmarkers)
3537 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3538 (if (> nl 0)
3539 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3540 (int-to-string nl) "\\}")))
3541 ;; Make the regexp
3542 (setq org-emph-re
3543 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3544 "\\("
3545 "\\([" markers "]\\)"
3546 "\\("
3547 "[^" border "]\\|"
3548 "[^" border (if (and nil stacked) markers) "]"
3549 body1
3550 "[^" border (if (and nil stacked) markers) "]"
3551 "\\)"
3552 "\\3\\)"
3553 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3554 (setq org-verbatim-re
3555 (concat "\\([" pre "]\\|^\\)"
3556 "\\("
3557 "\\([" vmarkers "]\\)"
3558 "\\("
3559 "[^" border "]\\|"
3560 "[^" border "]"
3561 body1
3562 "[^" border "]"
3563 "\\)"
3564 "\\3\\)"
3565 "\\([" post "]\\|$\\)")))))
3567 (defcustom org-emphasis-regexp-components
3568 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3569 "Components used to build the regular expression for emphasis.
3570 This is a list with 6 entries. Terminology: In an emphasis string
3571 like \" *strong word* \", we call the initial space PREMATCH, the final
3572 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3573 and \"trong wor\" is the body. The different components in this variable
3574 specify what is allowed/forbidden in each part:
3576 pre Chars allowed as prematch. Beginning of line will be allowed too.
3577 post Chars allowed as postmatch. End of line will be allowed too.
3578 border The chars *forbidden* as border characters.
3579 body-regexp A regexp like \".\" to match a body character. Don't use
3580 non-shy groups here, and don't allow newline here.
3581 newline The maximum number of newlines allowed in an emphasis exp.
3583 Use customize to modify this, or restart Emacs after changing it."
3584 :group 'org-font-lock
3585 :set 'org-set-emph-re
3586 :type '(list
3587 (sexp :tag "Allowed chars in pre ")
3588 (sexp :tag "Allowed chars in post ")
3589 (sexp :tag "Forbidden chars in border ")
3590 (sexp :tag "Regexp for body ")
3591 (integer :tag "number of newlines allowed")
3592 (option (boolean :tag "Stacking (DISABLED) "))))
3594 (defcustom org-emphasis-alist
3595 '(("*" bold "<b>" "</b>")
3596 ("/" italic "<i>" "</i>")
3597 ("_" underline "<u>" "</u>")
3598 ("=" org-code "<code>" "</code>" verbatim)
3599 ("~" org-verbatim "" "" verbatim)
3600 ("+" (:strike-through t) "<del>" "</del>")
3602 "Special syntax for emphasized text.
3603 Text starting and ending with a special character will be emphasized, for
3604 example *bold*, _underlined_ and /italic/. This variable sets the marker
3605 characters, the face to be used by font-lock for highlighting in Org-mode
3606 Emacs buffers, and the HTML tags to be used for this.
3607 Use customize to modify this, or restart Emacs after changing it."
3608 :group 'org-font-lock
3609 :set 'org-set-emph-re
3610 :type '(repeat
3611 (list
3612 (string :tag "Marker character")
3613 (choice
3614 (face :tag "Font-lock-face")
3615 (plist :tag "Face property list"))
3616 (string :tag "HTML start tag")
3617 (string :tag "HTML end tag")
3618 (option (const verbatim)))))
3620 ;;; The faces
3622 (defgroup org-faces nil
3623 "Faces in Org-mode."
3624 :tag "Org Faces"
3625 :group 'org-font-lock)
3627 (defun org-compatible-face (inherits specs)
3628 "Make a compatible face specification.
3629 If INHERITS is an existing face and if the Emacs version supports it,
3630 just inherit the face. If not, use SPECS to define the face.
3631 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3632 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3633 to the top of the list. The `min-colors' attribute will be removed from
3634 any other entries, and any resulting duplicates will be removed entirely."
3635 (cond
3636 ((and inherits (facep inherits)
3637 (not (featurep 'xemacs)) (> emacs-major-version 22))
3638 ;; In Emacs 23, we use inheritance where possible.
3639 ;; We only do this in Emacs 23, because only there the outline
3640 ;; faces have been changed to the original org-mode-level-faces.
3641 (list (list t :inherit inherits)))
3642 ((or (featurep 'xemacs) (< emacs-major-version 22))
3643 ;; These do not understand the `min-colors' attribute.
3644 (let (r e a)
3645 (while (setq e (pop specs))
3646 (cond
3647 ((memq (car e) '(t default)) (push e r))
3648 ((setq a (member '(min-colors 8) (car e)))
3649 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3650 (cdr e)))))
3651 ((setq a (assq 'min-colors (car e)))
3652 (setq e (cons (delq a (car e)) (cdr e)))
3653 (or (assoc (car e) r) (push e r)))
3654 (t (or (assoc (car e) r) (push e r)))))
3655 (nreverse r)))
3656 (t specs)))
3657 (put 'org-compatible-face 'lisp-indent-function 1)
3659 (defface org-hide
3660 '((((background light)) (:foreground "white"))
3661 (((background dark)) (:foreground "black")))
3662 "Face used to hide leading stars in headlines.
3663 The forground color of this face should be equal to the background
3664 color of the frame."
3665 :group 'org-faces)
3667 (defface org-level-1 ;; font-lock-function-name-face
3668 (org-compatible-face 'outline-1
3669 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3670 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3671 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3672 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3673 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3674 (t (:bold t))))
3675 "Face used for level 1 headlines."
3676 :group 'org-faces)
3678 (defface org-level-2 ;; font-lock-variable-name-face
3679 (org-compatible-face 'outline-2
3680 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3681 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3682 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3683 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3684 (t (:bold t))))
3685 "Face used for level 2 headlines."
3686 :group 'org-faces)
3688 (defface org-level-3 ;; font-lock-keyword-face
3689 (org-compatible-face 'outline-3
3690 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3691 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3692 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3693 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3694 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3695 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3696 (t (:bold t))))
3697 "Face used for level 3 headlines."
3698 :group 'org-faces)
3700 (defface org-level-4 ;; font-lock-comment-face
3701 (org-compatible-face 'outline-4
3702 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3703 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3704 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3705 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3706 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3707 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3708 (t (:bold t))))
3709 "Face used for level 4 headlines."
3710 :group 'org-faces)
3712 (defface org-level-5 ;; font-lock-type-face
3713 (org-compatible-face 'outline-5
3714 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3715 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3716 (((class color) (min-colors 8)) (:foreground "green"))))
3717 "Face used for level 5 headlines."
3718 :group 'org-faces)
3720 (defface org-level-6 ;; font-lock-constant-face
3721 (org-compatible-face 'outline-6
3722 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3723 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3724 (((class color) (min-colors 8)) (:foreground "magenta"))))
3725 "Face used for level 6 headlines."
3726 :group 'org-faces)
3728 (defface org-level-7 ;; font-lock-builtin-face
3729 (org-compatible-face 'outline-7
3730 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3731 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3732 (((class color) (min-colors 8)) (:foreground "blue"))))
3733 "Face used for level 7 headlines."
3734 :group 'org-faces)
3736 (defface org-level-8 ;; font-lock-string-face
3737 (org-compatible-face 'outline-8
3738 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3739 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3740 (((class color) (min-colors 8)) (:foreground "green"))))
3741 "Face used for level 8 headlines."
3742 :group 'org-faces)
3744 (defface org-special-keyword ;; font-lock-string-face
3745 (org-compatible-face nil
3746 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3747 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3748 (t (:italic t))))
3749 "Face used for special keywords."
3750 :group 'org-faces)
3752 (defface org-drawer ;; font-lock-function-name-face
3753 (org-compatible-face nil
3754 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3755 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3756 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3757 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3758 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3759 (t (:bold t))))
3760 "Face used for drawers."
3761 :group 'org-faces)
3763 (defface org-property-value nil
3764 "Face used for the value of a property."
3765 :group 'org-faces)
3767 (defface org-column
3768 (org-compatible-face nil
3769 '((((class color) (min-colors 16) (background light))
3770 (:background "grey90"))
3771 (((class color) (min-colors 16) (background dark))
3772 (:background "grey30"))
3773 (((class color) (min-colors 8))
3774 (:background "cyan" :foreground "black"))
3775 (t (:inverse-video t))))
3776 "Face for column display of entry properties."
3777 :group 'org-faces)
3779 (when (fboundp 'set-face-attribute)
3780 ;; Make sure that a fixed-width face is used when we have a column table.
3781 (set-face-attribute 'org-column nil
3782 :height (face-attribute 'default :height)
3783 :family (face-attribute 'default :family)))
3785 (defface org-warning
3786 (org-compatible-face 'font-lock-warning-face
3787 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3788 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3789 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3790 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3791 (t (:bold t))))
3792 "Face for deadlines and TODO keywords."
3793 :group 'org-faces)
3795 (defface org-archived ; similar to shadow
3796 (org-compatible-face 'shadow
3797 '((((class color grayscale) (min-colors 88) (background light))
3798 (:foreground "grey50"))
3799 (((class color grayscale) (min-colors 88) (background dark))
3800 (:foreground "grey70"))
3801 (((class color) (min-colors 8) (background light))
3802 (:foreground "green"))
3803 (((class color) (min-colors 8) (background dark))
3804 (:foreground "yellow"))))
3805 "Face for headline with the ARCHIVE tag."
3806 :group 'org-faces)
3808 (defface org-link
3809 '((((class color) (background light)) (:foreground "Purple" :underline t))
3810 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3811 (t (:underline t)))
3812 "Face for links."
3813 :group 'org-faces)
3815 (defface org-ellipsis
3816 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3817 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3818 (t (:strike-through t)))
3819 "Face for the ellipsis in folded text."
3820 :group 'org-faces)
3822 (defface org-target
3823 '((((class color) (background light)) (:underline t))
3824 (((class color) (background dark)) (:underline t))
3825 (t (:underline t)))
3826 "Face for links."
3827 :group 'org-faces)
3829 (defface org-date
3830 '((((class color) (background light)) (:foreground "Purple" :underline t))
3831 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3832 (t (:underline t)))
3833 "Face for links."
3834 :group 'org-faces)
3836 (defface org-sexp-date
3837 '((((class color) (background light)) (:foreground "Purple"))
3838 (((class color) (background dark)) (:foreground "Cyan"))
3839 (t (:underline t)))
3840 "Face for links."
3841 :group 'org-faces)
3843 (defface org-tag
3844 '((t (:bold t)))
3845 "Face for tags."
3846 :group 'org-faces)
3848 (defface org-todo ; font-lock-warning-face
3849 (org-compatible-face nil
3850 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3851 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3852 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3853 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3854 (t (:inverse-video t :bold t))))
3855 "Face for TODO keywords."
3856 :group 'org-faces)
3858 (defface org-done ;; font-lock-type-face
3859 (org-compatible-face nil
3860 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3861 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3862 (((class color) (min-colors 8)) (:foreground "green"))
3863 (t (:bold t))))
3864 "Face used for todo keywords that indicate DONE items."
3865 :group 'org-faces)
3867 (defface org-headline-done ;; font-lock-string-face
3868 (org-compatible-face nil
3869 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3870 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3871 (((class color) (min-colors 8) (background light)) (:bold nil))))
3872 "Face used to indicate that a headline is DONE.
3873 This face is only used if `org-fontify-done-headline' is set. If applies
3874 to the part of the headline after the DONE keyword."
3875 :group 'org-faces)
3877 (defcustom org-todo-keyword-faces nil
3878 "Faces for specific TODO keywords.
3879 This is a list of cons cells, with TODO keywords in the car
3880 and faces in the cdr. The face can be a symbol, or a property
3881 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3882 :group 'org-faces
3883 :group 'org-todo
3884 :type '(repeat
3885 (cons
3886 (string :tag "keyword")
3887 (sexp :tag "face"))))
3889 (defface org-table ;; font-lock-function-name-face
3890 (org-compatible-face nil
3891 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3892 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3893 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3894 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3895 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3896 (((class color) (min-colors 8) (background dark)))))
3897 "Face used for tables."
3898 :group 'org-faces)
3900 (defface org-formula
3901 (org-compatible-face nil
3902 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3903 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3904 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3905 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3906 (t (:bold t :italic t))))
3907 "Face for formulas."
3908 :group 'org-faces)
3910 (defface org-code
3911 (org-compatible-face nil
3912 '((((class color grayscale) (min-colors 88) (background light))
3913 (:foreground "grey50"))
3914 (((class color grayscale) (min-colors 88) (background dark))
3915 (:foreground "grey70"))
3916 (((class color) (min-colors 8) (background light))
3917 (:foreground "green"))
3918 (((class color) (min-colors 8) (background dark))
3919 (:foreground "yellow"))))
3920 "Face for fixed-with text like code snippets."
3921 :group 'org-faces
3922 :version "22.1")
3924 (defface org-verbatim
3925 (org-compatible-face nil
3926 '((((class color grayscale) (min-colors 88) (background light))
3927 (:foreground "grey50" :underline t))
3928 (((class color grayscale) (min-colors 88) (background dark))
3929 (:foreground "grey70" :underline t))
3930 (((class color) (min-colors 8) (background light))
3931 (:foreground "green" :underline t))
3932 (((class color) (min-colors 8) (background dark))
3933 (:foreground "yellow" :underline t))))
3934 "Face for fixed-with text like code snippets."
3935 :group 'org-faces
3936 :version "22.1")
3938 (defface org-agenda-structure ;; font-lock-function-name-face
3939 (org-compatible-face nil
3940 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3941 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3942 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3943 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3944 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3945 (t (:bold t))))
3946 "Face used in agenda for captions and dates."
3947 :group 'org-faces)
3949 (defface org-scheduled-today
3950 (org-compatible-face nil
3951 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3952 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3953 (((class color) (min-colors 8)) (:foreground "green"))
3954 (t (:bold t :italic t))))
3955 "Face for items scheduled for a certain day."
3956 :group 'org-faces)
3958 (defface org-scheduled-previously
3959 (org-compatible-face nil
3960 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3961 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3962 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3963 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3964 (t (:bold t))))
3965 "Face for items scheduled previously, and not yet done."
3966 :group 'org-faces)
3968 (defface org-upcoming-deadline
3969 (org-compatible-face nil
3970 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3971 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3972 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3973 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3974 (t (:bold t))))
3975 "Face for items scheduled previously, and not yet done."
3976 :group 'org-faces)
3978 (defcustom org-agenda-deadline-faces
3979 '((1.0 . org-warning)
3980 (0.5 . org-upcoming-deadline)
3981 (0.0 . default))
3982 "Faces for showing deadlines in the agenda.
3983 This is a list of cons cells. The cdr of each cess is a face to be used,
3984 and it can also just be a like like '(:foreground \"yellow\").
3985 Each car is a fraction of the head-warning time that must have passed for
3986 this the face in the cdr to be used for display. The numbers must be
3987 given in descending order. The head-warning time is normally taken
3988 from `org-deadline-warning-days', but can also be specified in the deadline
3989 timestamp itself, like this:
3991 DEADLINE: <2007-08-13 Mon -8d>
3993 You may use d for days, w for weeks, m for months and y for years. Months
3994 and years will only be treated in an approximate fashion (30.4 days for a
3995 month and 365.24 days for a year)."
3996 :group 'org-faces
3997 :group 'org-agenda-daily/weekly
3998 :type '(repeat
3999 (cons
4000 (number :tag "Fraction of head-warning time passed")
4001 (sexp :tag "Face"))))
4003 ;; FIXME: this is not a good face yet.
4004 (defface org-agenda-restriction-lock
4005 (org-compatible-face nil
4006 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4007 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4008 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4009 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4010 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4011 (t (:inverse-video t))))
4012 "Face for showing the agenda restriction lock."
4013 :group 'org-faces)
4015 (defface org-time-grid ;; font-lock-variable-name-face
4016 (org-compatible-face nil
4017 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4018 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4019 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4020 "Face used for time grids."
4021 :group 'org-faces)
4023 (defconst org-level-faces
4024 '(org-level-1 org-level-2 org-level-3 org-level-4
4025 org-level-5 org-level-6 org-level-7 org-level-8
4028 (defcustom org-n-level-faces (length org-level-faces)
4029 "The number different faces to be used for headlines.
4030 Org-mode defines 8 different headline faces, so this can be at most 8.
4031 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4032 :type 'number
4033 :group 'org-faces)
4035 ;;; Variables for pre-computed regular expressions, all buffer local
4037 (defvar org-drawer-regexp nil
4038 "Matches first line of a hidden block.")
4039 (make-variable-buffer-local 'org-drawer-regexp)
4040 (defvar org-todo-regexp nil
4041 "Matches any of the TODO state keywords.")
4042 (make-variable-buffer-local 'org-todo-regexp)
4043 (defvar org-not-done-regexp nil
4044 "Matches any of the TODO state keywords except the last one.")
4045 (make-variable-buffer-local 'org-not-done-regexp)
4046 (defvar org-todo-line-regexp nil
4047 "Matches a headline and puts TODO state into group 2 if present.")
4048 (make-variable-buffer-local 'org-todo-line-regexp)
4049 (defvar org-complex-heading-regexp nil
4050 "Matches a headline and puts everything into groups:
4051 group 1: the stars
4052 group 2: The todo keyword, maybe
4053 group 3: Priority cookie
4054 group 4: True headline
4055 group 5: Tags")
4056 (make-variable-buffer-local 'org-complex-heading-regexp)
4057 (defvar org-todo-line-tags-regexp nil
4058 "Matches a headline and puts TODO state into group 2 if present.
4059 Also put tags into group 4 if tags are present.")
4060 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4061 (defvar org-nl-done-regexp nil
4062 "Matches newline followed by a headline with the DONE keyword.")
4063 (make-variable-buffer-local 'org-nl-done-regexp)
4064 (defvar org-looking-at-done-regexp nil
4065 "Matches the DONE keyword a point.")
4066 (make-variable-buffer-local 'org-looking-at-done-regexp)
4067 (defvar org-ds-keyword-length 12
4068 "Maximum length of the Deadline and SCHEDULED keywords.")
4069 (make-variable-buffer-local 'org-ds-keyword-length)
4070 (defvar org-deadline-regexp nil
4071 "Matches the DEADLINE keyword.")
4072 (make-variable-buffer-local 'org-deadline-regexp)
4073 (defvar org-deadline-time-regexp nil
4074 "Matches the DEADLINE keyword together with a time stamp.")
4075 (make-variable-buffer-local 'org-deadline-time-regexp)
4076 (defvar org-deadline-line-regexp nil
4077 "Matches the DEADLINE keyword and the rest of the line.")
4078 (make-variable-buffer-local 'org-deadline-line-regexp)
4079 (defvar org-scheduled-regexp nil
4080 "Matches the SCHEDULED keyword.")
4081 (make-variable-buffer-local 'org-scheduled-regexp)
4082 (defvar org-scheduled-time-regexp nil
4083 "Matches the SCHEDULED keyword together with a time stamp.")
4084 (make-variable-buffer-local 'org-scheduled-time-regexp)
4085 (defvar org-closed-time-regexp nil
4086 "Matches the CLOSED keyword together with a time stamp.")
4087 (make-variable-buffer-local 'org-closed-time-regexp)
4089 (defvar org-keyword-time-regexp nil
4090 "Matches any of the 4 keywords, together with the time stamp.")
4091 (make-variable-buffer-local 'org-keyword-time-regexp)
4092 (defvar org-keyword-time-not-clock-regexp nil
4093 "Matches any of the 3 keywords, together with the time stamp.")
4094 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4095 (defvar org-maybe-keyword-time-regexp nil
4096 "Matches a timestamp, possibly preceeded by a keyword.")
4097 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4098 (defvar org-planning-or-clock-line-re nil
4099 "Matches a line with planning or clock info.")
4100 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4102 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4103 rear-nonsticky t mouse-map t fontified t)
4104 "Properties to remove when a string without properties is wanted.")
4106 (defsubst org-match-string-no-properties (num &optional string)
4107 (if (featurep 'xemacs)
4108 (let ((s (match-string num string)))
4109 (remove-text-properties 0 (length s) org-rm-props s)
4111 (match-string-no-properties num string)))
4113 (defsubst org-no-properties (s)
4114 (if (fboundp 'set-text-properties)
4115 (set-text-properties 0 (length s) nil s)
4116 (remove-text-properties 0 (length s) org-rm-props s))
4119 (defsubst org-get-alist-option (option key)
4120 (cond ((eq key t) t)
4121 ((eq option t) t)
4122 ((assoc key option) (cdr (assoc key option)))
4123 (t (cdr (assq 'default option)))))
4125 (defsubst org-inhibit-invisibility ()
4126 "Modified `buffer-invisibility-spec' for Emacs 21.
4127 Some ops with invisible text do not work correctly on Emacs 21. For these
4128 we turn off invisibility temporarily. Use this in a `let' form."
4129 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4131 (defsubst org-set-local (var value)
4132 "Make VAR local in current buffer and set it to VALUE."
4133 (set (make-variable-buffer-local var) value))
4135 (defsubst org-mode-p ()
4136 "Check if the current buffer is in Org-mode."
4137 (eq major-mode 'org-mode))
4139 (defsubst org-last (list)
4140 "Return the last element of LIST."
4141 (car (last list)))
4143 (defun org-let (list &rest body)
4144 (eval (cons 'let (cons list body))))
4145 (put 'org-let 'lisp-indent-function 1)
4147 (defun org-let2 (list1 list2 &rest body)
4148 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4149 (put 'org-let2 'lisp-indent-function 2)
4150 (defconst org-startup-options
4151 '(("fold" org-startup-folded t)
4152 ("overview" org-startup-folded t)
4153 ("nofold" org-startup-folded nil)
4154 ("showall" org-startup-folded nil)
4155 ("content" org-startup-folded content)
4156 ("hidestars" org-hide-leading-stars t)
4157 ("showstars" org-hide-leading-stars nil)
4158 ("odd" org-odd-levels-only t)
4159 ("oddeven" org-odd-levels-only nil)
4160 ("align" org-startup-align-all-tables t)
4161 ("noalign" org-startup-align-all-tables nil)
4162 ("customtime" org-display-custom-times t)
4163 ("logging" org-log-done t)
4164 ("logdone" org-log-done t)
4165 ("nologging" org-log-done nil)
4166 ("lognotedone" org-log-done done push)
4167 ("lognotestate" org-log-done state push)
4168 ("lognoteclock-out" org-log-done clock-out push)
4169 ("logrepeat" org-log-repeat t)
4170 ("nologrepeat" org-log-repeat nil)
4171 ("constcgs" constants-unit-system cgs)
4172 ("constSI" constants-unit-system SI))
4173 "Variable associated with STARTUP options for org-mode.
4174 Each element is a list of three items: The startup options as written
4175 in the #+STARTUP line, the corresponding variable, and the value to
4176 set this variable to if the option is found. An optional forth element PUSH
4177 means to push this value onto the list in the variable.")
4179 (defun org-set-regexps-and-options ()
4180 "Precompute regular expressions for current buffer."
4181 (when (org-mode-p)
4182 (org-set-local 'org-todo-kwd-alist nil)
4183 (org-set-local 'org-todo-key-alist nil)
4184 (org-set-local 'org-todo-key-trigger nil)
4185 (org-set-local 'org-todo-keywords-1 nil)
4186 (org-set-local 'org-done-keywords nil)
4187 (org-set-local 'org-todo-heads nil)
4188 (org-set-local 'org-todo-sets nil)
4189 (org-set-local 'org-todo-log-states nil)
4190 (let ((re (org-make-options-regexp
4191 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4192 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4193 "CONSTANTS" "PROPERTY" "DRAWERS")))
4194 (splitre "[ \t]+")
4195 kwds kws0 kwsa key value cat arch tags const links hw dws
4196 tail sep kws1 prio props drawers
4197 ex log)
4198 (save-excursion
4199 (save-restriction
4200 (widen)
4201 (goto-char (point-min))
4202 (while (re-search-forward re nil t)
4203 (setq key (match-string 1) value (org-match-string-no-properties 2))
4204 (cond
4205 ((equal key "CATEGORY")
4206 (if (string-match "[ \t]+$" value)
4207 (setq value (replace-match "" t t value)))
4208 (setq cat value))
4209 ((member key '("SEQ_TODO" "TODO"))
4210 (push (cons 'sequence (org-split-string value splitre)) kwds))
4211 ((equal key "TYP_TODO")
4212 (push (cons 'type (org-split-string value splitre)) kwds))
4213 ((equal key "TAGS")
4214 (setq tags (append tags (org-split-string value splitre))))
4215 ((equal key "COLUMNS")
4216 (org-set-local 'org-columns-default-format value))
4217 ((equal key "LINK")
4218 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4219 (push (cons (match-string 1 value)
4220 (org-trim (match-string 2 value)))
4221 links)))
4222 ((equal key "PRIORITIES")
4223 (setq prio (org-split-string value " +")))
4224 ((equal key "PROPERTY")
4225 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4226 (push (cons (match-string 1 value) (match-string 2 value))
4227 props)))
4228 ((equal key "DRAWERS")
4229 (setq drawers (org-split-string value splitre)))
4230 ((equal key "CONSTANTS")
4231 (setq const (append const (org-split-string value splitre))))
4232 ((equal key "STARTUP")
4233 (let ((opts (org-split-string value splitre))
4234 l var val)
4235 (while (setq l (pop opts))
4236 (when (setq l (assoc l org-startup-options))
4237 (setq var (nth 1 l) val (nth 2 l))
4238 (if (not (nth 3 l))
4239 (set (make-local-variable var) val)
4240 (if (not (listp (symbol-value var)))
4241 (set (make-local-variable var) nil))
4242 (set (make-local-variable var) (symbol-value var))
4243 (add-to-list var val))))))
4244 ((equal key "ARCHIVE")
4245 (string-match " *$" value)
4246 (setq arch (replace-match "" t t value))
4247 (remove-text-properties 0 (length arch)
4248 '(face t fontified t) arch)))
4250 (when cat
4251 (org-set-local 'org-category (intern cat))
4252 (push (cons "CATEGORY" cat) props))
4253 (when prio
4254 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4255 (setq prio (mapcar 'string-to-char prio))
4256 (org-set-local 'org-highest-priority (nth 0 prio))
4257 (org-set-local 'org-lowest-priority (nth 1 prio))
4258 (org-set-local 'org-default-priority (nth 2 prio)))
4259 (and props (org-set-local 'org-local-properties (nreverse props)))
4260 (and drawers (org-set-local 'org-drawers drawers))
4261 (and arch (org-set-local 'org-archive-location arch))
4262 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4263 ;; Process the TODO keywords
4264 (unless kwds
4265 ;; Use the global values as if they had been given locally.
4266 (setq kwds (default-value 'org-todo-keywords))
4267 (if (stringp (car kwds))
4268 (setq kwds (list (cons org-todo-interpretation
4269 (default-value 'org-todo-keywords)))))
4270 (setq kwds (reverse kwds)))
4271 (setq kwds (nreverse kwds))
4272 (let (inter kws kw)
4273 (while (setq kws (pop kwds))
4274 (setq inter (pop kws) sep (member "|" kws)
4275 kws0 (delete "|" (copy-sequence kws))
4276 kwsa nil
4277 kws1 (mapcar
4278 (lambda (x)
4279 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4280 (progn
4281 (setq kw (match-string 1 x)
4282 ex (and (match-end 2) (match-string 2 x))
4283 log (and ex (string-match "@" ex))
4284 key (and ex (substring ex 0 1)))
4285 (if (equal key "@") (setq key nil))
4286 (push (cons kw (and key (string-to-char key))) kwsa)
4287 (and log (push kw org-todo-log-states))
4289 (error "Invalid TODO keyword %s" x)))
4290 kws0)
4291 kwsa (if kwsa (append '((:startgroup))
4292 (nreverse kwsa)
4293 '((:endgroup))))
4294 hw (car kws1)
4295 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4296 tail (list inter hw (car dws) (org-last dws)))
4297 (add-to-list 'org-todo-heads hw 'append)
4298 (push kws1 org-todo-sets)
4299 (setq org-done-keywords (append org-done-keywords dws nil))
4300 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4301 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4302 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4303 (setq org-todo-sets (nreverse org-todo-sets)
4304 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4305 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4306 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4307 ;; Process the constants
4308 (when const
4309 (let (e cst)
4310 (while (setq e (pop const))
4311 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4312 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4313 (setq org-table-formula-constants-local cst)))
4315 ;; Process the tags.
4316 (when tags
4317 (let (e tgs)
4318 (while (setq e (pop tags))
4319 (cond
4320 ((equal e "{") (push '(:startgroup) tgs))
4321 ((equal e "}") (push '(:endgroup) tgs))
4322 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4323 (push (cons (match-string 1 e)
4324 (string-to-char (match-string 2 e)))
4325 tgs))
4326 (t (push (list e) tgs))))
4327 (org-set-local 'org-tag-alist nil)
4328 (while (setq e (pop tgs))
4329 (or (and (stringp (car e))
4330 (assoc (car e) org-tag-alist))
4331 (push e org-tag-alist))))))
4333 ;; Compute the regular expressions and other local variables
4334 (if (not org-done-keywords)
4335 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4336 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4337 (length org-scheduled-string)))
4338 org-drawer-regexp
4339 (concat "^[ \t]*:\\("
4340 (mapconcat 'regexp-quote org-drawers "\\|")
4341 "\\):[ \t]*$")
4342 org-not-done-keywords
4343 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4344 org-todo-regexp
4345 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4346 "\\|") "\\)\\>")
4347 org-not-done-regexp
4348 (concat "\\<\\("
4349 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4350 "\\)\\>")
4351 org-todo-line-regexp
4352 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4353 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4354 "\\)\\>\\)?[ \t]*\\(.*\\)")
4355 org-complex-heading-regexp
4356 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4357 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4358 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4359 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4360 org-nl-done-regexp
4361 (concat "\n\\*+[ \t]+"
4362 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4363 "\\)" "\\>")
4364 org-todo-line-tags-regexp
4365 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4366 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4367 (org-re
4368 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4369 org-looking-at-done-regexp
4370 (concat "^" "\\(?:"
4371 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4372 "\\>")
4373 org-deadline-regexp (concat "\\<" org-deadline-string)
4374 org-deadline-time-regexp
4375 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4376 org-deadline-line-regexp
4377 (concat "\\<\\(" org-deadline-string "\\).*")
4378 org-scheduled-regexp
4379 (concat "\\<" org-scheduled-string)
4380 org-scheduled-time-regexp
4381 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4382 org-closed-time-regexp
4383 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4384 org-keyword-time-regexp
4385 (concat "\\<\\(" org-scheduled-string
4386 "\\|" org-deadline-string
4387 "\\|" org-closed-string
4388 "\\|" org-clock-string "\\)"
4389 " *[[<]\\([^]>]+\\)[]>]")
4390 org-keyword-time-not-clock-regexp
4391 (concat "\\<\\(" org-scheduled-string
4392 "\\|" org-deadline-string
4393 "\\|" org-closed-string
4394 "\\)"
4395 " *[[<]\\([^]>]+\\)[]>]")
4396 org-maybe-keyword-time-regexp
4397 (concat "\\(\\<\\(" org-scheduled-string
4398 "\\|" org-deadline-string
4399 "\\|" org-closed-string
4400 "\\|" org-clock-string "\\)\\)?"
4401 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4402 org-planning-or-clock-line-re
4403 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4404 "\\|" org-deadline-string
4405 "\\|" org-closed-string "\\|" org-clock-string
4406 "\\)\\>\\)")
4408 (org-compute-latex-and-specials-regexp)
4409 (org-set-font-lock-defaults)))
4411 (defun org-remove-keyword-keys (list)
4412 (mapcar (lambda (x)
4413 (if (string-match "(..?)$" x)
4414 (substring x 0 (match-beginning 0))
4416 list))
4418 ;; FIXME: this could be done much better, using second characters etc.
4419 (defun org-assign-fast-keys (alist)
4420 "Assign fast keys to a keyword-key alist.
4421 Respect keys that are already there."
4422 (let (new e k c c1 c2 (char ?a))
4423 (while (setq e (pop alist))
4424 (cond
4425 ((equal e '(:startgroup)) (push e new))
4426 ((equal e '(:endgroup)) (push e new))
4428 (setq k (car e) c2 nil)
4429 (if (cdr e)
4430 (setq c (cdr e))
4431 ;; automatically assign a character.
4432 (setq c1 (string-to-char
4433 (downcase (substring
4434 k (if (= (string-to-char k) ?@) 1 0)))))
4435 (if (or (rassoc c1 new) (rassoc c1 alist))
4436 (while (or (rassoc char new) (rassoc char alist))
4437 (setq char (1+ char)))
4438 (setq c2 c1))
4439 (setq c (or c2 char)))
4440 (push (cons k c) new))))
4441 (nreverse new)))
4443 ;;; Some variables ujsed in various places
4445 (defvar org-window-configuration nil
4446 "Used in various places to store a window configuration.")
4447 (defvar org-finish-function nil
4448 "Function to be called when `C-c C-c' is used.
4449 This is for getting out of special buffers like remember.")
4451 ;;; Foreign variables, to inform the compiler
4453 ;; XEmacs only
4454 (defvar outline-mode-menu-heading)
4455 (defvar outline-mode-menu-show)
4456 (defvar outline-mode-menu-hide)
4457 (defvar zmacs-regions) ; XEmacs regions
4458 ;; Emacs only
4459 (defvar mark-active)
4461 ;; Packages that org-mode interacts with
4462 (defvar calc-embedded-close-formula)
4463 (defvar calc-embedded-open-formula)
4464 (defvar font-lock-unfontify-region-function)
4465 (defvar org-goto-start-pos)
4466 (defvar vm-message-pointer)
4467 (defvar vm-folder-directory)
4468 (defvar wl-summary-buffer-elmo-folder)
4469 (defvar wl-summary-buffer-folder-name)
4470 (defvar gnus-other-frame-object)
4471 (defvar gnus-group-name)
4472 (defvar gnus-article-current)
4473 (defvar w3m-current-url)
4474 (defvar w3m-current-title)
4475 (defvar mh-progs)
4476 (defvar mh-current-folder)
4477 (defvar mh-show-folder-buffer)
4478 (defvar mh-index-folder)
4479 (defvar mh-searcher)
4480 (defvar calendar-mode-map)
4481 (defvar Info-current-file)
4482 (defvar Info-current-node)
4483 (defvar texmathp-why)
4484 (defvar remember-save-after-remembering)
4485 (defvar remember-data-file)
4486 (defvar remember-register)
4487 (defvar remember-buffer)
4488 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4489 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4490 (defvar org-latex-regexps)
4491 (defvar constants-unit-system)
4493 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4495 ;; FIXME: Occasionally check by commenting these, to make sure
4496 ;; no other functions uses these, forgetting to let-bind them.
4497 (defvar entry)
4498 (defvar state)
4499 (defvar last-state)
4500 (defvar date)
4501 (defvar description)
4503 ;; Defined somewhere in this file, but used before definition.
4504 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4505 (defvar org-agenda-buffer-name)
4506 (defvar org-agenda-undo-list)
4507 (defvar org-agenda-pending-undo-list)
4508 (defvar org-agenda-overriding-header)
4509 (defvar orgtbl-mode)
4510 (defvar org-html-entities)
4511 (defvar org-struct-menu)
4512 (defvar org-org-menu)
4513 (defvar org-tbl-menu)
4514 (defvar org-agenda-keymap)
4516 ;;;; Emacs/XEmacs compatibility
4518 ;; Overlay compatibility functions
4519 (defun org-make-overlay (beg end &optional buffer)
4520 (if (featurep 'xemacs)
4521 (make-extent beg end buffer)
4522 (make-overlay beg end buffer)))
4523 (defun org-delete-overlay (ovl)
4524 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4525 (defun org-detach-overlay (ovl)
4526 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4527 (defun org-move-overlay (ovl beg end &optional buffer)
4528 (if (featurep 'xemacs)
4529 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4530 (move-overlay ovl beg end buffer)))
4531 (defun org-overlay-put (ovl prop value)
4532 (if (featurep 'xemacs)
4533 (set-extent-property ovl prop value)
4534 (overlay-put ovl prop value)))
4535 (defun org-overlay-display (ovl text &optional face evap)
4536 "Make overlay OVL display TEXT with face FACE."
4537 (if (featurep 'xemacs)
4538 (let ((gl (make-glyph text)))
4539 (and face (set-glyph-face gl face))
4540 (set-extent-property ovl 'invisible t)
4541 (set-extent-property ovl 'end-glyph gl))
4542 (overlay-put ovl 'display text)
4543 (if face (overlay-put ovl 'face face))
4544 (if evap (overlay-put ovl 'evaporate t))))
4545 (defun org-overlay-before-string (ovl text &optional face evap)
4546 "Make overlay OVL display TEXT with face FACE."
4547 (if (featurep 'xemacs)
4548 (let ((gl (make-glyph text)))
4549 (and face (set-glyph-face gl face))
4550 (set-extent-property ovl 'begin-glyph gl))
4551 (if face (org-add-props text nil 'face face))
4552 (overlay-put ovl 'before-string text)
4553 (if evap (overlay-put ovl 'evaporate t))))
4554 (defun org-overlay-get (ovl prop)
4555 (if (featurep 'xemacs)
4556 (extent-property ovl prop)
4557 (overlay-get ovl prop)))
4558 (defun org-overlays-at (pos)
4559 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4560 (defun org-overlays-in (&optional start end)
4561 (if (featurep 'xemacs)
4562 (extent-list nil start end)
4563 (overlays-in start end)))
4564 (defun org-overlay-start (o)
4565 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4566 (defun org-overlay-end (o)
4567 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4568 (defun org-find-overlays (prop &optional pos delete)
4569 "Find all overlays specifying PROP at POS or point.
4570 If DELETE is non-nil, delete all those overlays."
4571 (let ((overlays (org-overlays-at (or pos (point))))
4572 ov found)
4573 (while (setq ov (pop overlays))
4574 (if (org-overlay-get ov prop)
4575 (if delete (org-delete-overlay ov) (push ov found))))
4576 found))
4578 ;; Region compatibility
4580 (defun org-add-hook (hook function &optional append local)
4581 "Add-hook, compatible with both Emacsen."
4582 (if (and local (featurep 'xemacs))
4583 (add-local-hook hook function append)
4584 (add-hook hook function append local)))
4586 (defvar org-ignore-region nil
4587 "To temporarily disable the active region.")
4589 (defun org-region-active-p ()
4590 "Is `transient-mark-mode' on and the region active?
4591 Works on both Emacs and XEmacs."
4592 (if org-ignore-region
4594 (if (featurep 'xemacs)
4595 (and zmacs-regions (region-active-p))
4596 (and transient-mark-mode mark-active))))
4598 ;; Invisibility compatibility
4600 (defun org-add-to-invisibility-spec (arg)
4601 "Add elements to `buffer-invisibility-spec'.
4602 See documentation for `buffer-invisibility-spec' for the kind of elements
4603 that can be added."
4604 (cond
4605 ((fboundp 'add-to-invisibility-spec)
4606 (add-to-invisibility-spec arg))
4607 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4608 (setq buffer-invisibility-spec (list arg)))
4610 (setq buffer-invisibility-spec
4611 (cons arg buffer-invisibility-spec)))))
4613 (defun org-remove-from-invisibility-spec (arg)
4614 "Remove elements from `buffer-invisibility-spec'."
4615 (if (fboundp 'remove-from-invisibility-spec)
4616 (remove-from-invisibility-spec arg)
4617 (if (consp buffer-invisibility-spec)
4618 (setq buffer-invisibility-spec
4619 (delete arg buffer-invisibility-spec)))))
4621 (defun org-in-invisibility-spec-p (arg)
4622 "Is ARG a member of `buffer-invisibility-spec'?"
4623 (if (consp buffer-invisibility-spec)
4624 (member arg buffer-invisibility-spec)
4625 nil))
4627 ;;;; Define the Org-mode
4629 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4630 (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."))
4633 ;; We use a before-change function to check if a table might need
4634 ;; an update.
4635 (defvar org-table-may-need-update t
4636 "Indicates that a table might need an update.
4637 This variable is set by `org-before-change-function'.
4638 `org-table-align' sets it back to nil.")
4639 (defvar org-mode-map)
4640 (defvar org-mode-hook nil)
4641 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4642 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4643 (defvar org-table-buffer-is-an nil)
4644 (defconst org-outline-regexp "\\*+ ")
4646 ;;;###autoload
4647 (define-derived-mode org-mode outline-mode "Org"
4648 "Outline-based notes management and organizer, alias
4649 \"Carsten's outline-mode for keeping track of everything.\"
4651 Org-mode develops organizational tasks around a NOTES file which
4652 contains information about projects as plain text. Org-mode is
4653 implemented on top of outline-mode, which is ideal to keep the content
4654 of large files well structured. It supports ToDo items, deadlines and
4655 time stamps, which magically appear in the diary listing of the Emacs
4656 calendar. Tables are easily created with a built-in table editor.
4657 Plain text URL-like links connect to websites, emails (VM), Usenet
4658 messages (Gnus), BBDB entries, and any files related to the project.
4659 For printing and sharing of notes, an Org-mode file (or a part of it)
4660 can be exported as a structured ASCII or HTML file.
4662 The following commands are available:
4664 \\{org-mode-map}"
4666 ;; Get rid of Outline menus, they are not needed
4667 ;; Need to do this here because define-derived-mode sets up
4668 ;; the keymap so late. Still, it is a waste to call this each time
4669 ;; we switch another buffer into org-mode.
4670 (if (featurep 'xemacs)
4671 (when (boundp 'outline-mode-menu-heading)
4672 ;; Assume this is Greg's port, it used easymenu
4673 (easy-menu-remove outline-mode-menu-heading)
4674 (easy-menu-remove outline-mode-menu-show)
4675 (easy-menu-remove outline-mode-menu-hide))
4676 (define-key org-mode-map [menu-bar headings] 'undefined)
4677 (define-key org-mode-map [menu-bar hide] 'undefined)
4678 (define-key org-mode-map [menu-bar show] 'undefined))
4680 (easy-menu-add org-org-menu)
4681 (easy-menu-add org-tbl-menu)
4682 (org-install-agenda-files-menu)
4683 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4684 (org-add-to-invisibility-spec '(org-cwidth))
4685 (when (featurep 'xemacs)
4686 (org-set-local 'line-move-ignore-invisible t))
4687 (org-set-local 'outline-regexp org-outline-regexp)
4688 (org-set-local 'outline-level 'org-outline-level)
4689 (when (and org-ellipsis
4690 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4691 (fboundp 'make-glyph-code))
4692 (unless org-display-table
4693 (setq org-display-table (make-display-table)))
4694 (set-display-table-slot
4695 org-display-table 4
4696 (vconcat (mapcar
4697 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4698 org-ellipsis)))
4699 (if (stringp org-ellipsis) org-ellipsis "..."))))
4700 (setq buffer-display-table org-display-table))
4701 (org-set-regexps-and-options)
4702 ;; Calc embedded
4703 (org-set-local 'calc-embedded-open-mode "# ")
4704 (modify-syntax-entry ?# "<")
4705 (modify-syntax-entry ?@ "w")
4706 (if org-startup-truncated (setq truncate-lines t))
4707 (org-set-local 'font-lock-unfontify-region-function
4708 'org-unfontify-region)
4709 ;; Activate before-change-function
4710 (org-set-local 'org-table-may-need-update t)
4711 (org-add-hook 'before-change-functions 'org-before-change-function nil
4712 'local)
4713 ;; Check for running clock before killing a buffer
4714 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4715 ;; Paragraphs and auto-filling
4716 (org-set-autofill-regexps)
4717 (setq indent-line-function 'org-indent-line-function)
4718 (org-update-radio-target-regexp)
4720 ;; Comment characters
4721 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4722 (org-set-local 'comment-padding " ")
4724 ;; Imenu
4725 (org-set-local 'imenu-create-index-function
4726 'org-imenu-get-tree)
4728 ;; Make isearch reveal context
4729 (if (or (featurep 'xemacs)
4730 (not (boundp 'outline-isearch-open-invisible-function)))
4731 ;; Emacs 21 and XEmacs make use of the hook
4732 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4733 ;; Emacs 22 deals with this through a special variable
4734 (org-set-local 'outline-isearch-open-invisible-function
4735 (lambda (&rest ignore) (org-show-context 'isearch))))
4737 ;; If empty file that did not turn on org-mode automatically, make it to.
4738 (if (and org-insert-mode-line-in-empty-file
4739 (interactive-p)
4740 (= (point-min) (point-max)))
4741 (insert "# -*- mode: org -*-\n\n"))
4743 (unless org-inhibit-startup
4744 (when org-startup-align-all-tables
4745 (let ((bmp (buffer-modified-p)))
4746 (org-table-map-tables 'org-table-align)
4747 (set-buffer-modified-p bmp)))
4748 (org-cycle-hide-drawers 'all)
4749 (cond
4750 ((eq org-startup-folded t)
4751 (org-cycle '(4)))
4752 ((eq org-startup-folded 'content)
4753 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4754 (org-cycle '(4)) (org-cycle '(4)))))))
4756 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4758 (defsubst org-call-with-arg (command arg)
4759 "Call COMMAND interactively, but pretend prefix are was ARG."
4760 (let ((current-prefix-arg arg)) (call-interactively command)))
4762 (defsubst org-current-line (&optional pos)
4763 (save-excursion
4764 (and pos (goto-char pos))
4765 ;; works also in narrowed buffer, because we start at 1, not point-min
4766 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4768 (defun org-current-time ()
4769 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4770 (if (> org-time-stamp-rounding-minutes 0)
4771 (let ((r org-time-stamp-rounding-minutes)
4772 (time (decode-time)))
4773 (apply 'encode-time
4774 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4775 (nthcdr 2 time))))
4776 (current-time)))
4778 (defun org-add-props (string plist &rest props)
4779 "Add text properties to entire string, from beginning to end.
4780 PLIST may be a list of properties, PROPS are individual properties and values
4781 that will be added to PLIST. Returns the string that was modified."
4782 (add-text-properties
4783 0 (length string) (if props (append plist props) plist) string)
4784 string)
4785 (put 'org-add-props 'lisp-indent-function 2)
4788 ;;;; Font-Lock stuff, including the activators
4790 (defvar org-mouse-map (make-sparse-keymap))
4791 (org-defkey org-mouse-map
4792 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4793 (org-defkey org-mouse-map
4794 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4795 (when org-mouse-1-follows-link
4796 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4797 (when org-tab-follows-link
4798 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4799 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4800 (when org-return-follows-link
4801 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4802 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4804 (require 'font-lock)
4806 (defconst org-non-link-chars "]\t\n\r<>")
4807 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4808 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4809 (defvar org-link-re-with-space nil
4810 "Matches a link with spaces, optional angular brackets around it.")
4811 (defvar org-link-re-with-space2 nil
4812 "Matches a link with spaces, optional angular brackets around it.")
4813 (defvar org-angle-link-re nil
4814 "Matches link with angular brackets, spaces are allowed.")
4815 (defvar org-plain-link-re nil
4816 "Matches plain link, without spaces.")
4817 (defvar org-bracket-link-regexp nil
4818 "Matches a link in double brackets.")
4819 (defvar org-bracket-link-analytic-regexp nil
4820 "Regular expression used to analyze links.
4821 Here is what the match groups contain after a match:
4822 1: http:
4823 2: http
4824 3: path
4825 4: [desc]
4826 5: desc")
4827 (defvar org-any-link-re nil
4828 "Regular expression matching any link.")
4830 (defun org-make-link-regexps ()
4831 "Update the link regular expressions.
4832 This should be called after the variable `org-link-types' has changed."
4833 (setq org-link-re-with-space
4834 (concat
4835 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4836 "\\([^" org-non-link-chars " ]"
4837 "[^" org-non-link-chars "]*"
4838 "[^" org-non-link-chars " ]\\)>?")
4839 org-link-re-with-space2
4840 (concat
4841 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4842 "\\([^" org-non-link-chars " ]"
4843 "[^]\t\n\r]*"
4844 "[^" org-non-link-chars " ]\\)>?")
4845 org-angle-link-re
4846 (concat
4847 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4848 "\\([^" org-non-link-chars " ]"
4849 "[^" org-non-link-chars "]*"
4850 "\\)>")
4851 org-plain-link-re
4852 (concat
4853 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4854 "\\([^]\t\n\r<>,;() ]+\\)")
4855 org-bracket-link-regexp
4856 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4857 org-bracket-link-analytic-regexp
4858 (concat
4859 "\\[\\["
4860 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4861 "\\([^]]+\\)"
4862 "\\]"
4863 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4864 "\\]")
4865 org-any-link-re
4866 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4867 org-angle-link-re "\\)\\|\\("
4868 org-plain-link-re "\\)")))
4870 (org-make-link-regexps)
4872 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4873 "Regular expression for fast time stamp matching.")
4874 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4875 "Regular expression for fast time stamp matching.")
4876 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4877 "Regular expression matching time strings for analysis.
4878 This one does not require the space after the date.")
4879 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4880 "Regular expression matching time strings for analysis.")
4881 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4882 "Regular expression matching time stamps, with groups.")
4883 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4884 "Regular expression matching time stamps (also [..]), with groups.")
4885 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4886 "Regular expression matching a time stamp range.")
4887 (defconst org-tr-regexp-both
4888 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4889 "Regular expression matching a time stamp range.")
4890 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4891 org-ts-regexp "\\)?")
4892 "Regular expression matching a time stamp or time stamp range.")
4893 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4894 org-ts-regexp-both "\\)?")
4895 "Regular expression matching a time stamp or time stamp range.
4896 The time stamps may be either active or inactive.")
4898 (defvar org-emph-face nil)
4900 (defun org-do-emphasis-faces (limit)
4901 "Run through the buffer and add overlays to links."
4902 (let (rtn)
4903 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4904 (if (not (= (char-after (match-beginning 3))
4905 (char-after (match-beginning 4))))
4906 (progn
4907 (setq rtn t)
4908 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4909 'face
4910 (nth 1 (assoc (match-string 3)
4911 org-emphasis-alist)))
4912 (add-text-properties (match-beginning 2) (match-end 2)
4913 '(font-lock-multiline t))
4914 (when org-hide-emphasis-markers
4915 (add-text-properties (match-end 4) (match-beginning 5)
4916 '(invisible org-link))
4917 (add-text-properties (match-beginning 3) (match-end 3)
4918 '(invisible org-link)))))
4919 (backward-char 1))
4920 rtn))
4922 (defun org-emphasize (&optional char)
4923 "Insert or change an emphasis, i.e. a font like bold or italic.
4924 If there is an active region, change that region to a new emphasis.
4925 If there is no region, just insert the marker characters and position
4926 the cursor between them.
4927 CHAR should be either the marker character, or the first character of the
4928 HTML tag associated with that emphasis. If CHAR is a space, the means
4929 to remove the emphasis of the selected region.
4930 If char is not given (for example in an interactive call) it
4931 will be prompted for."
4932 (interactive)
4933 (let ((eal org-emphasis-alist) e det
4934 (erc org-emphasis-regexp-components)
4935 (prompt "")
4936 (string "") beg end move tag c s)
4937 (if (org-region-active-p)
4938 (setq beg (region-beginning) end (region-end)
4939 string (buffer-substring beg end))
4940 (setq move t))
4942 (while (setq e (pop eal))
4943 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4944 c (aref tag 0))
4945 (push (cons c (string-to-char (car e))) det)
4946 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4947 (substring tag 1)))))
4948 (unless char
4949 (message "%s" (concat "Emphasis marker or tag:" prompt))
4950 (setq char (read-char-exclusive)))
4951 (setq char (or (cdr (assoc char det)) char))
4952 (if (equal char ?\ )
4953 (setq s "" move nil)
4954 (unless (assoc (char-to-string char) org-emphasis-alist)
4955 (error "No such emphasis marker: \"%c\"" char))
4956 (setq s (char-to-string char)))
4957 (while (and (> (length string) 1)
4958 (equal (substring string 0 1) (substring string -1))
4959 (assoc (substring string 0 1) org-emphasis-alist))
4960 (setq string (substring string 1 -1)))
4961 (setq string (concat s string s))
4962 (if beg (delete-region beg end))
4963 (unless (or (bolp)
4964 (string-match (concat "[" (nth 0 erc) "\n]")
4965 (char-to-string (char-before (point)))))
4966 (insert " "))
4967 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4968 (char-to-string (char-after (point))))
4969 (insert " ") (backward-char 1))
4970 (insert string)
4971 (and move (backward-char 1))))
4973 (defconst org-nonsticky-props
4974 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4977 (defun org-activate-plain-links (limit)
4978 "Run through the buffer and add overlays to links."
4979 (catch 'exit
4980 (let (f)
4981 (while (re-search-forward org-plain-link-re limit t)
4982 (setq f (get-text-property (match-beginning 0) 'face))
4983 (if (or (eq f 'org-tag)
4984 (and (listp f) (memq 'org-tag f)))
4986 (add-text-properties (match-beginning 0) (match-end 0)
4987 (list 'mouse-face 'highlight
4988 'rear-nonsticky org-nonsticky-props
4989 'keymap org-mouse-map
4991 (throw 'exit t))))))
4993 (defun org-activate-code (limit)
4994 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4995 (unless (get-text-property (match-beginning 1) 'face)
4996 (remove-text-properties (match-beginning 0) (match-end 0)
4997 '(display t invisible t intangible t))
4998 t)))
5000 (defun org-activate-angle-links (limit)
5001 "Run through the buffer and add overlays to links."
5002 (if (re-search-forward org-angle-link-re limit t)
5003 (progn
5004 (add-text-properties (match-beginning 0) (match-end 0)
5005 (list 'mouse-face 'highlight
5006 'rear-nonsticky org-nonsticky-props
5007 'keymap org-mouse-map
5009 t)))
5011 (defmacro org-maybe-intangible (props)
5012 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5013 In emacs 21, invisible text is not avoided by the command loop, so the
5014 intangible property is needed to make sure point skips this text.
5015 In Emacs 22, this is not necessary. The intangible text property has
5016 led to problems with flyspell. These problems are fixed in flyspell.el,
5017 but we still avoid setting the property in Emacs 22 and later.
5018 We use a macro so that the test can happen at compilation time."
5019 (if (< emacs-major-version 22)
5020 `(append '(intangible t) ,props)
5021 props))
5023 (defun org-activate-bracket-links (limit)
5024 "Run through the buffer and add overlays to bracketed links."
5025 (if (re-search-forward org-bracket-link-regexp limit t)
5026 (let* ((help (concat "LINK: "
5027 (org-match-string-no-properties 1)))
5028 ;; FIXME: above we should remove the escapes.
5029 ;; but that requires another match, protecting match data,
5030 ;; a lot of overhead for font-lock.
5031 (ip (org-maybe-intangible
5032 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5033 'keymap org-mouse-map 'mouse-face 'highlight
5034 'font-lock-multiline t 'help-echo help)))
5035 (vp (list 'rear-nonsticky org-nonsticky-props
5036 'keymap org-mouse-map 'mouse-face 'highlight
5037 ' font-lock-multiline t 'help-echo help)))
5038 ;; We need to remove the invisible property here. Table narrowing
5039 ;; may have made some of this invisible.
5040 (remove-text-properties (match-beginning 0) (match-end 0)
5041 '(invisible nil))
5042 (if (match-end 3)
5043 (progn
5044 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5045 (add-text-properties (match-beginning 3) (match-end 3) vp)
5046 (add-text-properties (match-end 3) (match-end 0) ip))
5047 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5048 (add-text-properties (match-beginning 1) (match-end 1) vp)
5049 (add-text-properties (match-end 1) (match-end 0) ip))
5050 t)))
5052 (defun org-activate-dates (limit)
5053 "Run through the buffer and add overlays to dates."
5054 (if (re-search-forward org-tsr-regexp-both limit t)
5055 (progn
5056 (add-text-properties (match-beginning 0) (match-end 0)
5057 (list 'mouse-face 'highlight
5058 'rear-nonsticky org-nonsticky-props
5059 'keymap org-mouse-map))
5060 (when org-display-custom-times
5061 (if (match-end 3)
5062 (org-display-custom-time (match-beginning 3) (match-end 3)))
5063 (org-display-custom-time (match-beginning 1) (match-end 1)))
5064 t)))
5066 (defvar org-target-link-regexp nil
5067 "Regular expression matching radio targets in plain text.")
5068 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5069 "Regular expression matching a link target.")
5070 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5071 "Regular expression matching a radio target.")
5072 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5073 "Regular expression matching any target.")
5075 (defun org-activate-target-links (limit)
5076 "Run through the buffer and add overlays to target matches."
5077 (when org-target-link-regexp
5078 (let ((case-fold-search t))
5079 (if (re-search-forward org-target-link-regexp limit t)
5080 (progn
5081 (add-text-properties (match-beginning 0) (match-end 0)
5082 (list 'mouse-face 'highlight
5083 'rear-nonsticky org-nonsticky-props
5084 'keymap org-mouse-map
5085 'help-echo "Radio target link"
5086 'org-linked-text t))
5087 t)))))
5089 (defun org-update-radio-target-regexp ()
5090 "Find all radio targets in this file and update the regular expression."
5091 (interactive)
5092 (when (memq 'radio org-activate-links)
5093 (setq org-target-link-regexp
5094 (org-make-target-link-regexp (org-all-targets 'radio)))
5095 (org-restart-font-lock)))
5097 (defun org-hide-wide-columns (limit)
5098 (let (s e)
5099 (setq s (text-property-any (point) (or limit (point-max))
5100 'org-cwidth t))
5101 (when s
5102 (setq e (next-single-property-change s 'org-cwidth))
5103 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5104 (goto-char e)
5105 t)))
5107 (defvar org-latex-and-specials-regexp nil
5108 "Regular expression for highlighting export special stuff.")
5109 (defvar org-match-substring-regexp)
5110 (defvar org-match-substring-with-braces-regexp)
5111 (defvar org-export-html-special-string-regexps)
5113 (defun org-compute-latex-and-specials-regexp ()
5114 "Compute regular expression for stuff treated specially by exporters."
5115 (if (not org-highlight-latex-fragments-and-specials)
5116 (org-set-local 'org-latex-and-specials-regexp nil)
5117 (let*
5118 ((matchers (plist-get org-format-latex-options :matchers))
5119 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5120 org-latex-regexps)))
5121 (options (org-combine-plists (org-default-export-plist)
5122 (org-infile-export-plist)))
5123 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5124 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5125 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5126 (org-export-html-expand (plist-get options :expand-quoted-html))
5127 (org-export-with-special-strings (plist-get options :special-strings))
5128 (re-sub
5129 (cond
5130 ((equal org-export-with-sub-superscripts '{})
5131 (list org-match-substring-with-braces-regexp))
5132 (org-export-with-sub-superscripts
5133 (list org-match-substring-regexp))
5134 (t nil)))
5135 (re-latex
5136 (if org-export-with-LaTeX-fragments
5137 (mapcar (lambda (x) (nth 1 x)) latexs)))
5138 (re-macros
5139 (if org-export-with-TeX-macros
5140 (list (concat "\\\\"
5141 (regexp-opt
5142 (append (mapcar 'car org-html-entities)
5143 (if (boundp 'org-latex-entities)
5144 org-latex-entities nil))
5145 'words))) ; FIXME
5147 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5148 (re-special (if org-export-with-special-strings
5149 (mapcar (lambda (x) (car x))
5150 org-export-html-special-string-regexps)))
5151 (re-rest
5152 (delq nil
5153 (list
5154 (if org-export-html-expand "@<[^>\n]+>")
5155 ))))
5156 (org-set-local
5157 'org-latex-and-specials-regexp
5158 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5159 re-rest) "\\|")))))
5161 (defface org-latex-and-export-specials
5162 (let ((font (cond ((assq :inherit custom-face-attributes)
5163 '(:inherit underline))
5164 (t '(:underline t)))))
5165 `((((class grayscale) (background light))
5166 (:foreground "DimGray" ,@font))
5167 (((class grayscale) (background dark))
5168 (:foreground "LightGray" ,@font))
5169 (((class color) (background light))
5170 (:foreground "SaddleBrown"))
5171 (((class color) (background dark))
5172 (:foreground "burlywood"))
5173 (t (,@font))))
5174 "Face used to highlight math latex and other special exporter stuff."
5175 :group 'org-faces)
5177 (defun org-do-latex-and-special-faces (limit)
5178 "Run through the buffer and add overlays to links."
5179 (when org-latex-and-specials-regexp
5180 (let (rtn d)
5181 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5182 limit t))
5183 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5184 'face))
5185 '(org-code org-verbatim underline)))
5186 (progn
5187 (setq rtn t
5188 d (cond ((member (char-after (1+ (match-beginning 0)))
5189 '(?_ ?^)) 1)
5190 (t 0)))
5191 (font-lock-prepend-text-property
5192 (+ d (match-beginning 0)) (match-end 0)
5193 'face 'org-latex-and-export-specials)
5194 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5195 '(font-lock-multiline t)))))
5196 rtn)))
5198 (defun org-restart-font-lock ()
5199 "Restart font-lock-mode, to force refontification."
5200 (when (and (boundp 'font-lock-mode) font-lock-mode)
5201 (font-lock-mode -1)
5202 (font-lock-mode 1)))
5204 (defun org-all-targets (&optional radio)
5205 "Return a list of all targets in this file.
5206 With optional argument RADIO, only find radio targets."
5207 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5208 rtn)
5209 (save-excursion
5210 (goto-char (point-min))
5211 (while (re-search-forward re nil t)
5212 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5213 rtn)))
5215 (defun org-make-target-link-regexp (targets)
5216 "Make regular expression matching all strings in TARGETS.
5217 The regular expression finds the targets also if there is a line break
5218 between words."
5219 (and targets
5220 (concat
5221 "\\<\\("
5222 (mapconcat
5223 (lambda (x)
5224 (while (string-match " +" x)
5225 (setq x (replace-match "\\s-+" t t x)))
5227 targets
5228 "\\|")
5229 "\\)\\>")))
5231 (defun org-activate-tags (limit)
5232 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5233 (progn
5234 (add-text-properties (match-beginning 1) (match-end 1)
5235 (list 'mouse-face 'highlight
5236 'rear-nonsticky org-nonsticky-props
5237 'keymap org-mouse-map))
5238 t)))
5240 (defun org-outline-level ()
5241 (save-excursion
5242 (looking-at outline-regexp)
5243 (if (match-beginning 1)
5244 (+ (org-get-string-indentation (match-string 1)) 1000)
5245 (1- (- (match-end 0) (match-beginning 0))))))
5247 (defvar org-font-lock-keywords nil)
5249 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5250 "Regular expression matching a property line.")
5252 (defun org-set-font-lock-defaults ()
5253 (let* ((em org-fontify-emphasized-text)
5254 (lk org-activate-links)
5255 (org-font-lock-extra-keywords
5256 (list
5257 ;; Headlines
5258 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5259 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5260 ;; Table lines
5261 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5262 (1 'org-table t))
5263 ;; Table internals
5264 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5265 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5266 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5267 ;; Drawers
5268 (list org-drawer-regexp '(0 'org-special-keyword t))
5269 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5270 ;; Properties
5271 (list org-property-re
5272 '(1 'org-special-keyword t)
5273 '(3 'org-property-value t))
5274 (if org-format-transports-properties-p
5275 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5276 ;; Links
5277 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5278 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5279 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5280 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5281 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5282 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5283 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5284 '(org-hide-wide-columns (0 nil append))
5285 ;; TODO lines
5286 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5287 '(1 (org-get-todo-face 1) t))
5288 ;; DONE
5289 (if org-fontify-done-headline
5290 (list (concat "^[*]+ +\\<\\("
5291 (mapconcat 'regexp-quote org-done-keywords "\\|")
5292 "\\)\\(.*\\)")
5293 '(2 'org-headline-done t))
5294 nil)
5295 ;; Priorities
5296 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5297 ;; Special keywords
5298 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5299 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5300 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5301 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5302 ;; Emphasis
5303 (if em
5304 (if (featurep 'xemacs)
5305 '(org-do-emphasis-faces (0 nil append))
5306 '(org-do-emphasis-faces)))
5307 ;; Checkboxes
5308 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5309 2 'bold prepend)
5310 (if org-provide-checkbox-statistics
5311 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5312 (0 (org-get-checkbox-statistics-face) t)))
5313 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5314 '(1 'org-archived prepend))
5315 ;; Specials
5316 '(org-do-latex-and-special-faces)
5317 ;; Code
5318 '(org-activate-code (1 'org-code t))
5319 ;; COMMENT
5320 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5321 "\\|" org-quote-string "\\)\\>")
5322 '(1 'org-special-keyword t))
5323 '("^#.*" (0 'font-lock-comment-face t))
5325 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5326 ;; Now set the full font-lock-keywords
5327 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5328 (org-set-local 'font-lock-defaults
5329 '(org-font-lock-keywords t nil nil backward-paragraph))
5330 (kill-local-variable 'font-lock-keywords) nil))
5332 (defvar org-m nil)
5333 (defvar org-l nil)
5334 (defvar org-f nil)
5335 (defun org-get-level-face (n)
5336 "Get the right face for match N in font-lock matching of healdines."
5337 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5338 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5339 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5340 (cond
5341 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5342 ((eq n 2) org-f)
5343 (t (if org-level-color-stars-only nil org-f))))
5345 (defun org-get-todo-face (kwd)
5346 "Get the right face for a TODO keyword KWD.
5347 If KWD is a number, get the corresponding match group."
5348 (if (numberp kwd) (setq kwd (match-string kwd)))
5349 (or (cdr (assoc kwd org-todo-keyword-faces))
5350 (and (member kwd org-done-keywords) 'org-done)
5351 'org-todo))
5353 (defun org-unfontify-region (beg end &optional maybe_loudly)
5354 "Remove fontification and activation overlays from links."
5355 (font-lock-default-unfontify-region beg end)
5356 (let* ((buffer-undo-list t)
5357 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5358 (inhibit-modification-hooks t)
5359 deactivate-mark buffer-file-name buffer-file-truename)
5360 (remove-text-properties beg end
5361 '(mouse-face t keymap t org-linked-text t
5362 invisible t intangible t))))
5364 ;;;; Visibility cycling, including org-goto and indirect buffer
5366 ;;; Cycling
5368 (defvar org-cycle-global-status nil)
5369 (make-variable-buffer-local 'org-cycle-global-status)
5370 (defvar org-cycle-subtree-status nil)
5371 (make-variable-buffer-local 'org-cycle-subtree-status)
5373 ;;;###autoload
5374 (defun org-cycle (&optional arg)
5375 "Visibility cycling for Org-mode.
5377 - When this function is called with a prefix argument, rotate the entire
5378 buffer through 3 states (global cycling)
5379 1. OVERVIEW: Show only top-level headlines.
5380 2. CONTENTS: Show all headlines of all levels, but no body text.
5381 3. SHOW ALL: Show everything.
5383 - When point is at the beginning of a headline, rotate the subtree started
5384 by this line through 3 different states (local cycling)
5385 1. FOLDED: Only the main headline is shown.
5386 2. CHILDREN: The main headline and the direct children are shown.
5387 From this state, you can move to one of the children
5388 and zoom in further.
5389 3. SUBTREE: Show the entire subtree, including body text.
5391 - When there is a numeric prefix, go up to a heading with level ARG, do
5392 a `show-subtree' and return to the previous cursor position. If ARG
5393 is negative, go up that many levels.
5395 - When point is not at the beginning of a headline, execute
5396 `indent-relative', like TAB normally does. See the option
5397 `org-cycle-emulate-tab' for details.
5399 - Special case: if point is at the beginning of the buffer and there is
5400 no headline in line 1, this function will act as if called with prefix arg.
5401 But only if also the variable `org-cycle-global-at-bob' is t."
5402 (interactive "P")
5403 (let* ((outline-regexp
5404 (if (and (org-mode-p) org-cycle-include-plain-lists)
5405 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5406 outline-regexp))
5407 (bob-special (and org-cycle-global-at-bob (bobp)
5408 (not (looking-at outline-regexp))))
5409 (org-cycle-hook
5410 (if bob-special
5411 (delq 'org-optimize-window-after-visibility-change
5412 (copy-sequence org-cycle-hook))
5413 org-cycle-hook))
5414 (pos (point)))
5416 (if (or bob-special (equal arg '(4)))
5417 ;; special case: use global cycling
5418 (setq arg t))
5420 (cond
5422 ((org-at-table-p 'any)
5423 ;; Enter the table or move to the next field in the table
5424 (or (org-table-recognize-table.el)
5425 (progn
5426 (if arg (org-table-edit-field t)
5427 (org-table-justify-field-maybe)
5428 (call-interactively 'org-table-next-field)))))
5430 ((eq arg t) ;; Global cycling
5432 (cond
5433 ((and (eq last-command this-command)
5434 (eq org-cycle-global-status 'overview))
5435 ;; We just created the overview - now do table of contents
5436 ;; This can be slow in very large buffers, so indicate action
5437 (message "CONTENTS...")
5438 (org-content)
5439 (message "CONTENTS...done")
5440 (setq org-cycle-global-status 'contents)
5441 (run-hook-with-args 'org-cycle-hook 'contents))
5443 ((and (eq last-command this-command)
5444 (eq org-cycle-global-status 'contents))
5445 ;; We just showed the table of contents - now show everything
5446 (show-all)
5447 (message "SHOW ALL")
5448 (setq org-cycle-global-status 'all)
5449 (run-hook-with-args 'org-cycle-hook 'all))
5452 ;; Default action: go to overview
5453 (org-overview)
5454 (message "OVERVIEW")
5455 (setq org-cycle-global-status 'overview)
5456 (run-hook-with-args 'org-cycle-hook 'overview))))
5458 ((and org-drawers org-drawer-regexp
5459 (save-excursion
5460 (beginning-of-line 1)
5461 (looking-at org-drawer-regexp)))
5462 ;; Toggle block visibility
5463 (org-flag-drawer
5464 (not (get-char-property (match-end 0) 'invisible))))
5466 ((integerp arg)
5467 ;; Show-subtree, ARG levels up from here.
5468 (save-excursion
5469 (org-back-to-heading)
5470 (outline-up-heading (if (< arg 0) (- arg)
5471 (- (funcall outline-level) arg)))
5472 (org-show-subtree)))
5474 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5475 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5476 ;; At a heading: rotate between three different views
5477 (org-back-to-heading)
5478 (let ((goal-column 0) eoh eol eos)
5479 ;; First, some boundaries
5480 (save-excursion
5481 (org-back-to-heading)
5482 (save-excursion
5483 (beginning-of-line 2)
5484 (while (and (not (eobp)) ;; this is like `next-line'
5485 (get-char-property (1- (point)) 'invisible))
5486 (beginning-of-line 2)) (setq eol (point)))
5487 (outline-end-of-heading) (setq eoh (point))
5488 (org-end-of-subtree t)
5489 (unless (eobp)
5490 (skip-chars-forward " \t\n")
5491 (beginning-of-line 1) ; in case this is an item
5493 (setq eos (1- (point))))
5494 ;; Find out what to do next and set `this-command'
5495 (cond
5496 ((= eos eoh)
5497 ;; Nothing is hidden behind this heading
5498 (message "EMPTY ENTRY")
5499 (setq org-cycle-subtree-status nil)
5500 (save-excursion
5501 (goto-char eos)
5502 (outline-next-heading)
5503 (if (org-invisible-p) (org-flag-heading nil))))
5504 ((or (>= eol eos)
5505 (not (string-match "\\S-" (buffer-substring eol eos))))
5506 ;; Entire subtree is hidden in one line: open it
5507 (org-show-entry)
5508 (show-children)
5509 (message "CHILDREN")
5510 (save-excursion
5511 (goto-char eos)
5512 (outline-next-heading)
5513 (if (org-invisible-p) (org-flag-heading nil)))
5514 (setq org-cycle-subtree-status 'children)
5515 (run-hook-with-args 'org-cycle-hook 'children))
5516 ((and (eq last-command this-command)
5517 (eq org-cycle-subtree-status 'children))
5518 ;; We just showed the children, now show everything.
5519 (org-show-subtree)
5520 (message "SUBTREE")
5521 (setq org-cycle-subtree-status 'subtree)
5522 (run-hook-with-args 'org-cycle-hook 'subtree))
5524 ;; Default action: hide the subtree.
5525 (hide-subtree)
5526 (message "FOLDED")
5527 (setq org-cycle-subtree-status 'folded)
5528 (run-hook-with-args 'org-cycle-hook 'folded)))))
5530 ;; TAB emulation
5531 (buffer-read-only (org-back-to-heading))
5533 ((org-try-cdlatex-tab))
5535 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5536 (or (not (bolp))
5537 (not (looking-at outline-regexp))))
5538 (call-interactively (global-key-binding "\t")))
5540 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5541 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5542 (or (and (eq org-cycle-emulate-tab 'white)
5543 (= (match-end 0) (point-at-eol)))
5544 (and (eq org-cycle-emulate-tab 'whitestart)
5545 (>= (match-end 0) pos))))
5547 (eq org-cycle-emulate-tab t))
5548 ; (if (and (looking-at "[ \n\r\t]")
5549 ; (string-match "^[ \t]*$" (buffer-substring
5550 ; (point-at-bol) (point))))
5551 ; (progn
5552 ; (beginning-of-line 1)
5553 ; (and (looking-at "[ \t]+") (replace-match ""))))
5554 (call-interactively (global-key-binding "\t")))
5556 (t (save-excursion
5557 (org-back-to-heading)
5558 (org-cycle))))))
5560 ;;;###autoload
5561 (defun org-global-cycle (&optional arg)
5562 "Cycle the global visibility. For details see `org-cycle'."
5563 (interactive "P")
5564 (let ((org-cycle-include-plain-lists
5565 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5566 (if (integerp arg)
5567 (progn
5568 (show-all)
5569 (hide-sublevels arg)
5570 (setq org-cycle-global-status 'contents))
5571 (org-cycle '(4)))))
5573 (defun org-overview ()
5574 "Switch to overview mode, shoing only top-level headlines.
5575 Really, this shows all headlines with level equal or greater than the level
5576 of the first headline in the buffer. This is important, because if the
5577 first headline is not level one, then (hide-sublevels 1) gives confusing
5578 results."
5579 (interactive)
5580 (let ((level (save-excursion
5581 (goto-char (point-min))
5582 (if (re-search-forward (concat "^" outline-regexp) nil t)
5583 (progn
5584 (goto-char (match-beginning 0))
5585 (funcall outline-level))))))
5586 (and level (hide-sublevels level))))
5588 (defun org-content (&optional arg)
5589 "Show all headlines in the buffer, like a table of contents.
5590 With numerical argument N, show content up to level N."
5591 (interactive "P")
5592 (save-excursion
5593 ;; Visit all headings and show their offspring
5594 (and (integerp arg) (org-overview))
5595 (goto-char (point-max))
5596 (catch 'exit
5597 (while (and (progn (condition-case nil
5598 (outline-previous-visible-heading 1)
5599 (error (goto-char (point-min))))
5601 (looking-at outline-regexp))
5602 (if (integerp arg)
5603 (show-children (1- arg))
5604 (show-branches))
5605 (if (bobp) (throw 'exit nil))))))
5608 (defun org-optimize-window-after-visibility-change (state)
5609 "Adjust the window after a change in outline visibility.
5610 This function is the default value of the hook `org-cycle-hook'."
5611 (when (get-buffer-window (current-buffer))
5612 (cond
5613 ; ((eq state 'overview) (org-first-headline-recenter 1))
5614 ; ((eq state 'overview) (org-beginning-of-line))
5615 ((eq state 'content) nil)
5616 ((eq state 'all) nil)
5617 ((eq state 'folded) nil)
5618 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5619 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5622 (defun org-cycle-show-empty-lines (state)
5623 "Show empty lines above all visible headlines.
5624 The region to be covered depends on STATE when called through
5625 `org-cycle-hook'. Lisp program can use t for STATE to get the
5626 entire buffer covered. Note that an empty line is only shown if there
5627 are at least `org-cycle-separator-lines' empty lines before the headeline."
5628 (when (> org-cycle-separator-lines 0)
5629 (save-excursion
5630 (let* ((n org-cycle-separator-lines)
5631 (re (cond
5632 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5633 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5634 (t (let ((ns (number-to-string (- n 2))))
5635 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5636 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5637 beg end)
5638 (cond
5639 ((memq state '(overview contents t))
5640 (setq beg (point-min) end (point-max)))
5641 ((memq state '(children folded))
5642 (setq beg (point) end (progn (org-end-of-subtree t t)
5643 (beginning-of-line 2)
5644 (point)))))
5645 (when beg
5646 (goto-char beg)
5647 (while (re-search-forward re end t)
5648 (if (not (get-char-property (match-end 1) 'invisible))
5649 (outline-flag-region
5650 (match-beginning 1) (match-end 1) nil)))))))
5651 ;; Never hide empty lines at the end of the file.
5652 (save-excursion
5653 (goto-char (point-max))
5654 (outline-previous-heading)
5655 (outline-end-of-heading)
5656 (if (and (looking-at "[ \t\n]+")
5657 (= (match-end 0) (point-max)))
5658 (outline-flag-region (point) (match-end 0) nil))))
5660 (defun org-subtree-end-visible-p ()
5661 "Is the end of the current subtree visible?"
5662 (pos-visible-in-window-p
5663 (save-excursion (org-end-of-subtree t) (point))))
5665 (defun org-first-headline-recenter (&optional N)
5666 "Move cursor to the first headline and recenter the headline.
5667 Optional argument N means, put the headline into the Nth line of the window."
5668 (goto-char (point-min))
5669 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5670 (beginning-of-line)
5671 (recenter (prefix-numeric-value N))))
5673 ;;; Org-goto
5675 (defvar org-goto-window-configuration nil)
5676 (defvar org-goto-marker nil)
5677 (defvar org-goto-map
5678 (let ((map (make-sparse-keymap)))
5679 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5680 (while (setq cmd (pop cmds))
5681 (substitute-key-definition cmd cmd map global-map)))
5682 (suppress-keymap map)
5683 (org-defkey map "\C-m" 'org-goto-ret)
5684 (org-defkey map [(left)] 'org-goto-left)
5685 (org-defkey map [(right)] 'org-goto-right)
5686 (org-defkey map [(?q)] 'org-goto-quit)
5687 (org-defkey map [(control ?g)] 'org-goto-quit)
5688 (org-defkey map "\C-i" 'org-cycle)
5689 (org-defkey map [(tab)] 'org-cycle)
5690 (org-defkey map [(down)] 'outline-next-visible-heading)
5691 (org-defkey map [(up)] 'outline-previous-visible-heading)
5692 (org-defkey map "n" 'outline-next-visible-heading)
5693 (org-defkey map "p" 'outline-previous-visible-heading)
5694 (org-defkey map "f" 'outline-forward-same-level)
5695 (org-defkey map "b" 'outline-backward-same-level)
5696 (org-defkey map "u" 'outline-up-heading)
5697 (org-defkey map "/" 'org-occur)
5698 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5699 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5700 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5701 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5702 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5703 map))
5705 (defconst org-goto-help
5706 "Browse copy of buffer to find location or copy text.
5707 RET=jump to location [Q]uit and return to previous location
5708 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5711 (defun org-goto ()
5712 "Look up a different location in the current file, keeping current visibility.
5714 When you want look-up or go to a different location in a document, the
5715 fastest way is often to fold the entire buffer and then dive into the tree.
5716 This method has the disadvantage, that the previous location will be folded,
5717 which may not be what you want.
5719 This command works around this by showing a copy of the current buffer
5720 in an indirect buffer, in overview mode. You can dive into the tree in
5721 that copy, use org-occur and incremental search to find a location.
5722 When pressing RET or `Q', the command returns to the original buffer in
5723 which the visibility is still unchanged. After RET is will also jump to
5724 the location selected in the indirect buffer and expose the
5725 the headline hierarchy above."
5726 (interactive)
5727 (let* ((org-goto-start-pos (point))
5728 (selected-point
5729 (car (org-get-location (current-buffer) org-goto-help))))
5730 (if selected-point
5731 (progn
5732 (org-mark-ring-push org-goto-start-pos)
5733 (goto-char selected-point)
5734 (if (or (org-invisible-p) (org-invisible-p2))
5735 (org-show-context 'org-goto)))
5736 (message "Quit"))))
5738 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5739 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5741 (defun org-get-location (buf help)
5742 "Let the user select a location in the Org-mode buffer BUF.
5743 This function uses a recursive edit. It returns the selected position
5744 or nil."
5745 (let (org-goto-selected-point org-goto-exit-command)
5746 (save-excursion
5747 (save-window-excursion
5748 (delete-other-windows)
5749 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5750 (switch-to-buffer
5751 (condition-case nil
5752 (make-indirect-buffer (current-buffer) "*org-goto*")
5753 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5754 (with-output-to-temp-buffer "*Help*"
5755 (princ help))
5756 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5757 (setq buffer-read-only nil)
5758 (let ((org-startup-truncated t)
5759 (org-startup-folded nil)
5760 (org-startup-align-all-tables nil))
5761 (org-mode)
5762 (org-overview))
5763 (setq buffer-read-only t)
5764 (if (and (boundp 'org-goto-start-pos)
5765 (integer-or-marker-p org-goto-start-pos))
5766 (let ((org-show-hierarchy-above t)
5767 (org-show-siblings t)
5768 (org-show-following-heading t))
5769 (goto-char org-goto-start-pos)
5770 (and (org-invisible-p) (org-show-context)))
5771 (goto-char (point-min)))
5772 (org-beginning-of-line)
5773 (message "Select location and press RET")
5774 ;; now we make sure that during selection, ony very few keys work
5775 ;; and that it is impossible to switch to another window.
5776 ; (let ((gm (current-global-map))
5777 ; (overriding-local-map org-goto-map))
5778 ; (unwind-protect
5779 ; (progn
5780 ; (use-global-map org-goto-map)
5781 ; (recursive-edit))
5782 ; (use-global-map gm)))
5783 (use-local-map org-goto-map)
5784 (recursive-edit)
5786 (kill-buffer "*org-goto*")
5787 (cons org-goto-selected-point org-goto-exit-command)))
5789 (defun org-goto-ret (&optional arg)
5790 "Finish `org-goto' by going to the new location."
5791 (interactive "P")
5792 (setq org-goto-selected-point (point)
5793 org-goto-exit-command 'return)
5794 (throw 'exit nil))
5796 (defun org-goto-left ()
5797 "Finish `org-goto' by going to the new location."
5798 (interactive)
5799 (if (org-on-heading-p)
5800 (progn
5801 (beginning-of-line 1)
5802 (setq org-goto-selected-point (point)
5803 org-goto-exit-command 'left)
5804 (throw 'exit nil))
5805 (error "Not on a heading")))
5807 (defun org-goto-right ()
5808 "Finish `org-goto' by going to the new location."
5809 (interactive)
5810 (if (org-on-heading-p)
5811 (progn
5812 (setq org-goto-selected-point (point)
5813 org-goto-exit-command 'right)
5814 (throw 'exit nil))
5815 (error "Not on a heading")))
5817 (defun org-goto-quit ()
5818 "Finish `org-goto' without cursor motion."
5819 (interactive)
5820 (setq org-goto-selected-point nil)
5821 (setq org-goto-exit-command 'quit)
5822 (throw 'exit nil))
5824 ;;; Indirect buffer display of subtrees
5826 (defvar org-indirect-dedicated-frame nil
5827 "This is the frame being used for indirect tree display.")
5828 (defvar org-last-indirect-buffer nil)
5830 (defun org-tree-to-indirect-buffer (&optional arg)
5831 "Create indirect buffer and narrow it to current subtree.
5832 With numerical prefix ARG, go up to this level and then take that tree.
5833 If ARG is negative, go up that many levels.
5834 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5835 indirect buffer previously made with this command, to avoid proliferation of
5836 indirect buffers. However, when you call the command with a `C-u' prefix, or
5837 when `org-indirect-buffer-display' is `new-frame', the last buffer
5838 is kept so that you can work with several indirect buffers at the same time.
5839 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5840 requests that a new frame be made for the new buffer, so that the dedicated
5841 frame is not changed."
5842 (interactive "P")
5843 (let ((cbuf (current-buffer))
5844 (cwin (selected-window))
5845 (pos (point))
5846 beg end level heading ibuf)
5847 (save-excursion
5848 (org-back-to-heading t)
5849 (when (numberp arg)
5850 (setq level (org-outline-level))
5851 (if (< arg 0) (setq arg (+ level arg)))
5852 (while (> (setq level (org-outline-level)) arg)
5853 (outline-up-heading 1 t)))
5854 (setq beg (point)
5855 heading (org-get-heading))
5856 (org-end-of-subtree t) (setq end (point)))
5857 (if (and (buffer-live-p org-last-indirect-buffer)
5858 (not (eq org-indirect-buffer-display 'new-frame))
5859 (not arg))
5860 (kill-buffer org-last-indirect-buffer))
5861 (setq ibuf (org-get-indirect-buffer cbuf)
5862 org-last-indirect-buffer ibuf)
5863 (cond
5864 ((or (eq org-indirect-buffer-display 'new-frame)
5865 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5866 (select-frame (make-frame))
5867 (delete-other-windows)
5868 (switch-to-buffer ibuf)
5869 (org-set-frame-title heading))
5870 ((eq org-indirect-buffer-display 'dedicated-frame)
5871 (raise-frame
5872 (select-frame (or (and org-indirect-dedicated-frame
5873 (frame-live-p org-indirect-dedicated-frame)
5874 org-indirect-dedicated-frame)
5875 (setq org-indirect-dedicated-frame (make-frame)))))
5876 (delete-other-windows)
5877 (switch-to-buffer ibuf)
5878 (org-set-frame-title (concat "Indirect: " heading)))
5879 ((eq org-indirect-buffer-display 'current-window)
5880 (switch-to-buffer ibuf))
5881 ((eq org-indirect-buffer-display 'other-window)
5882 (pop-to-buffer ibuf))
5883 (t (error "Invalid value.")))
5884 (if (featurep 'xemacs)
5885 (save-excursion (org-mode) (turn-on-font-lock)))
5886 (narrow-to-region beg end)
5887 (show-all)
5888 (goto-char pos)
5889 (and (window-live-p cwin) (select-window cwin))))
5891 (defun org-get-indirect-buffer (&optional buffer)
5892 (setq buffer (or buffer (current-buffer)))
5893 (let ((n 1) (base (buffer-name buffer)) bname)
5894 (while (buffer-live-p
5895 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5896 (setq n (1+ n)))
5897 (condition-case nil
5898 (make-indirect-buffer buffer bname 'clone)
5899 (error (make-indirect-buffer buffer bname)))))
5901 (defun org-set-frame-title (title)
5902 "Set the title of the current frame to the string TITLE."
5903 ;; FIXME: how to name a single frame in XEmacs???
5904 (unless (featurep 'xemacs)
5905 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5907 ;;;; Structure editing
5909 ;;; Inserting headlines
5911 (defun org-insert-heading (&optional force-heading)
5912 "Insert a new heading or item with same depth at point.
5913 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5914 If point is at the beginning of a headline, insert a sibling before the
5915 current headline. If point is in the middle of a headline, split the headline
5916 at that position and make the rest of the headline part of the sibling below
5917 the current headline."
5918 (interactive "P")
5919 (if (= (buffer-size) 0)
5920 (insert "\n* ")
5921 (when (or force-heading (not (org-insert-item)))
5922 (let* ((head (save-excursion
5923 (condition-case nil
5924 (progn
5925 (org-back-to-heading)
5926 (match-string 0))
5927 (error "*"))))
5928 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5929 pos)
5930 (cond
5931 ((and (org-on-heading-p) (bolp)
5932 (or (bobp)
5933 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5934 (open-line (if blank 2 1)))
5935 ((and (bolp)
5936 (or (bobp)
5937 (save-excursion
5938 (backward-char 1) (not (org-invisible-p)))))
5939 nil)
5940 (t (newline (if blank 2 1))))
5941 (insert head) (just-one-space)
5942 (setq pos (point))
5943 (end-of-line 1)
5944 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5945 (run-hooks 'org-insert-heading-hook)))))
5947 (defun org-insert-heading-after-current ()
5948 "Insert a new heading with same level as current, after current subtree."
5949 (interactive)
5950 (org-back-to-heading)
5951 (org-insert-heading)
5952 (org-move-subtree-down)
5953 (end-of-line 1))
5955 (defun org-insert-todo-heading (arg)
5956 "Insert a new heading with the same level and TODO state as current heading.
5957 If the heading has no TODO state, or if the state is DONE, use the first
5958 state (TODO by default). Also with prefix arg, force first state."
5959 (interactive "P")
5960 (when (not (org-insert-item 'checkbox))
5961 (org-insert-heading)
5962 (save-excursion
5963 (org-back-to-heading)
5964 (outline-previous-heading)
5965 (looking-at org-todo-line-regexp))
5966 (if (or arg
5967 (not (match-beginning 2))
5968 (member (match-string 2) org-done-keywords))
5969 (insert (car org-todo-keywords-1) " ")
5970 (insert (match-string 2) " "))))
5972 (defun org-insert-subheading (arg)
5973 "Insert a new subheading and demote it.
5974 Works for outline headings and for plain lists alike."
5975 (interactive "P")
5976 (org-insert-heading arg)
5977 (cond
5978 ((org-on-heading-p) (org-do-demote))
5979 ((org-at-item-p) (org-indent-item 1))))
5981 (defun org-insert-todo-subheading (arg)
5982 "Insert a new subheading with TODO keyword or checkbox and demote it.
5983 Works for outline headings and for plain lists alike."
5984 (interactive "P")
5985 (org-insert-todo-heading arg)
5986 (cond
5987 ((org-on-heading-p) (org-do-demote))
5988 ((org-at-item-p) (org-indent-item 1))))
5990 ;;; Promotion and Demotion
5992 (defun org-promote-subtree ()
5993 "Promote the entire subtree.
5994 See also `org-promote'."
5995 (interactive)
5996 (save-excursion
5997 (org-map-tree 'org-promote))
5998 (org-fix-position-after-promote))
6000 (defun org-demote-subtree ()
6001 "Demote the entire subtree. See `org-demote'.
6002 See also `org-promote'."
6003 (interactive)
6004 (save-excursion
6005 (org-map-tree 'org-demote))
6006 (org-fix-position-after-promote))
6009 (defun org-do-promote ()
6010 "Promote the current heading higher up the tree.
6011 If the region is active in `transient-mark-mode', promote all headings
6012 in the region."
6013 (interactive)
6014 (save-excursion
6015 (if (org-region-active-p)
6016 (org-map-region 'org-promote (region-beginning) (region-end))
6017 (org-promote)))
6018 (org-fix-position-after-promote))
6020 (defun org-do-demote ()
6021 "Demote the current heading lower down the tree.
6022 If the region is active in `transient-mark-mode', demote all headings
6023 in the region."
6024 (interactive)
6025 (save-excursion
6026 (if (org-region-active-p)
6027 (org-map-region 'org-demote (region-beginning) (region-end))
6028 (org-demote)))
6029 (org-fix-position-after-promote))
6031 (defun org-fix-position-after-promote ()
6032 "Make sure that after pro/demotion cursor position is right."
6033 (let ((pos (point)))
6034 (when (save-excursion
6035 (beginning-of-line 1)
6036 (looking-at org-todo-line-regexp)
6037 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6038 (cond ((eobp) (insert " "))
6039 ((eolp) (insert " "))
6040 ((equal (char-after) ?\ ) (forward-char 1))))))
6042 (defun org-reduced-level (l)
6043 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6045 (defun org-get-legal-level (level &optional change)
6046 "Rectify a level change under the influence of `org-odd-levels-only'
6047 LEVEL is a current level, CHANGE is by how much the level should be
6048 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6049 even level numbers will become the next higher odd number."
6050 (if org-odd-levels-only
6051 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6052 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6053 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6054 (max 1 (+ level change))))
6056 (defun org-promote ()
6057 "Promote the current heading higher up the tree.
6058 If the region is active in `transient-mark-mode', promote all headings
6059 in the region."
6060 (org-back-to-heading t)
6061 (let* ((level (save-match-data (funcall outline-level)))
6062 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6063 (diff (abs (- level (length up-head) -1))))
6064 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6065 (replace-match up-head nil t)
6066 ;; Fixup tag positioning
6067 (and org-auto-align-tags (org-set-tags nil t))
6068 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6070 (defun org-demote ()
6071 "Demote the current heading lower down the tree.
6072 If the region is active in `transient-mark-mode', demote all headings
6073 in the region."
6074 (org-back-to-heading t)
6075 (let* ((level (save-match-data (funcall outline-level)))
6076 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6077 (diff (abs (- level (length down-head) -1))))
6078 (replace-match down-head nil t)
6079 ;; Fixup tag positioning
6080 (and org-auto-align-tags (org-set-tags nil t))
6081 (if org-adapt-indentation (org-fixup-indentation diff))))
6083 (defun org-map-tree (fun)
6084 "Call FUN for every heading underneath the current one."
6085 (org-back-to-heading)
6086 (let ((level (funcall outline-level)))
6087 (save-excursion
6088 (funcall fun)
6089 (while (and (progn
6090 (outline-next-heading)
6091 (> (funcall outline-level) level))
6092 (not (eobp)))
6093 (funcall fun)))))
6095 (defun org-map-region (fun beg end)
6096 "Call FUN for every heading between BEG and END."
6097 (let ((org-ignore-region t))
6098 (save-excursion
6099 (setq end (copy-marker end))
6100 (goto-char beg)
6101 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6102 (< (point) end))
6103 (funcall fun))
6104 (while (and (progn
6105 (outline-next-heading)
6106 (< (point) end))
6107 (not (eobp)))
6108 (funcall fun)))))
6110 (defun org-fixup-indentation (diff)
6111 "Change the indentation in the current entry by DIFF
6112 However, if any line in the current entry has no indentation, or if it
6113 would end up with no indentation after the change, nothing at all is done."
6114 (save-excursion
6115 (let ((end (save-excursion (outline-next-heading)
6116 (point-marker)))
6117 (prohibit (if (> diff 0)
6118 "^\\S-"
6119 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6120 col)
6121 (unless (save-excursion (end-of-line 1)
6122 (re-search-forward prohibit end t))
6123 (while (and (< (point) end)
6124 (re-search-forward "^[ \t]+" end t))
6125 (goto-char (match-end 0))
6126 (setq col (current-column))
6127 (if (< diff 0) (replace-match ""))
6128 (indent-to (+ diff col))))
6129 (move-marker end nil))))
6131 (defun org-convert-to-odd-levels ()
6132 "Convert an org-mode file with all levels allowed to one with odd levels.
6133 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6134 level 5 etc."
6135 (interactive)
6136 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6137 (let ((org-odd-levels-only nil) n)
6138 (save-excursion
6139 (goto-char (point-min))
6140 (while (re-search-forward "^\\*\\*+ " nil t)
6141 (setq n (- (length (match-string 0)) 2))
6142 (while (>= (setq n (1- n)) 0)
6143 (org-demote))
6144 (end-of-line 1))))))
6147 (defun org-convert-to-oddeven-levels ()
6148 "Convert an org-mode file with only odd levels to one with odd and even levels.
6149 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6150 section with an even level, conversion would destroy the structure of the file. An error
6151 is signaled in this case."
6152 (interactive)
6153 (goto-char (point-min))
6154 ;; First check if there are no even levels
6155 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6156 (org-show-context t)
6157 (error "Not all levels are odd in this file. Conversion not possible."))
6158 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6159 (let ((org-odd-levels-only nil) n)
6160 (save-excursion
6161 (goto-char (point-min))
6162 (while (re-search-forward "^\\*\\*+ " nil t)
6163 (setq n (/ (1- (length (match-string 0))) 2))
6164 (while (>= (setq n (1- n)) 0)
6165 (org-promote))
6166 (end-of-line 1))))))
6168 (defun org-tr-level (n)
6169 "Make N odd if required."
6170 (if org-odd-levels-only (1+ (/ n 2)) n))
6172 ;;; Vertical tree motion, cutting and pasting of subtrees
6174 (defun org-move-subtree-up (&optional arg)
6175 "Move the current subtree up past ARG headlines of the same level."
6176 (interactive "p")
6177 (org-move-subtree-down (- (prefix-numeric-value arg))))
6179 (defun org-move-subtree-down (&optional arg)
6180 "Move the current subtree down past ARG headlines of the same level."
6181 (interactive "p")
6182 (setq arg (prefix-numeric-value arg))
6183 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6184 'outline-get-last-sibling))
6185 (ins-point (make-marker))
6186 (cnt (abs arg))
6187 beg end txt folded)
6188 ;; Select the tree
6189 (org-back-to-heading)
6190 (setq beg (point))
6191 (save-match-data
6192 (save-excursion (outline-end-of-heading)
6193 (setq folded (org-invisible-p)))
6194 (outline-end-of-subtree))
6195 (outline-next-heading)
6196 (setq end (point))
6197 ;; Find insertion point, with error handling
6198 (goto-char beg)
6199 (while (> cnt 0)
6200 (or (and (funcall movfunc) (looking-at outline-regexp))
6201 (progn (goto-char beg)
6202 (error "Cannot move past superior level or buffer limit")))
6203 (setq cnt (1- cnt)))
6204 (if (> arg 0)
6205 ;; Moving forward - still need to move over subtree
6206 (progn (outline-end-of-subtree)
6207 (outline-next-heading)
6208 (if (not (or (looking-at (concat "^" outline-regexp))
6209 (bolp)))
6210 (newline))))
6211 (move-marker ins-point (point))
6212 (setq txt (buffer-substring beg end))
6213 (delete-region beg end)
6214 (insert txt)
6215 (or (bolp) (insert "\n"))
6216 (goto-char ins-point)
6217 (if folded (hide-subtree))
6218 (move-marker ins-point nil)))
6220 (defvar org-subtree-clip ""
6221 "Clipboard for cut and paste of subtrees.
6222 This is actually only a copy of the kill, because we use the normal kill
6223 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6225 (defvar org-subtree-clip-folded nil
6226 "Was the last copied subtree folded?
6227 This is used to fold the tree back after pasting.")
6229 (defun org-cut-subtree (&optional n)
6230 "Cut the current subtree into the clipboard.
6231 With prefix arg N, cut this many sequential subtrees.
6232 This is a short-hand for marking the subtree and then cutting it."
6233 (interactive "p")
6234 (org-copy-subtree n 'cut))
6236 (defun org-copy-subtree (&optional n cut)
6237 "Cut the current subtree into the clipboard.
6238 With prefix arg N, cut this many sequential subtrees.
6239 This is a short-hand for marking the subtree and then copying it.
6240 If CUT is non-nil, actually cut the subtree."
6241 (interactive "p")
6242 (let (beg end folded)
6243 (if (interactive-p)
6244 (org-back-to-heading nil) ; take what looks like a subtree
6245 (org-back-to-heading t)) ; take what is really there
6246 (setq beg (point))
6247 (save-match-data
6248 (save-excursion (outline-end-of-heading)
6249 (setq folded (org-invisible-p)))
6250 (condition-case nil
6251 (outline-forward-same-level (1- n))
6252 (error nil))
6253 (org-end-of-subtree t t))
6254 (setq end (point))
6255 (goto-char beg)
6256 (when (> end beg)
6257 (setq org-subtree-clip-folded folded)
6258 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6259 (setq org-subtree-clip (current-kill 0))
6260 (message "%s: Subtree(s) with %d characters"
6261 (if cut "Cut" "Copied")
6262 (length org-subtree-clip)))))
6264 (defun org-paste-subtree (&optional level tree)
6265 "Paste the clipboard as a subtree, with modification of headline level.
6266 The entire subtree is promoted or demoted in order to match a new headline
6267 level. By default, the new level is derived from the visible headings
6268 before and after the insertion point, and taken to be the inferior headline
6269 level of the two. So if the previous visible heading is level 3 and the
6270 next is level 4 (or vice versa), level 4 will be used for insertion.
6271 This makes sure that the subtree remains an independent subtree and does
6272 not swallow low level entries.
6274 You can also force a different level, either by using a numeric prefix
6275 argument, or by inserting the heading marker by hand. For example, if the
6276 cursor is after \"*****\", then the tree will be shifted to level 5.
6278 If you want to insert the tree as is, just use \\[yank].
6280 If optional TREE is given, use this text instead of the kill ring."
6281 (interactive "P")
6282 (unless (org-kill-is-subtree-p tree)
6283 (error
6284 (substitute-command-keys
6285 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6286 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6287 (^re (concat "^\\(" outline-regexp "\\)"))
6288 (re (concat "\\(" outline-regexp "\\)"))
6289 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6291 (old-level (if (string-match ^re txt)
6292 (- (match-end 0) (match-beginning 0) 1)
6293 -1))
6294 (force-level (cond (level (prefix-numeric-value level))
6295 ((string-match
6296 ^re_ (buffer-substring (point-at-bol) (point)))
6297 (- (match-end 1) (match-beginning 1)))
6298 (t nil)))
6299 (previous-level (save-excursion
6300 (condition-case nil
6301 (progn
6302 (outline-previous-visible-heading 1)
6303 (if (looking-at re)
6304 (- (match-end 0) (match-beginning 0) 1)
6306 (error 1))))
6307 (next-level (save-excursion
6308 (condition-case nil
6309 (progn
6310 (or (looking-at outline-regexp)
6311 (outline-next-visible-heading 1))
6312 (if (looking-at re)
6313 (- (match-end 0) (match-beginning 0) 1)
6315 (error 1))))
6316 (new-level (or force-level (max previous-level next-level)))
6317 (shift (if (or (= old-level -1)
6318 (= new-level -1)
6319 (= old-level new-level))
6321 (- new-level old-level)))
6322 (delta (if (> shift 0) -1 1))
6323 (func (if (> shift 0) 'org-demote 'org-promote))
6324 (org-odd-levels-only nil)
6325 beg end)
6326 ;; Remove the forced level indicator
6327 (if force-level
6328 (delete-region (point-at-bol) (point)))
6329 ;; Paste
6330 (beginning-of-line 1)
6331 (setq beg (point))
6332 (insert txt)
6333 (unless (string-match "\n\\'" txt) (insert "\n"))
6334 (setq end (point))
6335 (goto-char beg)
6336 ;; Shift if necessary
6337 (unless (= shift 0)
6338 (save-restriction
6339 (narrow-to-region beg end)
6340 (while (not (= shift 0))
6341 (org-map-region func (point-min) (point-max))
6342 (setq shift (+ delta shift)))
6343 (goto-char (point-min))))
6344 (when (interactive-p)
6345 (message "Clipboard pasted as level %d subtree" new-level))
6346 (if (and kill-ring
6347 (eq org-subtree-clip (current-kill 0))
6348 org-subtree-clip-folded)
6349 ;; The tree was folded before it was killed/copied
6350 (hide-subtree))))
6352 (defun org-kill-is-subtree-p (&optional txt)
6353 "Check if the current kill is an outline subtree, or a set of trees.
6354 Returns nil if kill does not start with a headline, or if the first
6355 headline level is not the largest headline level in the tree.
6356 So this will actually accept several entries of equal levels as well,
6357 which is OK for `org-paste-subtree'.
6358 If optional TXT is given, check this string instead of the current kill."
6359 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6360 (start-level (and kill
6361 (string-match (concat "\\`" org-outline-regexp) kill)
6362 (- (match-end 0) (match-beginning 0) 1)))
6363 (re (concat "^" org-outline-regexp))
6364 (start 1))
6365 (if (not start-level)
6366 (progn
6367 nil) ;; does not even start with a heading
6368 (catch 'exit
6369 (while (setq start (string-match re kill (1+ start)))
6370 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6371 (throw 'exit nil)))
6372 t))))
6374 (defun org-narrow-to-subtree ()
6375 "Narrow buffer to the current subtree."
6376 (interactive)
6377 (save-excursion
6378 (narrow-to-region
6379 (progn (org-back-to-heading) (point))
6380 (progn (org-end-of-subtree t t) (point)))))
6383 ;;; Outline Sorting
6385 (defun org-sort (with-case)
6386 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6387 Optional argument WITH-CASE means sort case-sensitively."
6388 (interactive "P")
6389 (if (org-at-table-p)
6390 (org-call-with-arg 'org-table-sort-lines with-case)
6391 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6393 (defvar org-priority-regexp) ; defined later in the file
6395 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6396 "Sort entries on a certain level of an outline tree.
6397 If there is an active region, the entries in the region are sorted.
6398 Else, if the cursor is before the first entry, sort the top-level items.
6399 Else, the children of the entry at point are sorted.
6401 Sorting can be alphabetically, numerically, and by date/time as given by
6402 the first time stamp in the entry. The command prompts for the sorting
6403 type unless it has been given to the function through the SORTING-TYPE
6404 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6405 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6406 called with point at the beginning of the record. It must return either
6407 a string or a number that should serve as the sorting key for that record.
6409 Comparing entries ignores case by default. However, with an optional argument
6410 WITH-CASE, the sorting considers case as well."
6411 (interactive "P")
6412 (let ((case-func (if with-case 'identity 'downcase))
6413 start beg end stars re re2
6414 txt what tmp plain-list-p)
6415 ;; Find beginning and end of region to sort
6416 (cond
6417 ((org-region-active-p)
6418 ;; we will sort the region
6419 (setq end (region-end)
6420 what "region")
6421 (goto-char (region-beginning))
6422 (if (not (org-on-heading-p)) (outline-next-heading))
6423 (setq start (point)))
6424 ((org-at-item-p)
6425 ;; we will sort this plain list
6426 (org-beginning-of-item-list) (setq start (point))
6427 (org-end-of-item-list) (setq end (point))
6428 (goto-char start)
6429 (setq plain-list-p t
6430 what "plain list"))
6431 ((or (org-on-heading-p)
6432 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6433 ;; we will sort the children of the current headline
6434 (org-back-to-heading)
6435 (setq start (point) end (org-end-of-subtree) what "children")
6436 (goto-char start)
6437 (show-subtree)
6438 (outline-next-heading))
6440 ;; we will sort the top-level entries in this file
6441 (goto-char (point-min))
6442 (or (org-on-heading-p) (outline-next-heading))
6443 (setq start (point) end (point-max) what "top-level")
6444 (goto-char start)
6445 (show-all)))
6447 (setq beg (point))
6448 (if (>= beg end) (error "Nothing to sort"))
6450 (unless plain-list-p
6451 (looking-at "\\(\\*+\\)")
6452 (setq stars (match-string 1)
6453 re (concat "^" (regexp-quote stars) " +")
6454 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6455 txt (buffer-substring beg end))
6456 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6457 (if (and (not (equal stars "*")) (string-match re2 txt))
6458 (error "Region to sort contains a level above the first entry")))
6460 (unless sorting-type
6461 (message
6462 (if plain-list-p
6463 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6464 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6465 what)
6466 (setq sorting-type (read-char-exclusive))
6468 (and (= (downcase sorting-type) ?f)
6469 (setq getkey-func
6470 (completing-read "Sort using function: "
6471 obarray 'fboundp t nil nil))
6472 (setq getkey-func (intern getkey-func)))
6474 (and (= (downcase sorting-type) ?r)
6475 (setq property
6476 (completing-read "Property: "
6477 (mapcar 'list (org-buffer-property-keys t))
6478 nil t))))
6480 (message "Sorting entries...")
6482 (save-restriction
6483 (narrow-to-region start end)
6485 (let ((dcst (downcase sorting-type))
6486 (now (current-time)))
6487 (sort-subr
6488 (/= dcst sorting-type)
6489 ;; This function moves to the beginning character of the "record" to
6490 ;; be sorted.
6491 (if plain-list-p
6492 (lambda nil
6493 (if (org-at-item-p) t (goto-char (point-max))))
6494 (lambda nil
6495 (if (re-search-forward re nil t)
6496 (goto-char (match-beginning 0))
6497 (goto-char (point-max)))))
6498 ;; This function moves to the last character of the "record" being
6499 ;; sorted.
6500 (if plain-list-p
6501 'org-end-of-item
6502 (lambda nil
6503 (save-match-data
6504 (condition-case nil
6505 (outline-forward-same-level 1)
6506 (error
6507 (goto-char (point-max)))))))
6509 ;; This function returns the value that gets sorted against.
6510 (if plain-list-p
6511 (lambda nil
6512 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6513 (cond
6514 ((= dcst ?n)
6515 (string-to-number (buffer-substring (match-end 0)
6516 (point-at-eol))))
6517 ((= dcst ?a)
6518 (buffer-substring (match-end 0) (point-at-eol)))
6519 ((= dcst ?t)
6520 (if (re-search-forward org-ts-regexp
6521 (point-at-eol) t)
6522 (org-time-string-to-time (match-string 0))
6523 now))
6524 ((= dcst ?f)
6525 (if getkey-func
6526 (progn
6527 (setq tmp (funcall getkey-func))
6528 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6529 tmp)
6530 (error "Invalid key function `%s'" getkey-func)))
6531 (t (error "Invalid sorting type `%c'" sorting-type)))))
6532 (lambda nil
6533 (cond
6534 ((= dcst ?n)
6535 (if (looking-at outline-regexp)
6536 (string-to-number (buffer-substring (match-end 0)
6537 (point-at-eol)))
6538 nil))
6539 ((= dcst ?a)
6540 (funcall case-func (buffer-substring (point-at-bol)
6541 (point-at-eol))))
6542 ((= dcst ?t)
6543 (if (re-search-forward org-ts-regexp
6544 (save-excursion
6545 (forward-line 2)
6546 (point)) t)
6547 (org-time-string-to-time (match-string 0))
6548 now))
6549 ((= dcst ?p)
6550 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6551 (string-to-char (match-string 2))
6552 org-default-priority))
6553 ((= dcst ?r)
6554 (or (org-entry-get nil property) ""))
6555 ((= dcst ?f)
6556 (if getkey-func
6557 (progn
6558 (setq tmp (funcall getkey-func))
6559 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6560 tmp)
6561 (error "Invalid key function `%s'" getkey-func)))
6562 (t (error "Invalid sorting type `%c'" sorting-type)))))
6564 (cond
6565 ((= dcst ?a) 'string<)
6566 ((= dcst ?t) 'time-less-p)
6567 (t nil)))))
6568 (message "Sorting entries...done")))
6570 (defun org-do-sort (table what &optional with-case sorting-type)
6571 "Sort TABLE of WHAT according to SORTING-TYPE.
6572 The user will be prompted for the SORTING-TYPE if the call to this
6573 function does not specify it. WHAT is only for the prompt, to indicate
6574 what is being sorted. The sorting key will be extracted from
6575 the car of the elements of the table.
6576 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6577 (unless sorting-type
6578 (message
6579 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6580 what)
6581 (setq sorting-type (read-char-exclusive)))
6582 (let ((dcst (downcase sorting-type))
6583 extractfun comparefun)
6584 ;; Define the appropriate functions
6585 (cond
6586 ((= dcst ?n)
6587 (setq extractfun 'string-to-number
6588 comparefun (if (= dcst sorting-type) '< '>)))
6589 ((= dcst ?a)
6590 (setq extractfun (if with-case 'identity 'downcase)
6591 comparefun (if (= dcst sorting-type)
6592 'string<
6593 (lambda (a b) (and (not (string< a b))
6594 (not (string= a b)))))))
6595 ((= dcst ?t)
6596 (setq extractfun
6597 (lambda (x)
6598 (if (string-match org-ts-regexp x)
6599 (time-to-seconds
6600 (org-time-string-to-time (match-string 0 x)))
6602 comparefun (if (= dcst sorting-type) '< '>)))
6603 (t (error "Invalid sorting type `%c'" sorting-type)))
6605 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6606 table)
6607 (lambda (a b) (funcall comparefun (car a) (car b))))))
6609 ;;;; Plain list items, including checkboxes
6611 ;;; Plain list items
6613 (defun org-at-item-p ()
6614 "Is point in a line starting a hand-formatted item?"
6615 (let ((llt org-plain-list-ordered-item-terminator))
6616 (save-excursion
6617 (goto-char (point-at-bol))
6618 (looking-at
6619 (cond
6620 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6621 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6622 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6623 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6625 (defun org-in-item-p ()
6626 "It the cursor inside a plain list item.
6627 Does not have to be the first line."
6628 (save-excursion
6629 (condition-case nil
6630 (progn
6631 (org-beginning-of-item)
6632 (org-at-item-p)
6634 (error nil))))
6636 (defun org-insert-item (&optional checkbox)
6637 "Insert a new item at the current level.
6638 Return t when things worked, nil when we are not in an item."
6639 (when (save-excursion
6640 (condition-case nil
6641 (progn
6642 (org-beginning-of-item)
6643 (org-at-item-p)
6644 (if (org-invisible-p) (error "Invisible item"))
6646 (error nil)))
6647 (let* ((bul (match-string 0))
6648 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6649 (match-end 0)))
6650 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6651 pos)
6652 (cond
6653 ((and (org-at-item-p) (<= (point) eow))
6654 ;; before the bullet
6655 (beginning-of-line 1)
6656 (open-line (if blank 2 1)))
6657 ((<= (point) eow)
6658 (beginning-of-line 1))
6659 (t (newline (if blank 2 1))))
6660 (insert bul (if checkbox "[ ]" ""))
6661 (just-one-space)
6662 (setq pos (point))
6663 (end-of-line 1)
6664 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6665 (org-maybe-renumber-ordered-list)
6666 (and checkbox (org-update-checkbox-count-maybe))
6669 ;;; Checkboxes
6671 (defun org-at-item-checkbox-p ()
6672 "Is point at a line starting a plain-list item with a checklet?"
6673 (and (org-at-item-p)
6674 (save-excursion
6675 (goto-char (match-end 0))
6676 (skip-chars-forward " \t")
6677 (looking-at "\\[[- X]\\]"))))
6679 (defun org-toggle-checkbox (&optional arg)
6680 "Toggle the checkbox in the current line."
6681 (interactive "P")
6682 (catch 'exit
6683 (let (beg end status (firstnew 'unknown))
6684 (cond
6685 ((org-region-active-p)
6686 (setq beg (region-beginning) end (region-end)))
6687 ((org-on-heading-p)
6688 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6689 ((org-at-item-checkbox-p)
6690 (let ((pos (point)))
6691 (replace-match
6692 (cond (arg "[-]")
6693 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6694 (t "[ ]"))
6695 t t)
6696 (goto-char pos))
6697 (throw 'exit t))
6698 (t (error "Not at a checkbox or heading, and no active region")))
6699 (save-excursion
6700 (goto-char beg)
6701 (while (< (point) end)
6702 (when (org-at-item-checkbox-p)
6703 (setq status (equal (match-string 0) "[X]"))
6704 (when (eq firstnew 'unknown)
6705 (setq firstnew (not status)))
6706 (replace-match
6707 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6708 (beginning-of-line 2)))))
6709 (org-update-checkbox-count-maybe))
6711 (defun org-update-checkbox-count-maybe ()
6712 "Update checkbox statistics unless turned off by user."
6713 (when org-provide-checkbox-statistics
6714 (org-update-checkbox-count)))
6716 (defun org-update-checkbox-count (&optional all)
6717 "Update the checkbox statistics in the current section.
6718 This will find all statistic cookies like [57%] and [6/12] and update them
6719 with the current numbers. With optional prefix argument ALL, do this for
6720 the whole buffer."
6721 (interactive "P")
6722 (save-excursion
6723 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6724 (beg (condition-case nil
6725 (progn (outline-back-to-heading) (point))
6726 (error (point-min))))
6727 (end (move-marker (make-marker)
6728 (progn (outline-next-heading) (point))))
6729 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6730 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6731 b1 e1 f1 c-on c-off lim (cstat 0))
6732 (when all
6733 (goto-char (point-min))
6734 (outline-next-heading)
6735 (setq beg (point) end (point-max)))
6736 (goto-char beg)
6737 (while (re-search-forward re end t)
6738 (setq cstat (1+ cstat)
6739 b1 (match-beginning 0)
6740 e1 (match-end 0)
6741 f1 (match-beginning 1)
6742 lim (cond
6743 ((org-on-heading-p) (outline-next-heading) (point))
6744 ((org-at-item-p) (org-end-of-item) (point))
6745 (t nil))
6746 c-on 0 c-off 0)
6747 (goto-char e1)
6748 (when lim
6749 (while (re-search-forward re-box lim t)
6750 (if (member (match-string 2) '("[ ]" "[-]"))
6751 (setq c-off (1+ c-off))
6752 (setq c-on (1+ c-on))))
6753 ; (delete-region b1 e1)
6754 (goto-char b1)
6755 (insert (if f1
6756 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6757 (format "[%d/%d]" c-on (+ c-on c-off))))
6758 (and (looking-at "\\[.*?\\]")
6759 (replace-match ""))))
6760 (when (interactive-p)
6761 (message "Checkbox satistics updated %s (%d places)"
6762 (if all "in entire file" "in current outline entry") cstat)))))
6764 (defun org-get-checkbox-statistics-face ()
6765 "Select the face for checkbox statistics.
6766 The face will be `org-done' when all relevant boxes are checked. Otherwise
6767 it will be `org-todo'."
6768 (if (match-end 1)
6769 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6770 (if (and (> (match-end 2) (match-beginning 2))
6771 (equal (match-string 2) (match-string 3)))
6772 'org-done
6773 'org-todo)))
6775 (defun org-get-indentation (&optional line)
6776 "Get the indentation of the current line, interpreting tabs.
6777 When LINE is given, assume it represents a line and compute its indentation."
6778 (if line
6779 (if (string-match "^ *" (org-remove-tabs line))
6780 (match-end 0))
6781 (save-excursion
6782 (beginning-of-line 1)
6783 (skip-chars-forward " \t")
6784 (current-column))))
6786 (defun org-remove-tabs (s &optional width)
6787 "Replace tabulators in S with spaces.
6788 Assumes that s is a single line, starting in column 0."
6789 (setq width (or width tab-width))
6790 (while (string-match "\t" s)
6791 (setq s (replace-match
6792 (make-string
6793 (- (* width (/ (+ (match-beginning 0) width) width))
6794 (match-beginning 0)) ?\ )
6795 t t s)))
6798 (defun org-fix-indentation (line ind)
6799 "Fix indentation in LINE.
6800 IND is a cons cell with target and minimum indentation.
6801 If the current indenation in LINE is smaller than the minimum,
6802 leave it alone. If it is larger than ind, set it to the target."
6803 (let* ((l (org-remove-tabs line))
6804 (i (org-get-indentation l))
6805 (i1 (car ind)) (i2 (cdr ind)))
6806 (if (>= i i2) (setq l (substring line i2)))
6807 (if (> i1 0)
6808 (concat (make-string i1 ?\ ) l)
6809 l)))
6811 (defcustom org-empty-line-terminates-plain-lists nil
6812 "Non-nil means, an empty line ends all plain list levels.
6813 When nil, empty lines are part of the preceeding item."
6814 :group 'org-plain-lists
6815 :type 'boolean)
6817 (defun org-beginning-of-item ()
6818 "Go to the beginning of the current hand-formatted item.
6819 If the cursor is not in an item, throw an error."
6820 (interactive)
6821 (let ((pos (point))
6822 (limit (save-excursion
6823 (condition-case nil
6824 (progn
6825 (org-back-to-heading)
6826 (beginning-of-line 2) (point))
6827 (error (point-min)))))
6828 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6829 ind ind1)
6830 (if (org-at-item-p)
6831 (beginning-of-line 1)
6832 (beginning-of-line 1)
6833 (skip-chars-forward " \t")
6834 (setq ind (current-column))
6835 (if (catch 'exit
6836 (while t
6837 (beginning-of-line 0)
6838 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6840 (if (looking-at "[ \t]*$")
6841 (setq ind1 ind-empty)
6842 (skip-chars-forward " \t")
6843 (setq ind1 (current-column)))
6844 (if (< ind1 ind)
6845 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6847 (goto-char pos)
6848 (error "Not in an item")))))
6850 (defun org-end-of-item ()
6851 "Go to the end of the current hand-formatted item.
6852 If the cursor is not in an item, throw an error."
6853 (interactive)
6854 (let* ((pos (point))
6855 ind1
6856 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6857 (limit (save-excursion (outline-next-heading) (point)))
6858 (ind (save-excursion
6859 (org-beginning-of-item)
6860 (skip-chars-forward " \t")
6861 (current-column)))
6862 (end (catch 'exit
6863 (while t
6864 (beginning-of-line 2)
6865 (if (eobp) (throw 'exit (point)))
6866 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6867 (if (looking-at "[ \t]*$")
6868 (setq ind1 ind-empty)
6869 (skip-chars-forward " \t")
6870 (setq ind1 (current-column)))
6871 (if (<= ind1 ind)
6872 (throw 'exit (point-at-bol)))))))
6873 (if end
6874 (goto-char end)
6875 (goto-char pos)
6876 (error "Not in an item"))))
6878 (defun org-next-item ()
6879 "Move to the beginning of the next item in the current plain list.
6880 Error if not at a plain list, or if this is the last item in the list."
6881 (interactive)
6882 (let (ind ind1 (pos (point)))
6883 (org-beginning-of-item)
6884 (setq ind (org-get-indentation))
6885 (org-end-of-item)
6886 (setq ind1 (org-get-indentation))
6887 (unless (and (org-at-item-p) (= ind ind1))
6888 (goto-char pos)
6889 (error "On last item"))))
6891 (defun org-previous-item ()
6892 "Move to the beginning of the previous item in the current plain list.
6893 Error if not at a plain list, or if this is the first item in the list."
6894 (interactive)
6895 (let (beg ind ind1 (pos (point)))
6896 (org-beginning-of-item)
6897 (setq beg (point))
6898 (setq ind (org-get-indentation))
6899 (goto-char beg)
6900 (catch 'exit
6901 (while t
6902 (beginning-of-line 0)
6903 (if (looking-at "[ \t]*$")
6905 (if (<= (setq ind1 (org-get-indentation)) ind)
6906 (throw 'exit t)))))
6907 (condition-case nil
6908 (if (or (not (org-at-item-p))
6909 (< ind1 (1- ind)))
6910 (error "")
6911 (org-beginning-of-item))
6912 (error (goto-char pos)
6913 (error "On first item")))))
6915 (defun org-move-item-down ()
6916 "Move the plain list item at point down, i.e. swap with following item.
6917 Subitems (items with larger indentation) are considered part of the item,
6918 so this really moves item trees."
6919 (interactive)
6920 (let (beg end ind ind1 (pos (point)) txt)
6921 (org-beginning-of-item)
6922 (setq beg (point))
6923 (setq ind (org-get-indentation))
6924 (org-end-of-item)
6925 (setq end (point))
6926 (setq ind1 (org-get-indentation))
6927 (if (and (org-at-item-p) (= ind ind1))
6928 (progn
6929 (org-end-of-item)
6930 (setq txt (buffer-substring beg end))
6931 (save-excursion
6932 (delete-region beg end))
6933 (setq pos (point))
6934 (insert txt)
6935 (goto-char pos)
6936 (org-maybe-renumber-ordered-list))
6937 (goto-char pos)
6938 (error "Cannot move this item further down"))))
6940 (defun org-move-item-up (arg)
6941 "Move the plain list item at point up, i.e. swap with previous item.
6942 Subitems (items with larger indentation) are considered part of the item,
6943 so this really moves item trees."
6944 (interactive "p")
6945 (let (beg end ind ind1 (pos (point)) txt)
6946 (org-beginning-of-item)
6947 (setq beg (point))
6948 (setq ind (org-get-indentation))
6949 (org-end-of-item)
6950 (setq end (point))
6951 (goto-char beg)
6952 (catch 'exit
6953 (while t
6954 (beginning-of-line 0)
6955 (if (looking-at "[ \t]*$")
6956 (if org-empty-line-terminates-plain-lists
6957 (progn
6958 (goto-char pos)
6959 (error "Cannot move this item further up"))
6960 nil)
6961 (if (<= (setq ind1 (org-get-indentation)) ind)
6962 (throw 'exit t)))))
6963 (condition-case nil
6964 (org-beginning-of-item)
6965 (error (goto-char beg)
6966 (error "Cannot move this item further up")))
6967 (setq ind1 (org-get-indentation))
6968 (if (and (org-at-item-p) (= ind ind1))
6969 (progn
6970 (setq txt (buffer-substring beg end))
6971 (save-excursion
6972 (delete-region beg end))
6973 (setq pos (point))
6974 (insert txt)
6975 (goto-char pos)
6976 (org-maybe-renumber-ordered-list))
6977 (goto-char pos)
6978 (error "Cannot move this item further up"))))
6980 (defun org-maybe-renumber-ordered-list ()
6981 "Renumber the ordered list at point if setup allows it.
6982 This tests the user option `org-auto-renumber-ordered-lists' before
6983 doing the renumbering."
6984 (interactive)
6985 (when (and org-auto-renumber-ordered-lists
6986 (org-at-item-p))
6987 (if (match-beginning 3)
6988 (org-renumber-ordered-list 1)
6989 (org-fix-bullet-type))))
6991 (defun org-maybe-renumber-ordered-list-safe ()
6992 (condition-case nil
6993 (save-excursion
6994 (org-maybe-renumber-ordered-list))
6995 (error nil)))
6997 (defun org-cycle-list-bullet (&optional which)
6998 "Cycle through the different itemize/enumerate bullets.
6999 This cycle the entire list level through the sequence:
7001 `-' -> `+' -> `*' -> `1.' -> `1)'
7003 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7004 0 meand `-', 1 means `+' etc."
7005 (interactive "P")
7006 (org-preserve-lc
7007 (org-beginning-of-item-list)
7008 (org-at-item-p)
7009 (beginning-of-line 1)
7010 (let ((current (match-string 0))
7011 (prevp (eq which 'previous))
7012 new)
7013 (setq new (cond
7014 ((and (numberp which)
7015 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7016 ((string-match "-" current) (if prevp "1)" "+"))
7017 ((string-match "\\+" current)
7018 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7019 ((string-match "\\*" current) (if prevp "+" "1."))
7020 ((string-match "\\." current) (if prevp "*" "1)"))
7021 ((string-match ")" current) (if prevp "1." "-"))
7022 (t (error "This should not happen"))))
7023 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7024 (org-fix-bullet-type)
7025 (org-maybe-renumber-ordered-list))))
7027 (defun org-get-string-indentation (s)
7028 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7029 (let ((n -1) (i 0) (w tab-width) c)
7030 (catch 'exit
7031 (while (< (setq n (1+ n)) (length s))
7032 (setq c (aref s n))
7033 (cond ((= c ?\ ) (setq i (1+ i)))
7034 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7035 (t (throw 'exit t)))))
7038 (defun org-renumber-ordered-list (arg)
7039 "Renumber an ordered plain list.
7040 Cursor needs to be in the first line of an item, the line that starts
7041 with something like \"1.\" or \"2)\"."
7042 (interactive "p")
7043 (unless (and (org-at-item-p)
7044 (match-beginning 3))
7045 (error "This is not an ordered list"))
7046 (let ((line (org-current-line))
7047 (col (current-column))
7048 (ind (org-get-string-indentation
7049 (buffer-substring (point-at-bol) (match-beginning 3))))
7050 ;; (term (substring (match-string 3) -1))
7051 ind1 (n (1- arg))
7052 fmt)
7053 ;; find where this list begins
7054 (org-beginning-of-item-list)
7055 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7056 (setq fmt (concat "%d" (match-string 1)))
7057 (beginning-of-line 0)
7058 ;; walk forward and replace these numbers
7059 (catch 'exit
7060 (while t
7061 (catch 'next
7062 (beginning-of-line 2)
7063 (if (eobp) (throw 'exit nil))
7064 (if (looking-at "[ \t]*$") (throw 'next nil))
7065 (skip-chars-forward " \t") (setq ind1 (current-column))
7066 (if (> ind1 ind) (throw 'next t))
7067 (if (< ind1 ind) (throw 'exit t))
7068 (if (not (org-at-item-p)) (throw 'exit nil))
7069 (delete-region (match-beginning 2) (match-end 2))
7070 (goto-char (match-beginning 2))
7071 (insert (format fmt (setq n (1+ n)))))))
7072 (goto-line line)
7073 (move-to-column col)))
7075 (defun org-fix-bullet-type ()
7076 "Make sure all items in this list have the same bullet as the firsst item."
7077 (interactive)
7078 (unless (org-at-item-p) (error "This is not a list"))
7079 (let ((line (org-current-line))
7080 (col (current-column))
7081 (ind (current-indentation))
7082 ind1 bullet)
7083 ;; find where this list begins
7084 (org-beginning-of-item-list)
7085 (beginning-of-line 1)
7086 ;; find out what the bullet type is
7087 (looking-at "[ \t]*\\(\\S-+\\)")
7088 (setq bullet (match-string 1))
7089 ;; walk forward and replace these numbers
7090 (beginning-of-line 0)
7091 (catch 'exit
7092 (while t
7093 (catch 'next
7094 (beginning-of-line 2)
7095 (if (eobp) (throw 'exit nil))
7096 (if (looking-at "[ \t]*$") (throw 'next nil))
7097 (skip-chars-forward " \t") (setq ind1 (current-column))
7098 (if (> ind1 ind) (throw 'next t))
7099 (if (< ind1 ind) (throw 'exit t))
7100 (if (not (org-at-item-p)) (throw 'exit nil))
7101 (skip-chars-forward " \t")
7102 (looking-at "\\S-+")
7103 (replace-match bullet))))
7104 (goto-line line)
7105 (move-to-column col)
7106 (if (string-match "[0-9]" bullet)
7107 (org-renumber-ordered-list 1))))
7109 (defun org-beginning-of-item-list ()
7110 "Go to the beginning of the current item list.
7111 I.e. to the first item in this list."
7112 (interactive)
7113 (org-beginning-of-item)
7114 (let ((pos (point-at-bol))
7115 (ind (org-get-indentation))
7116 ind1)
7117 ;; find where this list begins
7118 (catch 'exit
7119 (while t
7120 (catch 'next
7121 (beginning-of-line 0)
7122 (if (looking-at "[ \t]*$")
7123 (throw (if (bobp) 'exit 'next) t))
7124 (skip-chars-forward " \t") (setq ind1 (current-column))
7125 (if (or (< ind1 ind)
7126 (and (= ind1 ind)
7127 (not (org-at-item-p)))
7128 (bobp))
7129 (throw 'exit t)
7130 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7131 (goto-char pos)))
7134 (defun org-end-of-item-list ()
7135 "Go to the end of the current item list.
7136 I.e. to the text after the last item."
7137 (interactive)
7138 (org-beginning-of-item)
7139 (let ((pos (point-at-bol))
7140 (ind (org-get-indentation))
7141 ind1)
7142 ;; find where this list begins
7143 (catch 'exit
7144 (while t
7145 (catch 'next
7146 (beginning-of-line 2)
7147 (if (looking-at "[ \t]*$")
7148 (throw (if (eobp) 'exit 'next) t))
7149 (skip-chars-forward " \t") (setq ind1 (current-column))
7150 (if (or (< ind1 ind)
7151 (and (= ind1 ind)
7152 (not (org-at-item-p)))
7153 (eobp))
7154 (progn
7155 (setq pos (point-at-bol))
7156 (throw 'exit t))))))
7157 (goto-char pos)))
7160 (defvar org-last-indent-begin-marker (make-marker))
7161 (defvar org-last-indent-end-marker (make-marker))
7163 (defun org-outdent-item (arg)
7164 "Outdent a local list item."
7165 (interactive "p")
7166 (org-indent-item (- arg)))
7168 (defun org-indent-item (arg)
7169 "Indent a local list item."
7170 (interactive "p")
7171 (unless (org-at-item-p)
7172 (error "Not on an item"))
7173 (save-excursion
7174 (let (beg end ind ind1 tmp delta ind-down ind-up)
7175 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7176 (setq beg org-last-indent-begin-marker
7177 end org-last-indent-end-marker)
7178 (org-beginning-of-item)
7179 (setq beg (move-marker org-last-indent-begin-marker (point)))
7180 (org-end-of-item)
7181 (setq end (move-marker org-last-indent-end-marker (point))))
7182 (goto-char beg)
7183 (setq tmp (org-item-indent-positions)
7184 ind (car tmp)
7185 ind-down (nth 2 tmp)
7186 ind-up (nth 1 tmp)
7187 delta (if (> arg 0)
7188 (if ind-down (- ind-down ind) 2)
7189 (if ind-up (- ind-up ind) -2)))
7190 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7191 (while (< (point) end)
7192 (beginning-of-line 1)
7193 (skip-chars-forward " \t") (setq ind1 (current-column))
7194 (delete-region (point-at-bol) (point))
7195 (or (eolp) (indent-to-column (+ ind1 delta)))
7196 (beginning-of-line 2))))
7197 (org-fix-bullet-type)
7198 (org-maybe-renumber-ordered-list-safe)
7199 (save-excursion
7200 (beginning-of-line 0)
7201 (condition-case nil (org-beginning-of-item) (error nil))
7202 (org-maybe-renumber-ordered-list-safe)))
7204 (defun org-item-indent-positions ()
7205 "Return indentation for plain list items.
7206 This returns a list with three values: The current indentation, the
7207 parent indentation and the indentation a child should habe.
7208 Assumes cursor in item line."
7209 (let* ((bolpos (point-at-bol))
7210 (ind (org-get-indentation))
7211 ind-down ind-up pos)
7212 (save-excursion
7213 (org-beginning-of-item-list)
7214 (skip-chars-backward "\n\r \t")
7215 (when (org-in-item-p)
7216 (org-beginning-of-item)
7217 (setq ind-up (org-get-indentation))))
7218 (setq pos (point))
7219 (save-excursion
7220 (cond
7221 ((and (condition-case nil (progn (org-previous-item) t)
7222 (error nil))
7223 (or (forward-char 1) t)
7224 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7225 (setq ind-down (org-get-indentation)))
7226 ((and (goto-char pos)
7227 (org-at-item-p))
7228 (goto-char (match-end 0))
7229 (skip-chars-forward " \t")
7230 (setq ind-down (current-column)))))
7231 (list ind ind-up ind-down)))
7233 ;;; The orgstruct minor mode
7235 ;; Define a minor mode which can be used in other modes in order to
7236 ;; integrate the org-mode structure editing commands.
7238 ;; This is really a hack, because the org-mode structure commands use
7239 ;; keys which normally belong to the major mode. Here is how it
7240 ;; works: The minor mode defines all the keys necessary to operate the
7241 ;; structure commands, but wraps the commands into a function which
7242 ;; tests if the cursor is currently at a headline or a plain list
7243 ;; item. If that is the case, the structure command is used,
7244 ;; temporarily setting many Org-mode variables like regular
7245 ;; expressions for filling etc. However, when any of those keys is
7246 ;; used at a different location, function uses `key-binding' to look
7247 ;; up if the key has an associated command in another currently active
7248 ;; keymap (minor modes, major mode, global), and executes that
7249 ;; command. There might be problems if any of the keys is otherwise
7250 ;; used as a prefix key.
7252 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7253 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7254 ;; addresses this by checking explicitly for both bindings.
7256 (defvar orgstruct-mode-map (make-sparse-keymap)
7257 "Keymap for the minor `orgstruct-mode'.")
7259 (defvar org-local-vars nil
7260 "List of local variables, for use by `orgstruct-mode'")
7262 ;;;###autoload
7263 (define-minor-mode orgstruct-mode
7264 "Toggle the minor more `orgstruct-mode'.
7265 This mode is for using Org-mode structure commands in other modes.
7266 The following key behave as if Org-mode was active, if the cursor
7267 is on a headline, or on a plain list item (both in the definition
7268 of Org-mode).
7270 M-up Move entry/item up
7271 M-down Move entry/item down
7272 M-left Promote
7273 M-right Demote
7274 M-S-up Move entry/item up
7275 M-S-down Move entry/item down
7276 M-S-left Promote subtree
7277 M-S-right Demote subtree
7278 M-q Fill paragraph and items like in Org-mode
7279 C-c ^ Sort entries
7280 C-c - Cycle list bullet
7281 TAB Cycle item visibility
7282 M-RET Insert new heading/item
7283 S-M-RET Insert new TODO heading / Chekbox item
7284 C-c C-c Set tags / toggle checkbox"
7285 nil " OrgStruct" nil
7286 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7288 ;;;###autoload
7289 (defun turn-on-orgstruct ()
7290 "Unconditionally turn on `orgstruct-mode'."
7291 (orgstruct-mode 1))
7293 ;;;###autoload
7294 (defun turn-on-orgstruct++ ()
7295 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7296 In addition to setting orgstruct-mode, this also exports all indentation and
7297 autofilling variables from org-mode into the buffer. Note that turning
7298 off orgstruct-mode will *not* remove these additonal settings."
7299 (orgstruct-mode 1)
7300 (let (var val)
7301 (mapc
7302 (lambda (x)
7303 (when (string-match
7304 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7305 (symbol-name (car x)))
7306 (setq var (car x) val (nth 1 x))
7307 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7308 org-local-vars)))
7310 (defun orgstruct-error ()
7311 "Error when there is no default binding for a structure key."
7312 (interactive)
7313 (error "This key is has no function outside structure elements"))
7315 (defun orgstruct-setup ()
7316 "Setup orgstruct keymaps."
7317 (let ((nfunc 0)
7318 (bindings
7319 (list
7320 '([(meta up)] org-metaup)
7321 '([(meta down)] org-metadown)
7322 '([(meta left)] org-metaleft)
7323 '([(meta right)] org-metaright)
7324 '([(meta shift up)] org-shiftmetaup)
7325 '([(meta shift down)] org-shiftmetadown)
7326 '([(meta shift left)] org-shiftmetaleft)
7327 '([(meta shift right)] org-shiftmetaright)
7328 '([(shift up)] org-shiftup)
7329 '([(shift down)] org-shiftdown)
7330 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7331 '("\M-q" fill-paragraph)
7332 '("\C-c^" org-sort)
7333 '("\C-c-" org-cycle-list-bullet)))
7334 elt key fun cmd)
7335 (while (setq elt (pop bindings))
7336 (setq nfunc (1+ nfunc))
7337 (setq key (org-key (car elt))
7338 fun (nth 1 elt)
7339 cmd (orgstruct-make-binding fun nfunc key))
7340 (org-defkey orgstruct-mode-map key cmd))
7342 ;; Special treatment needed for TAB and RET
7343 (org-defkey orgstruct-mode-map [(tab)]
7344 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7345 (org-defkey orgstruct-mode-map "\C-i"
7346 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7348 (org-defkey orgstruct-mode-map "\M-\C-m"
7349 (orgstruct-make-binding 'org-insert-heading 105
7350 "\M-\C-m" [(meta return)]))
7351 (org-defkey orgstruct-mode-map [(meta return)]
7352 (orgstruct-make-binding 'org-insert-heading 106
7353 [(meta return)] "\M-\C-m"))
7355 (org-defkey orgstruct-mode-map [(shift meta return)]
7356 (orgstruct-make-binding 'org-insert-todo-heading 107
7357 [(meta return)] "\M-\C-m"))
7359 (unless org-local-vars
7360 (setq org-local-vars (org-get-local-variables)))
7364 (defun orgstruct-make-binding (fun n &rest keys)
7365 "Create a function for binding in the structure minor mode.
7366 FUN is the command to call inside a table. N is used to create a unique
7367 command name. KEYS are keys that should be checked in for a command
7368 to execute outside of tables."
7369 (eval
7370 (list 'defun
7371 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7372 '(arg)
7373 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7374 "Outside of structure, run the binding of `"
7375 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7376 "'.")
7377 '(interactive "p")
7378 (list 'if
7379 '(org-context-p 'headline 'item)
7380 (list 'org-run-like-in-org-mode (list 'quote fun))
7381 (list 'let '(orgstruct-mode)
7382 (list 'call-interactively
7383 (append '(or)
7384 (mapcar (lambda (k)
7385 (list 'key-binding k))
7386 keys)
7387 '('orgstruct-error))))))))
7389 (defun org-context-p (&rest contexts)
7390 "Check if local context is and of CONTEXTS.
7391 Possible values in the list of contexts are `table', `headline', and `item'."
7392 (let ((pos (point)))
7393 (goto-char (point-at-bol))
7394 (prog1 (or (and (memq 'table contexts)
7395 (looking-at "[ \t]*|"))
7396 (and (memq 'headline contexts)
7397 (looking-at "\\*+"))
7398 (and (memq 'item contexts)
7399 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7400 (goto-char pos))))
7402 (defun org-get-local-variables ()
7403 "Return a list of all local variables in an org-mode buffer."
7404 (let (varlist)
7405 (with-current-buffer (get-buffer-create "*Org tmp*")
7406 (erase-buffer)
7407 (org-mode)
7408 (setq varlist (buffer-local-variables)))
7409 (kill-buffer "*Org tmp*")
7410 (delq nil
7411 (mapcar
7412 (lambda (x)
7413 (setq x
7414 (if (symbolp x)
7415 (list x)
7416 (list (car x) (list 'quote (cdr x)))))
7417 (if (string-match
7418 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7419 (symbol-name (car x)))
7420 x nil))
7421 varlist))))
7423 ;;;###autoload
7424 (defun org-run-like-in-org-mode (cmd)
7425 (unless org-local-vars
7426 (setq org-local-vars (org-get-local-variables)))
7427 (eval (list 'let org-local-vars
7428 (list 'call-interactively (list 'quote cmd)))))
7430 ;;;; Archiving
7432 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7434 (defun org-archive-subtree (&optional find-done)
7435 "Move the current subtree to the archive.
7436 The archive can be a certain top-level heading in the current file, or in
7437 a different file. The tree will be moved to that location, the subtree
7438 heading be marked DONE, and the current time will be added.
7440 When called with prefix argument FIND-DONE, find whole trees without any
7441 open TODO items and archive them (after getting confirmation from the user).
7442 If the cursor is not at a headline when this comand is called, try all level
7443 1 trees. If the cursor is on a headline, only try the direct children of
7444 this heading."
7445 (interactive "P")
7446 (if find-done
7447 (org-archive-all-done)
7448 ;; Save all relevant TODO keyword-relatex variables
7450 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7451 (tr-org-todo-keywords-1 org-todo-keywords-1)
7452 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7453 (tr-org-done-keywords org-done-keywords)
7454 (tr-org-todo-regexp org-todo-regexp)
7455 (tr-org-todo-line-regexp org-todo-line-regexp)
7456 (tr-org-odd-levels-only org-odd-levels-only)
7457 (this-buffer (current-buffer))
7458 (org-archive-location org-archive-location)
7459 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7460 ;; start of variables that will be used for saving context
7461 ;; The compiler complains about them - keep them anyway!
7462 (file (abbreviate-file-name (buffer-file-name)))
7463 (time (format-time-string
7464 (substring (cdr org-time-stamp-formats) 1 -1)
7465 (current-time)))
7466 afile heading buffer level newfile-p
7467 category todo priority
7468 ;; start of variables that will be used for savind context
7469 ltags itags prop)
7471 ;; Try to find a local archive location
7472 (save-excursion
7473 (save-restriction
7474 (widen)
7475 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7476 (if (and prop (string-match "\\S-" prop))
7477 (setq org-archive-location prop)
7478 (if (or (re-search-backward re nil t)
7479 (re-search-forward re nil t))
7480 (setq org-archive-location (match-string 1))))))
7482 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7483 (progn
7484 (setq afile (format (match-string 1 org-archive-location)
7485 (file-name-nondirectory buffer-file-name))
7486 heading (match-string 2 org-archive-location)))
7487 (error "Invalid `org-archive-location'"))
7488 (if (> (length afile) 0)
7489 (setq newfile-p (not (file-exists-p afile))
7490 buffer (find-file-noselect afile))
7491 (setq buffer (current-buffer)))
7492 (unless buffer
7493 (error "Cannot access file \"%s\"" afile))
7494 (if (and (> (length heading) 0)
7495 (string-match "^\\*+" heading))
7496 (setq level (match-end 0))
7497 (setq heading nil level 0))
7498 (save-excursion
7499 (org-back-to-heading t)
7500 ;; Get context information that will be lost by moving the tree
7501 (org-refresh-category-properties)
7502 (setq category (org-get-category)
7503 todo (and (looking-at org-todo-line-regexp)
7504 (match-string 2))
7505 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7506 ltags (org-get-tags)
7507 itags (org-delete-all ltags (org-get-tags-at)))
7508 (setq ltags (mapconcat 'identity ltags " ")
7509 itags (mapconcat 'identity itags " "))
7510 ;; We first only copy, in case something goes wrong
7511 ;; we need to protect this-command, to avoid kill-region sets it,
7512 ;; which would lead to duplication of subtrees
7513 (let (this-command) (org-copy-subtree))
7514 (set-buffer buffer)
7515 ;; Enforce org-mode for the archive buffer
7516 (if (not (org-mode-p))
7517 ;; Force the mode for future visits.
7518 (let ((org-insert-mode-line-in-empty-file t)
7519 (org-inhibit-startup t))
7520 (call-interactively 'org-mode)))
7521 (when newfile-p
7522 (goto-char (point-max))
7523 (insert (format "\nArchived entries from file %s\n\n"
7524 (buffer-file-name this-buffer))))
7525 ;; Force the TODO keywords of the original buffer
7526 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7527 (org-todo-keywords-1 tr-org-todo-keywords-1)
7528 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7529 (org-done-keywords tr-org-done-keywords)
7530 (org-todo-regexp tr-org-todo-regexp)
7531 (org-todo-line-regexp tr-org-todo-line-regexp)
7532 (org-odd-levels-only
7533 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7534 org-odd-levels-only
7535 tr-org-odd-levels-only)))
7536 (goto-char (point-min))
7537 (if heading
7538 (progn
7539 (if (re-search-forward
7540 (concat "^" (regexp-quote heading)
7541 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7542 nil t)
7543 (goto-char (match-end 0))
7544 ;; Heading not found, just insert it at the end
7545 (goto-char (point-max))
7546 (or (bolp) (insert "\n"))
7547 (insert "\n" heading "\n")
7548 (end-of-line 0))
7549 ;; Make the subtree visible
7550 (show-subtree)
7551 (org-end-of-subtree t)
7552 (skip-chars-backward " \t\r\n")
7553 (and (looking-at "[ \t\r\n]*")
7554 (replace-match "\n\n")))
7555 ;; No specific heading, just go to end of file.
7556 (goto-char (point-max)) (insert "\n"))
7557 ;; Paste
7558 (org-paste-subtree (org-get-legal-level level 1))
7560 ;; Mark the entry as done
7561 (when (and org-archive-mark-done
7562 (looking-at org-todo-line-regexp)
7563 (or (not (match-end 2))
7564 (not (member (match-string 2) org-done-keywords))))
7565 (let (org-log-done)
7566 (org-todo
7567 (car (or (member org-archive-mark-done org-done-keywords)
7568 org-done-keywords)))))
7570 ;; Add the context info
7571 (when org-archive-save-context-info
7572 (let ((l org-archive-save-context-info) e n v)
7573 (while (setq e (pop l))
7574 (when (and (setq v (symbol-value e))
7575 (stringp v) (string-match "\\S-" v))
7576 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7577 (org-entry-put (point) n v)))))
7579 ;; Save the buffer, if it is not the same buffer.
7580 (if (not (eq this-buffer buffer)) (save-buffer))))
7581 ;; Here we are back in the original buffer. Everything seems to have
7582 ;; worked. So now cut the tree and finish up.
7583 (let (this-command) (org-cut-subtree))
7584 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7585 (message "Subtree archived %s"
7586 (if (eq this-buffer buffer)
7587 (concat "under heading: " heading)
7588 (concat "in file: " (abbreviate-file-name afile)))))))
7590 (defun org-refresh-category-properties ()
7591 "Refresh category text properties in teh buffer."
7592 (let ((def-cat (cond
7593 ((null org-category)
7594 (if buffer-file-name
7595 (file-name-sans-extension
7596 (file-name-nondirectory buffer-file-name))
7597 "???"))
7598 ((symbolp org-category) (symbol-name org-category))
7599 (t org-category)))
7600 beg end cat pos optionp)
7601 (org-unmodified
7602 (save-excursion
7603 (save-restriction
7604 (widen)
7605 (goto-char (point-min))
7606 (put-text-property (point) (point-max) 'org-category def-cat)
7607 (while (re-search-forward
7608 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7609 (setq pos (match-end 0)
7610 optionp (equal (char-after (match-beginning 0)) ?#)
7611 cat (org-trim (match-string 2)))
7612 (if optionp
7613 (setq beg (point-at-bol) end (point-max))
7614 (org-back-to-heading t)
7615 (setq beg (point) end (org-end-of-subtree t t)))
7616 (put-text-property beg end 'org-category cat)
7617 (goto-char pos)))))))
7619 (defun org-archive-all-done (&optional tag)
7620 "Archive sublevels of the current tree without open TODO items.
7621 If the cursor is not on a headline, try all level 1 trees. If
7622 it is on a headline, try all direct children.
7623 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7624 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7625 (rea (concat ".*:" org-archive-tag ":"))
7626 (begm (make-marker))
7627 (endm (make-marker))
7628 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7629 "Move subtree to archive (no open TODO items)? "))
7630 beg end (cntarch 0))
7631 (if (org-on-heading-p)
7632 (progn
7633 (setq re1 (concat "^" (regexp-quote
7634 (make-string
7635 (1+ (- (match-end 0) (match-beginning 0)))
7636 ?*))
7637 " "))
7638 (move-marker begm (point))
7639 (move-marker endm (org-end-of-subtree t)))
7640 (setq re1 "^* ")
7641 (move-marker begm (point-min))
7642 (move-marker endm (point-max)))
7643 (save-excursion
7644 (goto-char begm)
7645 (while (re-search-forward re1 endm t)
7646 (setq beg (match-beginning 0)
7647 end (save-excursion (org-end-of-subtree t) (point)))
7648 (goto-char beg)
7649 (if (re-search-forward re end t)
7650 (goto-char end)
7651 (goto-char beg)
7652 (if (and (or (not tag) (not (looking-at rea)))
7653 (y-or-n-p question))
7654 (progn
7655 (if tag
7656 (org-toggle-tag org-archive-tag 'on)
7657 (org-archive-subtree))
7658 (setq cntarch (1+ cntarch)))
7659 (goto-char end)))))
7660 (message "%d trees archived" cntarch)))
7662 (defun org-cycle-hide-drawers (state)
7663 "Re-hide all drawers after a visibility state change."
7664 (when (and (org-mode-p)
7665 (not (memq state '(overview folded))))
7666 (save-excursion
7667 (let* ((globalp (memq state '(contents all)))
7668 (beg (if globalp (point-min) (point)))
7669 (end (if globalp (point-max) (org-end-of-subtree t))))
7670 (goto-char beg)
7671 (while (re-search-forward org-drawer-regexp end t)
7672 (org-flag-drawer t))))))
7674 (defun org-flag-drawer (flag)
7675 (save-excursion
7676 (beginning-of-line 1)
7677 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7678 (let ((b (match-end 0)))
7679 (if (re-search-forward
7680 "^[ \t]*:END:"
7681 (save-excursion (outline-next-heading) (point)) t)
7682 (outline-flag-region b (point-at-eol) flag)
7683 (error ":END: line missing"))))))
7685 (defun org-cycle-hide-archived-subtrees (state)
7686 "Re-hide all archived subtrees after a visibility state change."
7687 (when (and (not org-cycle-open-archived-trees)
7688 (not (memq state '(overview folded))))
7689 (save-excursion
7690 (let* ((globalp (memq state '(contents all)))
7691 (beg (if globalp (point-min) (point)))
7692 (end (if globalp (point-max) (org-end-of-subtree t))))
7693 (org-hide-archived-subtrees beg end)
7694 (goto-char beg)
7695 (if (looking-at (concat ".*:" org-archive-tag ":"))
7696 (message (substitute-command-keys
7697 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7699 (defun org-force-cycle-archived ()
7700 "Cycle subtree even if it is archived."
7701 (interactive)
7702 (setq this-command 'org-cycle)
7703 (let ((org-cycle-open-archived-trees t))
7704 (call-interactively 'org-cycle)))
7706 (defun org-hide-archived-subtrees (beg end)
7707 "Re-hide all archived subtrees after a visibility state change."
7708 (save-excursion
7709 (let* ((re (concat ":" org-archive-tag ":")))
7710 (goto-char beg)
7711 (while (re-search-forward re end t)
7712 (and (org-on-heading-p) (hide-subtree))
7713 (org-end-of-subtree t)))))
7715 (defun org-toggle-tag (tag &optional onoff)
7716 "Toggle the tag TAG for the current line.
7717 If ONOFF is `on' or `off', don't toggle but set to this state."
7718 (unless (org-on-heading-p t) (error "Not on headling"))
7719 (let (res current)
7720 (save-excursion
7721 (beginning-of-line)
7722 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7723 (point-at-eol) t)
7724 (progn
7725 (setq current (match-string 1))
7726 (replace-match ""))
7727 (setq current ""))
7728 (setq current (nreverse (org-split-string current ":")))
7729 (cond
7730 ((eq onoff 'on)
7731 (setq res t)
7732 (or (member tag current) (push tag current)))
7733 ((eq onoff 'off)
7734 (or (not (member tag current)) (setq current (delete tag current))))
7735 (t (if (member tag current)
7736 (setq current (delete tag current))
7737 (setq res t)
7738 (push tag current))))
7739 (end-of-line 1)
7740 (if current
7741 (progn
7742 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7743 (org-set-tags nil t))
7744 (delete-horizontal-space))
7745 (run-hooks 'org-after-tags-change-hook))
7746 res))
7748 (defun org-toggle-archive-tag (&optional arg)
7749 "Toggle the archive tag for the current headline.
7750 With prefix ARG, check all children of current headline and offer tagging
7751 the children that do not contain any open TODO items."
7752 (interactive "P")
7753 (if arg
7754 (org-archive-all-done 'tag)
7755 (let (set)
7756 (save-excursion
7757 (org-back-to-heading t)
7758 (setq set (org-toggle-tag org-archive-tag))
7759 (when set (hide-subtree)))
7760 (and set (beginning-of-line 1))
7761 (message "Subtree %s" (if set "archived" "unarchived")))))
7764 ;;;; Tables
7766 ;;; The table editor
7768 ;; Watch out: Here we are talking about two different kind of tables.
7769 ;; Most of the code is for the tables created with the Org-mode table editor.
7770 ;; Sometimes, we talk about tables created and edited with the table.el
7771 ;; Emacs package. We call the former org-type tables, and the latter
7772 ;; table.el-type tables.
7774 (defun org-before-change-function (beg end)
7775 "Every change indicates that a table might need an update."
7776 (setq org-table-may-need-update t))
7778 (defconst org-table-line-regexp "^[ \t]*|"
7779 "Detects an org-type table line.")
7780 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7781 "Detects an org-type table line.")
7782 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7783 "Detects a table line marked for automatic recalculation.")
7784 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7785 "Detects a table line marked for automatic recalculation.")
7786 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7787 "Detects a table line marked for automatic recalculation.")
7788 (defconst org-table-hline-regexp "^[ \t]*|-"
7789 "Detects an org-type table hline.")
7790 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7791 "Detects a table-type table hline.")
7792 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7793 "Detects an org-type or table-type table.")
7794 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7795 "Searching from within a table (any type) this finds the first line
7796 outside the table.")
7797 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7798 "Searching from within a table (any type) this finds the first line
7799 outside the table.")
7801 (defvar org-table-last-highlighted-reference nil)
7802 (defvar org-table-formula-history nil)
7804 (defvar org-table-column-names nil
7805 "Alist with column names, derived from the `!' line.")
7806 (defvar org-table-column-name-regexp nil
7807 "Regular expression matching the current column names.")
7808 (defvar org-table-local-parameters nil
7809 "Alist with parameter names, derived from the `$' line.")
7810 (defvar org-table-named-field-locations nil
7811 "Alist with locations of named fields.")
7813 (defvar org-table-current-line-types nil
7814 "Table row types, non-nil only for the duration of a comand.")
7815 (defvar org-table-current-begin-line nil
7816 "Table begin line, non-nil only for the duration of a comand.")
7817 (defvar org-table-current-begin-pos nil
7818 "Table begin position, non-nil only for the duration of a comand.")
7819 (defvar org-table-dlines nil
7820 "Vector of data line line numbers in the current table.")
7821 (defvar org-table-hlines nil
7822 "Vector of hline line numbers in the current table.")
7824 (defconst org-table-range-regexp
7825 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7826 ;; 1 2 3 4 5
7827 "Regular expression for matching ranges in formulas.")
7829 (defconst org-table-range-regexp2
7830 (concat
7831 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7832 "\\.\\."
7833 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7834 "Match a range for reference display.")
7836 (defconst org-table-translate-regexp
7837 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7838 "Match a reference that needs translation, for reference display.")
7840 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7842 (defun org-table-create-with-table.el ()
7843 "Use the table.el package to insert a new table.
7844 If there is already a table at point, convert between Org-mode tables
7845 and table.el tables."
7846 (interactive)
7847 (require 'table)
7848 (cond
7849 ((org-at-table.el-p)
7850 (if (y-or-n-p "Convert table to Org-mode table? ")
7851 (org-table-convert)))
7852 ((org-at-table-p)
7853 (if (y-or-n-p "Convert table to table.el table? ")
7854 (org-table-convert)))
7855 (t (call-interactively 'table-insert))))
7857 (defun org-table-create-or-convert-from-region (arg)
7858 "Convert region to table, or create an empty table.
7859 If there is an active region, convert it to a table, using the function
7860 `org-table-convert-region'. See the documentation of that function
7861 to learn how the prefix argument is interpreted to determine the field
7862 separator.
7863 If there is no such region, create an empty table with `org-table-create'."
7864 (interactive "P")
7865 (if (org-region-active-p)
7866 (org-table-convert-region (region-beginning) (region-end) arg)
7867 (org-table-create arg)))
7869 (defun org-table-create (&optional size)
7870 "Query for a size and insert a table skeleton.
7871 SIZE is a string Columns x Rows like for example \"3x2\"."
7872 (interactive "P")
7873 (unless size
7874 (setq size (read-string
7875 (concat "Table size Columns x Rows [e.g. "
7876 org-table-default-size "]: ")
7877 "" nil org-table-default-size)))
7879 (let* ((pos (point))
7880 (indent (make-string (current-column) ?\ ))
7881 (split (org-split-string size " *x *"))
7882 (rows (string-to-number (nth 1 split)))
7883 (columns (string-to-number (car split)))
7884 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7885 "\n")))
7886 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7887 (point-at-bol) (point)))
7888 (beginning-of-line 1)
7889 (newline))
7890 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7891 (dotimes (i rows) (insert line))
7892 (goto-char pos)
7893 (if (> rows 1)
7894 ;; Insert a hline after the first row.
7895 (progn
7896 (end-of-line 1)
7897 (insert "\n|-")
7898 (goto-char pos)))
7899 (org-table-align)))
7901 (defun org-table-convert-region (beg0 end0 &optional separator)
7902 "Convert region to a table.
7903 The region goes from BEG0 to END0, but these borders will be moved
7904 slightly, to make sure a beginning of line in the first line is included.
7906 SEPARATOR specifies the field separator in the lines. It can have the
7907 following values:
7909 '(4) Use the comma as a field separator
7910 '(16) Use a TAB as field separator
7911 integer When a number, use that many spaces as field separator
7912 nil When nil, the command tries to be smart and figure out the
7913 separator in the following way:
7914 - when each line contains a TAB, assume TAB-separated material
7915 - when each line contains a comme, assume CSV material
7916 - else, assume one or more SPACE charcters as separator."
7917 (interactive "rP")
7918 (let* ((beg (min beg0 end0))
7919 (end (max beg0 end0))
7921 (goto-char beg)
7922 (beginning-of-line 1)
7923 (setq beg (move-marker (make-marker) (point)))
7924 (goto-char end)
7925 (if (bolp) (backward-char 1) (end-of-line 1))
7926 (setq end (move-marker (make-marker) (point)))
7927 ;; Get the right field separator
7928 (unless separator
7929 (goto-char beg)
7930 (setq separator
7931 (cond
7932 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7933 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7934 (t 1))))
7935 (setq re (cond
7936 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7937 ((equal separator '(16)) "^\\|\t")
7938 ((integerp separator)
7939 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7940 (t (error "This should not happen"))))
7941 (goto-char beg)
7942 (while (re-search-forward re end t)
7943 (replace-match "| " t t))
7944 (goto-char beg)
7945 (insert " ")
7946 (org-table-align)))
7948 (defun org-table-import (file arg)
7949 "Import FILE as a table.
7950 The file is assumed to be tab-separated. Such files can be produced by most
7951 spreadsheet and database applications. If no tabs (at least one per line)
7952 are found, lines will be split on whitespace into fields."
7953 (interactive "f\nP")
7954 (or (bolp) (newline))
7955 (let ((beg (point))
7956 (pm (point-max)))
7957 (insert-file-contents file)
7958 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7960 (defun org-table-export ()
7961 "Export table as a tab-separated file.
7962 Such a file can be imported into a spreadsheet program like Excel."
7963 (interactive)
7964 (let* ((beg (org-table-begin))
7965 (end (org-table-end))
7966 (table (buffer-substring beg end))
7967 (file (read-file-name "Export table to: "))
7968 buf)
7969 (unless (or (not (file-exists-p file))
7970 (y-or-n-p (format "Overwrite file %s? " file)))
7971 (error "Abort"))
7972 (with-current-buffer (find-file-noselect file)
7973 (setq buf (current-buffer))
7974 (erase-buffer)
7975 (fundamental-mode)
7976 (insert table)
7977 (goto-char (point-min))
7978 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7979 (replace-match "" t t)
7980 (end-of-line 1))
7981 (goto-char (point-min))
7982 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7983 (replace-match "" t t)
7984 (goto-char (min (1+ (point)) (point-max))))
7985 (goto-char (point-min))
7986 (while (re-search-forward "^-[-+]*$" nil t)
7987 (replace-match "")
7988 (if (looking-at "\n")
7989 (delete-char 1)))
7990 (goto-char (point-min))
7991 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7992 (replace-match "\t" t t))
7993 (save-buffer))
7994 (kill-buffer buf)))
7996 (defvar org-table-aligned-begin-marker (make-marker)
7997 "Marker at the beginning of the table last aligned.
7998 Used to check if cursor still is in that table, to minimize realignment.")
7999 (defvar org-table-aligned-end-marker (make-marker)
8000 "Marker at the end of the table last aligned.
8001 Used to check if cursor still is in that table, to minimize realignment.")
8002 (defvar org-table-last-alignment nil
8003 "List of flags for flushright alignment, from the last re-alignment.
8004 This is being used to correctly align a single field after TAB or RET.")
8005 (defvar org-table-last-column-widths nil
8006 "List of max width of fields in each column.
8007 This is being used to correctly align a single field after TAB or RET.")
8008 (defvar org-table-overlay-coordinates nil
8009 "Overlay coordinates after each align of a table.")
8010 (make-variable-buffer-local 'org-table-overlay-coordinates)
8012 (defvar org-last-recalc-line nil)
8013 (defconst org-narrow-column-arrow "=>"
8014 "Used as display property in narrowed table columns.")
8016 (defun org-table-align ()
8017 "Align the table at point by aligning all vertical bars."
8018 (interactive)
8019 (let* (
8020 ;; Limits of table
8021 (beg (org-table-begin))
8022 (end (org-table-end))
8023 ;; Current cursor position
8024 (linepos (org-current-line))
8025 (colpos (org-table-current-column))
8026 (winstart (window-start))
8027 (winstartline (org-current-line (min winstart (1- (point-max)))))
8028 lines (new "") lengths l typenums ty fields maxfields i
8029 column
8030 (indent "") cnt frac
8031 rfmt hfmt
8032 (spaces '(1 . 1))
8033 (sp1 (car spaces))
8034 (sp2 (cdr spaces))
8035 (rfmt1 (concat
8036 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8037 (hfmt1 (concat
8038 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8039 emptystrings links dates emph narrow fmax f1 len c e)
8040 (untabify beg end)
8041 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8042 ;; Check if we have links or dates
8043 (goto-char beg)
8044 (setq links (re-search-forward org-bracket-link-regexp end t))
8045 (goto-char beg)
8046 (setq emph (and org-hide-emphasis-markers
8047 (re-search-forward org-emph-re end t)))
8048 (goto-char beg)
8049 (setq dates (and org-display-custom-times
8050 (re-search-forward org-ts-regexp-both end t)))
8051 ;; Make sure the link properties are right
8052 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8053 ;; Make sure the date properties are right
8054 (when dates (goto-char beg) (while (org-activate-dates end)))
8055 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8057 ;; Check if we are narrowing any columns
8058 (goto-char beg)
8059 (setq narrow (and org-format-transports-properties-p
8060 (re-search-forward "<[0-9]+>" end t)))
8061 ;; Get the rows
8062 (setq lines (org-split-string
8063 (buffer-substring beg end) "\n"))
8064 ;; Store the indentation of the first line
8065 (if (string-match "^ *" (car lines))
8066 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8067 ;; Mark the hlines by setting the corresponding element to nil
8068 ;; At the same time, we remove trailing space.
8069 (setq lines (mapcar (lambda (l)
8070 (if (string-match "^ *|-" l)
8072 (if (string-match "[ \t]+$" l)
8073 (substring l 0 (match-beginning 0))
8074 l)))
8075 lines))
8076 ;; Get the data fields by splitting the lines.
8077 (setq fields (mapcar
8078 (lambda (l)
8079 (org-split-string l " *| *"))
8080 (delq nil (copy-sequence lines))))
8081 ;; How many fields in the longest line?
8082 (condition-case nil
8083 (setq maxfields (apply 'max (mapcar 'length fields)))
8084 (error
8085 (kill-region beg end)
8086 (org-table-create org-table-default-size)
8087 (error "Empty table - created default table")))
8088 ;; A list of empty strings to fill any short rows on output
8089 (setq emptystrings (make-list maxfields ""))
8090 ;; Check for special formatting.
8091 (setq i -1)
8092 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8093 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8094 ;; Check if there is an explicit width specified
8095 (when narrow
8096 (setq c column fmax nil)
8097 (while c
8098 (setq e (pop c))
8099 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8100 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8101 ;; Find fields that are wider than fmax, and shorten them
8102 (when fmax
8103 (loop for xx in column do
8104 (when (and (stringp xx)
8105 (> (org-string-width xx) fmax))
8106 (org-add-props xx nil
8107 'help-echo
8108 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8109 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8110 (unless (> f1 1)
8111 (error "Cannot narrow field starting with wide link \"%s\""
8112 (match-string 0 xx)))
8113 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8114 (add-text-properties (- f1 2) f1
8115 (list 'display org-narrow-column-arrow)
8116 xx)))))
8117 ;; Get the maximum width for each column
8118 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8119 ;; Get the fraction of numbers, to decide about alignment of the column
8120 (setq cnt 0 frac 0.0)
8121 (loop for x in column do
8122 (if (equal x "")
8124 (setq frac ( / (+ (* frac cnt)
8125 (if (string-match org-table-number-regexp x) 1 0))
8126 (setq cnt (1+ cnt))))))
8127 (push (>= frac org-table-number-fraction) typenums))
8128 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8130 ;; Store the alignment of this table, for later editing of single fields
8131 (setq org-table-last-alignment typenums
8132 org-table-last-column-widths lengths)
8134 ;; With invisible characters, `format' does not get the field width right
8135 ;; So we need to make these fields wide by hand.
8136 (when (or links emph)
8137 (loop for i from 0 upto (1- maxfields) do
8138 (setq len (nth i lengths))
8139 (loop for j from 0 upto (1- (length fields)) do
8140 (setq c (nthcdr i (car (nthcdr j fields))))
8141 (if (and (stringp (car c))
8142 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8143 ; (string-match org-bracket-link-regexp (car c))
8144 (< (org-string-width (car c)) len))
8145 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8147 ;; Compute the formats needed for output of the table
8148 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8149 (while (setq l (pop lengths))
8150 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8151 (setq rfmt (concat rfmt (format rfmt1 ty l))
8152 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8153 (setq rfmt (concat rfmt "\n")
8154 hfmt (concat (substring hfmt 0 -1) "|\n"))
8156 (setq new (mapconcat
8157 (lambda (l)
8158 (if l (apply 'format rfmt
8159 (append (pop fields) emptystrings))
8160 hfmt))
8161 lines ""))
8162 ;; Replace the old one
8163 (delete-region beg end)
8164 (move-marker end nil)
8165 (move-marker org-table-aligned-begin-marker (point))
8166 (insert new)
8167 (move-marker org-table-aligned-end-marker (point))
8168 (when (and orgtbl-mode (not (org-mode-p)))
8169 (goto-char org-table-aligned-begin-marker)
8170 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8171 ;; Try to move to the old location
8172 (goto-line winstartline)
8173 (setq winstart (point-at-bol))
8174 (goto-line linepos)
8175 (set-window-start (selected-window) winstart 'noforce)
8176 (org-table-goto-column colpos)
8177 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8178 (setq org-table-may-need-update nil)
8181 (defun org-string-width (s)
8182 "Compute width of string, ignoring invisible characters.
8183 This ignores character with invisibility property `org-link', and also
8184 characters with property `org-cwidth', because these will become invisible
8185 upon the next fontification round."
8186 (let (b l)
8187 (when (or (eq t buffer-invisibility-spec)
8188 (assq 'org-link buffer-invisibility-spec))
8189 (while (setq b (text-property-any 0 (length s)
8190 'invisible 'org-link s))
8191 (setq s (concat (substring s 0 b)
8192 (substring s (or (next-single-property-change
8193 b 'invisible s) (length s)))))))
8194 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8195 (setq s (concat (substring s 0 b)
8196 (substring s (or (next-single-property-change
8197 b 'org-cwidth s) (length s))))))
8198 (setq l (string-width s) b -1)
8199 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8200 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8203 (defun org-table-begin (&optional table-type)
8204 "Find the beginning of the table and return its position.
8205 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8206 (save-excursion
8207 (if (not (re-search-backward
8208 (if table-type org-table-any-border-regexp
8209 org-table-border-regexp)
8210 nil t))
8211 (progn (goto-char (point-min)) (point))
8212 (goto-char (match-beginning 0))
8213 (beginning-of-line 2)
8214 (point))))
8216 (defun org-table-end (&optional table-type)
8217 "Find the end of the table and return its position.
8218 With argument TABLE-TYPE, go to the end of a table.el-type table."
8219 (save-excursion
8220 (if (not (re-search-forward
8221 (if table-type org-table-any-border-regexp
8222 org-table-border-regexp)
8223 nil t))
8224 (goto-char (point-max))
8225 (goto-char (match-beginning 0)))
8226 (point-marker)))
8228 (defun org-table-justify-field-maybe (&optional new)
8229 "Justify the current field, text to left, number to right.
8230 Optional argument NEW may specify text to replace the current field content."
8231 (cond
8232 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8233 ((org-at-table-hline-p))
8234 ((and (not new)
8235 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8236 (current-buffer)))
8237 (< (point) org-table-aligned-begin-marker)
8238 (>= (point) org-table-aligned-end-marker)))
8239 ;; This is not the same table, force a full re-align
8240 (setq org-table-may-need-update t))
8241 (t ;; realign the current field, based on previous full realign
8242 (let* ((pos (point)) s
8243 (col (org-table-current-column))
8244 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8245 l f n o e)
8246 (when (> col 0)
8247 (skip-chars-backward "^|\n")
8248 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8249 (progn
8250 (setq s (match-string 1)
8251 o (match-string 0)
8252 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8253 e (not (= (match-beginning 2) (match-end 2))))
8254 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8255 l (if e "|" (setq org-table-may-need-update t) ""))
8256 n (format f s))
8257 (if new
8258 (if (<= (length new) l) ;; FIXME: length -> str-width?
8259 (setq n (format f new))
8260 (setq n (concat new "|") org-table-may-need-update t)))
8261 (or (equal n o)
8262 (let (org-table-may-need-update)
8263 (replace-match n t t))))
8264 (setq org-table-may-need-update t))
8265 (goto-char pos))))))
8267 (defun org-table-next-field ()
8268 "Go to the next field in the current table, creating new lines as needed.
8269 Before doing so, re-align the table if necessary."
8270 (interactive)
8271 (org-table-maybe-eval-formula)
8272 (org-table-maybe-recalculate-line)
8273 (if (and org-table-automatic-realign
8274 org-table-may-need-update)
8275 (org-table-align))
8276 (let ((end (org-table-end)))
8277 (if (org-at-table-hline-p)
8278 (end-of-line 1))
8279 (condition-case nil
8280 (progn
8281 (re-search-forward "|" end)
8282 (if (looking-at "[ \t]*$")
8283 (re-search-forward "|" end))
8284 (if (and (looking-at "-")
8285 org-table-tab-jumps-over-hlines
8286 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8287 (goto-char (match-beginning 1)))
8288 (if (looking-at "-")
8289 (progn
8290 (beginning-of-line 0)
8291 (org-table-insert-row 'below))
8292 (if (looking-at " ") (forward-char 1))))
8293 (error
8294 (org-table-insert-row 'below)))))
8296 (defun org-table-previous-field ()
8297 "Go to the previous field in the table.
8298 Before doing so, re-align the table if necessary."
8299 (interactive)
8300 (org-table-justify-field-maybe)
8301 (org-table-maybe-recalculate-line)
8302 (if (and org-table-automatic-realign
8303 org-table-may-need-update)
8304 (org-table-align))
8305 (if (org-at-table-hline-p)
8306 (end-of-line 1))
8307 (re-search-backward "|" (org-table-begin))
8308 (re-search-backward "|" (org-table-begin))
8309 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8310 (re-search-backward "|" (org-table-begin)))
8311 (if (looking-at "| ?")
8312 (goto-char (match-end 0))))
8314 (defun org-table-next-row ()
8315 "Go to the next row (same column) in the current table.
8316 Before doing so, re-align the table if necessary."
8317 (interactive)
8318 (org-table-maybe-eval-formula)
8319 (org-table-maybe-recalculate-line)
8320 (if (or (looking-at "[ \t]*$")
8321 (save-excursion (skip-chars-backward " \t") (bolp)))
8322 (newline)
8323 (if (and org-table-automatic-realign
8324 org-table-may-need-update)
8325 (org-table-align))
8326 (let ((col (org-table-current-column)))
8327 (beginning-of-line 2)
8328 (if (or (not (org-at-table-p))
8329 (org-at-table-hline-p))
8330 (progn
8331 (beginning-of-line 0)
8332 (org-table-insert-row 'below)))
8333 (org-table-goto-column col)
8334 (skip-chars-backward "^|\n\r")
8335 (if (looking-at " ") (forward-char 1)))))
8337 (defun org-table-copy-down (n)
8338 "Copy a field down in the current column.
8339 If the field at the cursor is empty, copy into it the content of the nearest
8340 non-empty field above. With argument N, use the Nth non-empty field.
8341 If the current field is not empty, it is copied down to the next row, and
8342 the cursor is moved with it. Therefore, repeating this command causes the
8343 column to be filled row-by-row.
8344 If the variable `org-table-copy-increment' is non-nil and the field is an
8345 integer or a timestamp, it will be incremented while copying. In the case of
8346 a timestamp, if the cursor is on the year, change the year. If it is on the
8347 month or the day, change that. Point will stay on the current date field
8348 in order to easily repeat the interval."
8349 (interactive "p")
8350 (let* ((colpos (org-table-current-column))
8351 (col (current-column))
8352 (field (org-table-get-field))
8353 (non-empty (string-match "[^ \t]" field))
8354 (beg (org-table-begin))
8355 txt)
8356 (org-table-check-inside-data-field)
8357 (if non-empty
8358 (progn
8359 (setq txt (org-trim field))
8360 (org-table-next-row)
8361 (org-table-blank-field))
8362 (save-excursion
8363 (setq txt
8364 (catch 'exit
8365 (while (progn (beginning-of-line 1)
8366 (re-search-backward org-table-dataline-regexp
8367 beg t))
8368 (org-table-goto-column colpos t)
8369 (if (and (looking-at
8370 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8371 (= (setq n (1- n)) 0))
8372 (throw 'exit (match-string 1))))))))
8373 (if txt
8374 (progn
8375 (if (and org-table-copy-increment
8376 (string-match "^[0-9]+$" txt))
8377 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8378 (insert txt)
8379 (move-to-column col)
8380 (if (and org-table-copy-increment (org-at-timestamp-p t))
8381 (org-timestamp-up 1)
8382 (org-table-maybe-recalculate-line))
8383 (org-table-align)
8384 (move-to-column col))
8385 (error "No non-empty field found"))))
8387 (defun org-table-check-inside-data-field ()
8388 "Is point inside a table data field?
8389 I.e. not on a hline or before the first or after the last column?
8390 This actually throws an error, so it aborts the current command."
8391 (if (or (not (org-at-table-p))
8392 (= (org-table-current-column) 0)
8393 (org-at-table-hline-p)
8394 (looking-at "[ \t]*$"))
8395 (error "Not in table data field")))
8397 (defvar org-table-clip nil
8398 "Clipboard for table regions.")
8400 (defun org-table-blank-field ()
8401 "Blank the current table field or active region."
8402 (interactive)
8403 (org-table-check-inside-data-field)
8404 (if (and (interactive-p) (org-region-active-p))
8405 (let (org-table-clip)
8406 (org-table-cut-region (region-beginning) (region-end)))
8407 (skip-chars-backward "^|")
8408 (backward-char 1)
8409 (if (looking-at "|[^|\n]+")
8410 (let* ((pos (match-beginning 0))
8411 (match (match-string 0))
8412 (len (org-string-width match)))
8413 (replace-match (concat "|" (make-string (1- len) ?\ )))
8414 (goto-char (+ 2 pos))
8415 (substring match 1)))))
8417 (defun org-table-get-field (&optional n replace)
8418 "Return the value of the field in column N of current row.
8419 N defaults to current field.
8420 If REPLACE is a string, replace field with this value. The return value
8421 is always the old value."
8422 (and n (org-table-goto-column n))
8423 (skip-chars-backward "^|\n")
8424 (backward-char 1)
8425 (if (looking-at "|[^|\r\n]*")
8426 (let* ((pos (match-beginning 0))
8427 (val (buffer-substring (1+ pos) (match-end 0))))
8428 (if replace
8429 (replace-match (concat "|" replace) t t))
8430 (goto-char (min (point-at-eol) (+ 2 pos)))
8431 val)
8432 (forward-char 1) ""))
8434 (defun org-table-field-info (arg)
8435 "Show info about the current field, and highlight any reference at point."
8436 (interactive "P")
8437 (org-table-get-specials)
8438 (save-excursion
8439 (let* ((pos (point))
8440 (col (org-table-current-column))
8441 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8442 (name (car (rassoc (list (org-current-line) col)
8443 org-table-named-field-locations)))
8444 (eql (org-table-get-stored-formulas))
8445 (dline (org-table-current-dline))
8446 (ref (format "@%d$%d" dline col))
8447 (ref1 (org-table-convert-refs-to-an ref))
8448 (fequation (or (assoc name eql) (assoc ref eql)))
8449 (cequation (assoc (int-to-string col) eql))
8450 (eqn (or fequation cequation)))
8451 (goto-char pos)
8452 (condition-case nil
8453 (org-table-show-reference 'local)
8454 (error nil))
8455 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8456 dline col
8457 (if cname (concat " or $" cname) "")
8458 dline col ref1
8459 (if name (concat " or $" name) "")
8460 ;; FIXME: formula info not correct if special table line
8461 (if eqn
8462 (concat ", formula: "
8463 (org-table-formula-to-user
8464 (concat
8465 (if (string-match "^[$@]"(car eqn)) "" "$")
8466 (car eqn) "=" (cdr eqn))))
8467 "")))))
8469 (defun org-table-current-column ()
8470 "Find out which column we are in.
8471 When called interactively, column is also displayed in echo area."
8472 (interactive)
8473 (if (interactive-p) (org-table-check-inside-data-field))
8474 (save-excursion
8475 (let ((cnt 0) (pos (point)))
8476 (beginning-of-line 1)
8477 (while (search-forward "|" pos t)
8478 (setq cnt (1+ cnt)))
8479 (if (interactive-p) (message "This is table column %d" cnt))
8480 cnt)))
8482 (defun org-table-current-dline ()
8483 "Find out what table data line we are in.
8484 Only datalins count for this."
8485 (interactive)
8486 (if (interactive-p) (org-table-check-inside-data-field))
8487 (save-excursion
8488 (let ((cnt 0) (pos (point)))
8489 (goto-char (org-table-begin))
8490 (while (<= (point) pos)
8491 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8492 (beginning-of-line 2))
8493 (if (interactive-p) (message "This is table line %d" cnt))
8494 cnt)))
8496 (defun org-table-goto-column (n &optional on-delim force)
8497 "Move the cursor to the Nth column in the current table line.
8498 With optional argument ON-DELIM, stop with point before the left delimiter
8499 of the field.
8500 If there are less than N fields, just go to after the last delimiter.
8501 However, when FORCE is non-nil, create new columns if necessary."
8502 (interactive "p")
8503 (let ((pos (point-at-eol)))
8504 (beginning-of-line 1)
8505 (when (> n 0)
8506 (while (and (> (setq n (1- n)) -1)
8507 (or (search-forward "|" pos t)
8508 (and force
8509 (progn (end-of-line 1)
8510 (skip-chars-backward "^|")
8511 (insert " | "))))))
8512 ; (backward-char 2) t)))))
8513 (when (and force (not (looking-at ".*|")))
8514 (save-excursion (end-of-line 1) (insert " | ")))
8515 (if on-delim
8516 (backward-char 1)
8517 (if (looking-at " ") (forward-char 1))))))
8519 (defun org-at-table-p (&optional table-type)
8520 "Return t if the cursor is inside an org-type table.
8521 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8522 (if org-enable-table-editor
8523 (save-excursion
8524 (beginning-of-line 1)
8525 (looking-at (if table-type org-table-any-line-regexp
8526 org-table-line-regexp)))
8527 nil))
8529 (defun org-at-table.el-p ()
8530 "Return t if and only if we are at a table.el table."
8531 (and (org-at-table-p 'any)
8532 (save-excursion
8533 (goto-char (org-table-begin 'any))
8534 (looking-at org-table1-hline-regexp))))
8536 (defun org-table-recognize-table.el ()
8537 "If there is a table.el table nearby, recognize it and move into it."
8538 (if org-table-tab-recognizes-table.el
8539 (if (org-at-table.el-p)
8540 (progn
8541 (beginning-of-line 1)
8542 (if (looking-at org-table-dataline-regexp)
8544 (if (looking-at org-table1-hline-regexp)
8545 (progn
8546 (beginning-of-line 2)
8547 (if (looking-at org-table-any-border-regexp)
8548 (beginning-of-line -1)))))
8549 (if (re-search-forward "|" (org-table-end t) t)
8550 (progn
8551 (require 'table)
8552 (if (table--at-cell-p (point))
8554 (message "recognizing table.el table...")
8555 (table-recognize-table)
8556 (message "recognizing table.el table...done")))
8557 (error "This should not happen..."))
8559 nil)
8560 nil))
8562 (defun org-at-table-hline-p ()
8563 "Return t if the cursor is inside a hline in a table."
8564 (if org-enable-table-editor
8565 (save-excursion
8566 (beginning-of-line 1)
8567 (looking-at org-table-hline-regexp))
8568 nil))
8570 (defun org-table-insert-column ()
8571 "Insert a new column into the table."
8572 (interactive)
8573 (if (not (org-at-table-p))
8574 (error "Not at a table"))
8575 (org-table-find-dataline)
8576 (let* ((col (max 1 (org-table-current-column)))
8577 (beg (org-table-begin))
8578 (end (org-table-end))
8579 ;; Current cursor position
8580 (linepos (org-current-line))
8581 (colpos col))
8582 (goto-char beg)
8583 (while (< (point) end)
8584 (if (org-at-table-hline-p)
8586 (org-table-goto-column col t)
8587 (insert "| "))
8588 (beginning-of-line 2))
8589 (move-marker end nil)
8590 (goto-line linepos)
8591 (org-table-goto-column colpos)
8592 (org-table-align)
8593 (org-table-fix-formulas "$" nil (1- col) 1)))
8595 (defun org-table-find-dataline ()
8596 "Find a dataline in the current table, which is needed for column commands."
8597 (if (and (org-at-table-p)
8598 (not (org-at-table-hline-p)))
8600 (let ((col (current-column))
8601 (end (org-table-end)))
8602 (move-to-column col)
8603 (while (and (< (point) end)
8604 (or (not (= (current-column) col))
8605 (org-at-table-hline-p)))
8606 (beginning-of-line 2)
8607 (move-to-column col))
8608 (if (and (org-at-table-p)
8609 (not (org-at-table-hline-p)))
8611 (error
8612 "Please position cursor in a data line for column operations")))))
8614 (defun org-table-delete-column ()
8615 "Delete a column from the table."
8616 (interactive)
8617 (if (not (org-at-table-p))
8618 (error "Not at a table"))
8619 (org-table-find-dataline)
8620 (org-table-check-inside-data-field)
8621 (let* ((col (org-table-current-column))
8622 (beg (org-table-begin))
8623 (end (org-table-end))
8624 ;; Current cursor position
8625 (linepos (org-current-line))
8626 (colpos col))
8627 (goto-char beg)
8628 (while (< (point) end)
8629 (if (org-at-table-hline-p)
8631 (org-table-goto-column col t)
8632 (and (looking-at "|[^|\n]+|")
8633 (replace-match "|")))
8634 (beginning-of-line 2))
8635 (move-marker end nil)
8636 (goto-line linepos)
8637 (org-table-goto-column colpos)
8638 (org-table-align)
8639 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8640 col -1 col)))
8642 (defun org-table-move-column-right ()
8643 "Move column to the right."
8644 (interactive)
8645 (org-table-move-column nil))
8646 (defun org-table-move-column-left ()
8647 "Move column to the left."
8648 (interactive)
8649 (org-table-move-column 'left))
8651 (defun org-table-move-column (&optional left)
8652 "Move the current column to the right. With arg LEFT, move to the left."
8653 (interactive "P")
8654 (if (not (org-at-table-p))
8655 (error "Not at a table"))
8656 (org-table-find-dataline)
8657 (org-table-check-inside-data-field)
8658 (let* ((col (org-table-current-column))
8659 (col1 (if left (1- col) col))
8660 (beg (org-table-begin))
8661 (end (org-table-end))
8662 ;; Current cursor position
8663 (linepos (org-current-line))
8664 (colpos (if left (1- col) (1+ col))))
8665 (if (and left (= col 1))
8666 (error "Cannot move column further left"))
8667 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8668 (error "Cannot move column further right"))
8669 (goto-char beg)
8670 (while (< (point) end)
8671 (if (org-at-table-hline-p)
8673 (org-table-goto-column col1 t)
8674 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8675 (replace-match "|\\2|\\1|")))
8676 (beginning-of-line 2))
8677 (move-marker end nil)
8678 (goto-line linepos)
8679 (org-table-goto-column colpos)
8680 (org-table-align)
8681 (org-table-fix-formulas
8682 "$" (list (cons (number-to-string col) (number-to-string colpos))
8683 (cons (number-to-string colpos) (number-to-string col))))))
8685 (defun org-table-move-row-down ()
8686 "Move table row down."
8687 (interactive)
8688 (org-table-move-row nil))
8689 (defun org-table-move-row-up ()
8690 "Move table row up."
8691 (interactive)
8692 (org-table-move-row 'up))
8694 (defun org-table-move-row (&optional up)
8695 "Move the current table line down. With arg UP, move it up."
8696 (interactive "P")
8697 (let* ((col (current-column))
8698 (pos (point))
8699 (hline1p (save-excursion (beginning-of-line 1)
8700 (looking-at org-table-hline-regexp)))
8701 (dline1 (org-table-current-dline))
8702 (dline2 (+ dline1 (if up -1 1)))
8703 (tonew (if up 0 2))
8704 txt hline2p)
8705 (beginning-of-line tonew)
8706 (unless (org-at-table-p)
8707 (goto-char pos)
8708 (error "Cannot move row further"))
8709 (setq hline2p (looking-at org-table-hline-regexp))
8710 (goto-char pos)
8711 (beginning-of-line 1)
8712 (setq pos (point))
8713 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8714 (delete-region (point) (1+ (point-at-eol)))
8715 (beginning-of-line tonew)
8716 (insert txt)
8717 (beginning-of-line 0)
8718 (move-to-column col)
8719 (unless (or hline1p hline2p)
8720 (org-table-fix-formulas
8721 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8722 (cons (number-to-string dline2) (number-to-string dline1)))))))
8724 (defun org-table-insert-row (&optional arg)
8725 "Insert a new row above the current line into the table.
8726 With prefix ARG, insert below the current line."
8727 (interactive "P")
8728 (if (not (org-at-table-p))
8729 (error "Not at a table"))
8730 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8731 (new (org-table-clean-line line)))
8732 ;; Fix the first field if necessary
8733 (if (string-match "^[ \t]*| *[#$] *|" line)
8734 (setq new (replace-match (match-string 0 line) t t new)))
8735 (beginning-of-line (if arg 2 1))
8736 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8737 (beginning-of-line 0)
8738 (re-search-forward "| ?" (point-at-eol) t)
8739 (and (or org-table-may-need-update org-table-overlay-coordinates)
8740 (org-table-align))
8741 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8743 (defun org-table-insert-hline (&optional above)
8744 "Insert a horizontal-line below the current line into the table.
8745 With prefix ABOVE, insert above the current line."
8746 (interactive "P")
8747 (if (not (org-at-table-p))
8748 (error "Not at a table"))
8749 (let ((line (org-table-clean-line
8750 (buffer-substring (point-at-bol) (point-at-eol))))
8751 (col (current-column)))
8752 (while (string-match "|\\( +\\)|" line)
8753 (setq line (replace-match
8754 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8755 ?-) "|") t t line)))
8756 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8757 (beginning-of-line (if above 1 2))
8758 (insert line "\n")
8759 (beginning-of-line (if above 1 -1))
8760 (move-to-column col)
8761 (and org-table-overlay-coordinates (org-table-align))))
8763 (defun org-table-hline-and-move (&optional same-column)
8764 "Insert a hline and move to the row below that line."
8765 (interactive "P")
8766 (let ((col (org-table-current-column)))
8767 (org-table-maybe-eval-formula)
8768 (org-table-maybe-recalculate-line)
8769 (org-table-insert-hline)
8770 (end-of-line 2)
8771 (if (looking-at "\n[ \t]*|-")
8772 (progn (insert "\n|") (org-table-align))
8773 (org-table-next-field))
8774 (if same-column (org-table-goto-column col))))
8776 (defun org-table-clean-line (s)
8777 "Convert a table line S into a string with only \"|\" and space.
8778 In particular, this does handle wide and invisible characters."
8779 (if (string-match "^[ \t]*|-" s)
8780 ;; It's a hline, just map the characters
8781 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8782 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8783 (setq s (replace-match
8784 (concat "|" (make-string (org-string-width (match-string 1 s))
8785 ?\ ) "|")
8786 t t s)))
8789 (defun org-table-kill-row ()
8790 "Delete the current row or horizontal line from the table."
8791 (interactive)
8792 (if (not (org-at-table-p))
8793 (error "Not at a table"))
8794 (let ((col (current-column))
8795 (dline (org-table-current-dline)))
8796 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8797 (if (not (org-at-table-p)) (beginning-of-line 0))
8798 (move-to-column col)
8799 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8800 dline -1 dline)))
8802 (defun org-table-sort-lines (with-case &optional sorting-type)
8803 "Sort table lines according to the column at point.
8805 The position of point indicates the column to be used for
8806 sorting, and the range of lines is the range between the nearest
8807 horizontal separator lines, or the entire table of no such lines
8808 exist. If point is before the first column, you will be prompted
8809 for the sorting column. If there is an active region, the mark
8810 specifies the first line and the sorting column, while point
8811 should be in the last line to be included into the sorting.
8813 The command then prompts for the sorting type which can be
8814 alphabetically, numerically, or by time (as given in a time stamp
8815 in the field). Sorting in reverse order is also possible.
8817 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8819 If SORTING-TYPE is specified when this function is called from a Lisp
8820 program, no prompting will take place. SORTING-TYPE must be a character,
8821 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8822 should be done in reverse order."
8823 (interactive "P")
8824 (let* ((thisline (org-current-line))
8825 (thiscol (org-table-current-column))
8826 beg end bcol ecol tend tbeg column lns pos)
8827 (when (equal thiscol 0)
8828 (if (interactive-p)
8829 (setq thiscol
8830 (string-to-number
8831 (read-string "Use column N for sorting: ")))
8832 (setq thiscol 1))
8833 (org-table-goto-column thiscol))
8834 (org-table-check-inside-data-field)
8835 (if (org-region-active-p)
8836 (progn
8837 (setq beg (region-beginning) end (region-end))
8838 (goto-char beg)
8839 (setq column (org-table-current-column)
8840 beg (point-at-bol))
8841 (goto-char end)
8842 (setq end (point-at-bol 2)))
8843 (setq column (org-table-current-column)
8844 pos (point)
8845 tbeg (org-table-begin)
8846 tend (org-table-end))
8847 (if (re-search-backward org-table-hline-regexp tbeg t)
8848 (setq beg (point-at-bol 2))
8849 (goto-char tbeg)
8850 (setq beg (point-at-bol 1)))
8851 (goto-char pos)
8852 (if (re-search-forward org-table-hline-regexp tend t)
8853 (setq end (point-at-bol 1))
8854 (goto-char tend)
8855 (setq end (point-at-bol))))
8856 (setq beg (move-marker (make-marker) beg)
8857 end (move-marker (make-marker) end))
8858 (untabify beg end)
8859 (goto-char beg)
8860 (org-table-goto-column column)
8861 (skip-chars-backward "^|")
8862 (setq bcol (current-column))
8863 (org-table-goto-column (1+ column))
8864 (skip-chars-backward "^|")
8865 (setq ecol (1- (current-column)))
8866 (org-table-goto-column column)
8867 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8868 (org-split-string (buffer-substring beg end) "\n")))
8869 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8870 (delete-region beg end)
8871 (move-marker beg nil)
8872 (move-marker end nil)
8873 (insert (mapconcat 'cdr lns "\n") "\n")
8874 (goto-line thisline)
8875 (org-table-goto-column thiscol)
8876 (message "%d lines sorted, based on column %d" (length lns) column)))
8878 (defun org-table-cut-region (beg end)
8879 "Copy region in table to the clipboard and blank all relevant fields."
8880 (interactive "r")
8881 (org-table-copy-region beg end 'cut))
8883 (defun org-table-copy-region (beg end &optional cut)
8884 "Copy rectangular region in table to clipboard.
8885 A special clipboard is used which can only be accessed
8886 with `org-table-paste-rectangle'."
8887 (interactive "rP")
8888 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8889 region cols
8890 (rpl (if cut " " nil)))
8891 (goto-char beg)
8892 (org-table-check-inside-data-field)
8893 (setq l01 (org-current-line)
8894 c01 (org-table-current-column))
8895 (goto-char end)
8896 (org-table-check-inside-data-field)
8897 (setq l02 (org-current-line)
8898 c02 (org-table-current-column))
8899 (setq l1 (min l01 l02) l2 (max l01 l02)
8900 c1 (min c01 c02) c2 (max c01 c02))
8901 (catch 'exit
8902 (while t
8903 (catch 'nextline
8904 (if (> l1 l2) (throw 'exit t))
8905 (goto-line l1)
8906 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8907 (setq cols nil ic1 c1 ic2 c2)
8908 (while (< ic1 (1+ ic2))
8909 (push (org-table-get-field ic1 rpl) cols)
8910 (setq ic1 (1+ ic1)))
8911 (push (nreverse cols) region)
8912 (setq l1 (1+ l1)))))
8913 (setq org-table-clip (nreverse region))
8914 (if cut (org-table-align))
8915 org-table-clip))
8917 (defun org-table-paste-rectangle ()
8918 "Paste a rectangular region into a table.
8919 The upper right corner ends up in the current field. All involved fields
8920 will be overwritten. If the rectangle does not fit into the present table,
8921 the table is enlarged as needed. The process ignores horizontal separator
8922 lines."
8923 (interactive)
8924 (unless (and org-table-clip (listp org-table-clip))
8925 (error "First cut/copy a region to paste!"))
8926 (org-table-check-inside-data-field)
8927 (let* ((clip org-table-clip)
8928 (line (org-current-line))
8929 (col (org-table-current-column))
8930 (org-enable-table-editor t)
8931 (org-table-automatic-realign nil)
8932 c cols field)
8933 (while (setq cols (pop clip))
8934 (while (org-at-table-hline-p) (beginning-of-line 2))
8935 (if (not (org-at-table-p))
8936 (progn (end-of-line 0) (org-table-next-field)))
8937 (setq c col)
8938 (while (setq field (pop cols))
8939 (org-table-goto-column c nil 'force)
8940 (org-table-get-field nil field)
8941 (setq c (1+ c)))
8942 (beginning-of-line 2))
8943 (goto-line line)
8944 (org-table-goto-column col)
8945 (org-table-align)))
8947 (defun org-table-convert ()
8948 "Convert from `org-mode' table to table.el and back.
8949 Obviously, this only works within limits. When an Org-mode table is
8950 converted to table.el, all horizontal separator lines get lost, because
8951 table.el uses these as cell boundaries and has no notion of horizontal lines.
8952 A table.el table can be converted to an Org-mode table only if it does not
8953 do row or column spanning. Multiline cells will become multiple cells.
8954 Beware, Org-mode does not test if the table can be successfully converted - it
8955 blindly applies a recipe that works for simple tables."
8956 (interactive)
8957 (require 'table)
8958 (if (org-at-table.el-p)
8959 ;; convert to Org-mode table
8960 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8961 (end (move-marker (make-marker) (org-table-end t))))
8962 (table-unrecognize-region beg end)
8963 (goto-char beg)
8964 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8965 (replace-match ""))
8966 (goto-char beg))
8967 (if (org-at-table-p)
8968 ;; convert to table.el table
8969 (let ((beg (move-marker (make-marker) (org-table-begin)))
8970 (end (move-marker (make-marker) (org-table-end))))
8971 ;; first, get rid of all horizontal lines
8972 (goto-char beg)
8973 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8974 (replace-match ""))
8975 ;; insert a hline before first
8976 (goto-char beg)
8977 (org-table-insert-hline 'above)
8978 (beginning-of-line -1)
8979 ;; insert a hline after each line
8980 (while (progn (beginning-of-line 3) (< (point) end))
8981 (org-table-insert-hline))
8982 (goto-char beg)
8983 (setq end (move-marker end (org-table-end)))
8984 ;; replace "+" at beginning and ending of hlines
8985 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8986 (replace-match "\\1+-"))
8987 (goto-char beg)
8988 (while (re-search-forward "-|[ \t]*$" end t)
8989 (replace-match "-+"))
8990 (goto-char beg)))))
8992 (defun org-table-wrap-region (arg)
8993 "Wrap several fields in a column like a paragraph.
8994 This is useful if you'd like to spread the contents of a field over several
8995 lines, in order to keep the table compact.
8997 If there is an active region, and both point and mark are in the same column,
8998 the text in the column is wrapped to minimum width for the given number of
8999 lines. Generally, this makes the table more compact. A prefix ARG may be
9000 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9001 formats the selected text to two lines. If the region was longer than two
9002 lines, the remaining lines remain empty. A negative prefix argument reduces
9003 the current number of lines by that amount. The wrapped text is pasted back
9004 into the table. If you formatted it to more lines than it was before, fields
9005 further down in the table get overwritten - so you might need to make space in
9006 the table first.
9008 If there is no region, the current field is split at the cursor position and
9009 the text fragment to the right of the cursor is prepended to the field one
9010 line down.
9012 If there is no region, but you specify a prefix ARG, the current field gets
9013 blank, and the content is appended to the field above."
9014 (interactive "P")
9015 (org-table-check-inside-data-field)
9016 (if (org-region-active-p)
9017 ;; There is a region: fill as a paragraph
9018 (let* ((beg (region-beginning))
9019 (cline (save-excursion (goto-char beg) (org-current-line)))
9020 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9021 nlines)
9022 (org-table-cut-region (region-beginning) (region-end))
9023 (if (> (length (car org-table-clip)) 1)
9024 (error "Region must be limited to single column"))
9025 (setq nlines (if arg
9026 (if (< arg 1)
9027 (+ (length org-table-clip) arg)
9028 arg)
9029 (length org-table-clip)))
9030 (setq org-table-clip
9031 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9032 nil nlines)))
9033 (goto-line cline)
9034 (org-table-goto-column ccol)
9035 (org-table-paste-rectangle))
9036 ;; No region, split the current field at point
9037 (if arg
9038 ;; combine with field above
9039 (let ((s (org-table-blank-field))
9040 (col (org-table-current-column)))
9041 (beginning-of-line 0)
9042 (while (org-at-table-hline-p) (beginning-of-line 0))
9043 (org-table-goto-column col)
9044 (skip-chars-forward "^|")
9045 (skip-chars-backward " ")
9046 (insert " " (org-trim s))
9047 (org-table-align))
9048 ;; split field
9049 (when (looking-at "\\([^|]+\\)+|")
9050 (let ((s (match-string 1)))
9051 (replace-match " |")
9052 (goto-char (match-beginning 0))
9053 (org-table-next-row)
9054 (insert (org-trim s) " ")
9055 (org-table-align))))))
9057 (defvar org-field-marker nil)
9059 (defun org-table-edit-field (arg)
9060 "Edit table field in a different window.
9061 This is mainly useful for fields that contain hidden parts.
9062 When called with a \\[universal-argument] prefix, just make the full field visible so that
9063 it can be edited in place."
9064 (interactive "P")
9065 (if arg
9066 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9067 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9068 (remove-text-properties b e '(org-cwidth t invisible t
9069 display t intangible t))
9070 (if (and (boundp 'font-lock-mode) font-lock-mode)
9071 (font-lock-fontify-block)))
9072 (let ((pos (move-marker (make-marker) (point)))
9073 (field (org-table-get-field))
9074 (cw (current-window-configuration))
9076 (org-switch-to-buffer-other-window "*Org tmp*")
9077 (erase-buffer)
9078 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9079 (let ((org-inhibit-startup t)) (org-mode))
9080 (goto-char (setq p (point-max)))
9081 (insert (org-trim field))
9082 (remove-text-properties p (point-max)
9083 '(invisible t org-cwidth t display t
9084 intangible t))
9085 (goto-char p)
9086 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9087 (org-set-local 'org-window-configuration cw)
9088 (org-set-local 'org-field-marker pos)
9089 (message "Edit and finish with C-c C-c"))))
9091 (defun org-table-finish-edit-field ()
9092 "Finish editing a table data field.
9093 Remove all newline characters, insert the result into the table, realign
9094 the table and kill the editing buffer."
9095 (let ((pos org-field-marker)
9096 (cw org-window-configuration)
9097 (cb (current-buffer))
9098 text)
9099 (goto-char (point-min))
9100 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9101 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9102 (replace-match " "))
9103 (setq text (org-trim (buffer-string)))
9104 (set-window-configuration cw)
9105 (kill-buffer cb)
9106 (select-window (get-buffer-window (marker-buffer pos)))
9107 (goto-char pos)
9108 (move-marker pos nil)
9109 (org-table-check-inside-data-field)
9110 (org-table-get-field nil text)
9111 (org-table-align)
9112 (message "New field value inserted")))
9114 (defun org-trim (s)
9115 "Remove whitespace at beginning and end of string."
9116 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9117 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9120 (defun org-wrap (string &optional width lines)
9121 "Wrap string to either a number of lines, or a width in characters.
9122 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9123 that costs. If there is a word longer than WIDTH, the text is actually
9124 wrapped to the length of that word.
9125 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9126 many lines, whatever width that takes.
9127 The return value is a list of lines, without newlines at the end."
9128 (let* ((words (org-split-string string "[ \t\n]+"))
9129 (maxword (apply 'max (mapcar 'org-string-width words)))
9130 w ll)
9131 (cond (width
9132 (org-do-wrap words (max maxword width)))
9133 (lines
9134 (setq w maxword)
9135 (setq ll (org-do-wrap words maxword))
9136 (if (<= (length ll) lines)
9138 (setq ll words)
9139 (while (> (length ll) lines)
9140 (setq w (1+ w))
9141 (setq ll (org-do-wrap words w)))
9142 ll))
9143 (t (error "Cannot wrap this")))))
9146 (defun org-do-wrap (words width)
9147 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9148 (let (lines line)
9149 (while words
9150 (setq line (pop words))
9151 (while (and words (< (+ (length line) (length (car words))) width))
9152 (setq line (concat line " " (pop words))))
9153 (setq lines (push line lines)))
9154 (nreverse lines)))
9156 (defun org-split-string (string &optional separators)
9157 "Splits STRING into substrings at SEPARATORS.
9158 No empty strings are returned if there are matches at the beginning
9159 and end of string."
9160 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9161 (start 0)
9162 notfirst
9163 (list nil))
9164 (while (and (string-match rexp string
9165 (if (and notfirst
9166 (= start (match-beginning 0))
9167 (< start (length string)))
9168 (1+ start) start))
9169 (< (match-beginning 0) (length string)))
9170 (setq notfirst t)
9171 (or (eq (match-beginning 0) 0)
9172 (and (eq (match-beginning 0) (match-end 0))
9173 (eq (match-beginning 0) start))
9174 (setq list
9175 (cons (substring string start (match-beginning 0))
9176 list)))
9177 (setq start (match-end 0)))
9178 (or (eq start (length string))
9179 (setq list
9180 (cons (substring string start)
9181 list)))
9182 (nreverse list)))
9184 (defun org-table-map-tables (function)
9185 "Apply FUNCTION to the start of all tables in the buffer."
9186 (save-excursion
9187 (save-restriction
9188 (widen)
9189 (goto-char (point-min))
9190 (while (re-search-forward org-table-any-line-regexp nil t)
9191 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9192 (beginning-of-line 1)
9193 (if (looking-at org-table-line-regexp)
9194 (save-excursion (funcall function)))
9195 (re-search-forward org-table-any-border-regexp nil 1))))
9196 (message "Mapping tables: done"))
9198 (defvar org-timecnt) ; dynamically scoped parameter
9200 (defun org-table-sum (&optional beg end nlast)
9201 "Sum numbers in region of current table column.
9202 The result will be displayed in the echo area, and will be available
9203 as kill to be inserted with \\[yank].
9205 If there is an active region, it is interpreted as a rectangle and all
9206 numbers in that rectangle will be summed. If there is no active
9207 region and point is located in a table column, sum all numbers in that
9208 column.
9210 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9211 numbers are assumed to be times as well (in decimal hours) and the
9212 numbers are added as such.
9214 If NLAST is a number, only the NLAST fields will actually be summed."
9215 (interactive)
9216 (save-excursion
9217 (let (col (org-timecnt 0) diff h m s org-table-clip)
9218 (cond
9219 ((and beg end)) ; beg and end given explicitly
9220 ((org-region-active-p)
9221 (setq beg (region-beginning) end (region-end)))
9223 (setq col (org-table-current-column))
9224 (goto-char (org-table-begin))
9225 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9226 (error "No table data"))
9227 (org-table-goto-column col)
9228 (setq beg (point))
9229 (goto-char (org-table-end))
9230 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9231 (error "No table data"))
9232 (org-table-goto-column col)
9233 (setq end (point))))
9234 (let* ((items (apply 'append (org-table-copy-region beg end)))
9235 (items1 (cond ((not nlast) items)
9236 ((>= nlast (length items)) items)
9237 (t (setq items (reverse items))
9238 (setcdr (nthcdr (1- nlast) items) nil)
9239 (nreverse items))))
9240 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9241 items1)))
9242 (res (apply '+ numbers))
9243 (sres (if (= org-timecnt 0)
9244 (format "%g" res)
9245 (setq diff (* 3600 res)
9246 h (floor (/ diff 3600)) diff (mod diff 3600)
9247 m (floor (/ diff 60)) diff (mod diff 60)
9248 s diff)
9249 (format "%d:%02d:%02d" h m s))))
9250 (kill-new sres)
9251 (if (interactive-p)
9252 (message "%s"
9253 (substitute-command-keys
9254 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9255 (length numbers) sres))))
9256 sres))))
9258 (defun org-table-get-number-for-summing (s)
9259 (let (n)
9260 (if (string-match "^ *|? *" s)
9261 (setq s (replace-match "" nil nil s)))
9262 (if (string-match " *|? *$" s)
9263 (setq s (replace-match "" nil nil s)))
9264 (setq n (string-to-number s))
9265 (cond
9266 ((and (string-match "0" s)
9267 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9268 ((string-match "\\`[ \t]+\\'" s) nil)
9269 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9270 (let ((h (string-to-number (or (match-string 1 s) "0")))
9271 (m (string-to-number (or (match-string 2 s) "0")))
9272 (s (string-to-number (or (match-string 4 s) "0"))))
9273 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9274 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9275 ((equal n 0) nil)
9276 (t n))))
9278 (defun org-table-current-field-formula (&optional key noerror)
9279 "Return the formula active for the current field.
9280 Assumes that specials are in place.
9281 If KEY is given, return the key to this formula.
9282 Otherwise return the formula preceeded with \"=\" or \":=\"."
9283 (let* ((name (car (rassoc (list (org-current-line)
9284 (org-table-current-column))
9285 org-table-named-field-locations)))
9286 (col (org-table-current-column))
9287 (scol (int-to-string col))
9288 (ref (format "@%d$%d" (org-table-current-dline) col))
9289 (stored-list (org-table-get-stored-formulas noerror))
9290 (ass (or (assoc name stored-list)
9291 (assoc ref stored-list)
9292 (assoc scol stored-list))))
9293 (if key
9294 (car ass)
9295 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9296 (cdr ass))))))
9298 (defun org-table-get-formula (&optional equation named)
9299 "Read a formula from the minibuffer, offer stored formula as default.
9300 When NAMED is non-nil, look for a named equation."
9301 (let* ((stored-list (org-table-get-stored-formulas))
9302 (name (car (rassoc (list (org-current-line)
9303 (org-table-current-column))
9304 org-table-named-field-locations)))
9305 (ref (format "@%d$%d" (org-table-current-dline)
9306 (org-table-current-column)))
9307 (refass (assoc ref stored-list))
9308 (scol (if named
9309 (if name name ref)
9310 (int-to-string (org-table-current-column))))
9311 (dummy (and (or name refass) (not named)
9312 (not (y-or-n-p "Replace field formula with column formula? " ))
9313 (error "Abort")))
9314 (name (or name ref))
9315 (org-table-may-need-update nil)
9316 (stored (cdr (assoc scol stored-list)))
9317 (eq (cond
9318 ((and stored equation (string-match "^ *=? *$" equation))
9319 stored)
9320 ((stringp equation)
9321 equation)
9322 (t (org-table-formula-from-user
9323 (read-string
9324 (org-table-formula-to-user
9325 (format "%s formula %s%s="
9326 (if named "Field" "Column")
9327 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9328 scol))
9329 (if stored (org-table-formula-to-user stored) "")
9330 'org-table-formula-history
9331 )))))
9332 mustsave)
9333 (when (not (string-match "\\S-" eq))
9334 ;; remove formula
9335 (setq stored-list (delq (assoc scol stored-list) stored-list))
9336 (org-table-store-formulas stored-list)
9337 (error "Formula removed"))
9338 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9339 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9340 (if (and name (not named))
9341 ;; We set the column equation, delete the named one.
9342 (setq stored-list (delq (assoc name stored-list) stored-list)
9343 mustsave t))
9344 (if stored
9345 (setcdr (assoc scol stored-list) eq)
9346 (setq stored-list (cons (cons scol eq) stored-list)))
9347 (if (or mustsave (not (equal stored eq)))
9348 (org-table-store-formulas stored-list))
9349 eq))
9351 (defun org-table-store-formulas (alist)
9352 "Store the list of formulas below the current table."
9353 (setq alist (sort alist 'org-table-formula-less-p))
9354 (save-excursion
9355 (goto-char (org-table-end))
9356 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9357 (progn
9358 ;; don't overwrite TBLFM, we might use text properties to store stuff
9359 (goto-char (match-beginning 2))
9360 (delete-region (match-beginning 2) (match-end 0)))
9361 (insert "#+TBLFM:"))
9362 (insert " "
9363 (mapconcat (lambda (x)
9364 (concat
9365 (if (equal (string-to-char (car x)) ?@) "" "$")
9366 (car x) "=" (cdr x)))
9367 alist "::")
9368 "\n")))
9370 (defsubst org-table-formula-make-cmp-string (a)
9371 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9372 (concat
9373 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9374 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9375 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9377 (defun org-table-formula-less-p (a b)
9378 "Compare two formulas for sorting."
9379 (let ((as (org-table-formula-make-cmp-string (car a)))
9380 (bs (org-table-formula-make-cmp-string (car b))))
9381 (and as bs (string< as bs))))
9383 (defun org-table-get-stored-formulas (&optional noerror)
9384 "Return an alist with the stored formulas directly after current table."
9385 (interactive)
9386 (let (scol eq eq-alist strings string seen)
9387 (save-excursion
9388 (goto-char (org-table-end))
9389 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9390 (setq strings (org-split-string (match-string 2) " *:: *"))
9391 (while (setq string (pop strings))
9392 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9393 (setq scol (if (match-end 2)
9394 (match-string 2 string)
9395 (match-string 1 string))
9396 eq (match-string 3 string)
9397 eq-alist (cons (cons scol eq) eq-alist))
9398 (if (member scol seen)
9399 (if noerror
9400 (progn
9401 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9402 (ding)
9403 (sit-for 2))
9404 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9405 (push scol seen))))))
9406 (nreverse eq-alist)))
9408 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9409 "Modify the equations after the table structure has been edited.
9410 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9411 For all numbers larger than LIMIT, shift them by DELTA."
9412 (save-excursion
9413 (goto-char (org-table-end))
9414 (when (looking-at "#\\+TBLFM:")
9415 (let ((re (concat key "\\([0-9]+\\)"))
9416 (re2
9417 (when remove
9418 (if (equal key "$")
9419 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9420 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9421 s n a)
9422 (when remove
9423 (while (re-search-forward re2 (point-at-eol) t)
9424 (replace-match "")))
9425 (while (re-search-forward re (point-at-eol) t)
9426 (setq s (match-string 1) n (string-to-number s))
9427 (cond
9428 ((setq a (assoc s replace))
9429 (replace-match (concat key (cdr a)) t t))
9430 ((and limit (> n limit))
9431 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9433 (defun org-table-get-specials ()
9434 "Get the column names and local parameters for this table."
9435 (save-excursion
9436 (let ((beg (org-table-begin)) (end (org-table-end))
9437 names name fields fields1 field cnt
9438 c v l line col types dlines hlines)
9439 (setq org-table-column-names nil
9440 org-table-local-parameters nil
9441 org-table-named-field-locations nil
9442 org-table-current-begin-line nil
9443 org-table-current-begin-pos nil
9444 org-table-current-line-types nil)
9445 (goto-char beg)
9446 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9447 (setq names (org-split-string (match-string 1) " *| *")
9448 cnt 1)
9449 (while (setq name (pop names))
9450 (setq cnt (1+ cnt))
9451 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9452 (push (cons name (int-to-string cnt)) org-table-column-names))))
9453 (setq org-table-column-names (nreverse org-table-column-names))
9454 (setq org-table-column-name-regexp
9455 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9456 (goto-char beg)
9457 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9458 (setq fields (org-split-string (match-string 1) " *| *"))
9459 (while (setq field (pop fields))
9460 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9461 (push (cons (match-string 1 field) (match-string 2 field))
9462 org-table-local-parameters))))
9463 (goto-char beg)
9464 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9465 (setq c (match-string 1)
9466 fields (org-split-string (match-string 2) " *| *"))
9467 (save-excursion
9468 (beginning-of-line (if (equal c "_") 2 0))
9469 (setq line (org-current-line) col 1)
9470 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9471 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9472 (while (and fields1 (setq field (pop fields)))
9473 (setq v (pop fields1) col (1+ col))
9474 (when (and (stringp field) (stringp v)
9475 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9476 (push (cons field v) org-table-local-parameters)
9477 (push (list field line col) org-table-named-field-locations))))
9478 ;; Analyse the line types
9479 (goto-char beg)
9480 (setq org-table-current-begin-line (org-current-line)
9481 org-table-current-begin-pos (point)
9482 l org-table-current-begin-line)
9483 (while (looking-at "[ \t]*|\\(-\\)?")
9484 (push (if (match-end 1) 'hline 'dline) types)
9485 (if (match-end 1) (push l hlines) (push l dlines))
9486 (beginning-of-line 2)
9487 (setq l (1+ l)))
9488 (setq org-table-current-line-types (apply 'vector (nreverse types))
9489 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9490 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9492 (defun org-table-maybe-eval-formula ()
9493 "Check if the current field starts with \"=\" or \":=\".
9494 If yes, store the formula and apply it."
9495 ;; We already know we are in a table. Get field will only return a formula
9496 ;; when appropriate. It might return a separator line, but no problem.
9497 (when org-table-formula-evaluate-inline
9498 (let* ((field (org-trim (or (org-table-get-field) "")))
9499 named eq)
9500 (when (string-match "^:?=\\(.*\\)" field)
9501 (setq named (equal (string-to-char field) ?:)
9502 eq (match-string 1 field))
9503 (if (or (fboundp 'calc-eval)
9504 (equal (substring eq 0 (min 2 (length eq))) "'("))
9505 (org-table-eval-formula (if named '(4) nil)
9506 (org-table-formula-from-user eq))
9507 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9509 (defvar org-recalc-commands nil
9510 "List of commands triggering the recalculation of a line.
9511 Will be filled automatically during use.")
9513 (defvar org-recalc-marks
9514 '((" " . "Unmarked: no special line, no automatic recalculation")
9515 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9516 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9517 ("!" . "Column name definition line. Reference in formula as $name.")
9518 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9519 ("_" . "Names for values in row below this one.")
9520 ("^" . "Names for values in row above this one.")))
9522 (defun org-table-rotate-recalc-marks (&optional newchar)
9523 "Rotate the recalculation mark in the first column.
9524 If in any row, the first field is not consistent with a mark,
9525 insert a new column for the markers.
9526 When there is an active region, change all the lines in the region,
9527 after prompting for the marking character.
9528 After each change, a message will be displayed indicating the meaning
9529 of the new mark."
9530 (interactive)
9531 (unless (org-at-table-p) (error "Not at a table"))
9532 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9533 (beg (org-table-begin))
9534 (end (org-table-end))
9535 (l (org-current-line))
9536 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9537 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9538 (have-col
9539 (save-excursion
9540 (goto-char beg)
9541 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9542 (col (org-table-current-column))
9543 (forcenew (car (assoc newchar org-recalc-marks)))
9544 epos new)
9545 (when l1
9546 (message "Change region to what mark? Type # * ! $ or SPC: ")
9547 (setq newchar (char-to-string (read-char-exclusive))
9548 forcenew (car (assoc newchar org-recalc-marks))))
9549 (if (and newchar (not forcenew))
9550 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9551 newchar))
9552 (if l1 (goto-line l1))
9553 (save-excursion
9554 (beginning-of-line 1)
9555 (unless (looking-at org-table-dataline-regexp)
9556 (error "Not at a table data line")))
9557 (unless have-col
9558 (org-table-goto-column 1)
9559 (org-table-insert-column)
9560 (org-table-goto-column (1+ col)))
9561 (setq epos (point-at-eol))
9562 (save-excursion
9563 (beginning-of-line 1)
9564 (org-table-get-field
9565 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9566 (concat " "
9567 (setq new (or forcenew
9568 (cadr (member (match-string 1) marks))))
9569 " ")
9570 " # ")))
9571 (if (and l1 l2)
9572 (progn
9573 (goto-line l1)
9574 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9575 (and (looking-at org-table-dataline-regexp)
9576 (org-table-get-field 1 (concat " " new " "))))
9577 (goto-line l1)))
9578 (if (not (= epos (point-at-eol))) (org-table-align))
9579 (goto-line l)
9580 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9582 (defun org-table-maybe-recalculate-line ()
9583 "Recompute the current line if marked for it, and if we haven't just done it."
9584 (interactive)
9585 (and org-table-allow-automatic-line-recalculation
9586 (not (and (memq last-command org-recalc-commands)
9587 (equal org-last-recalc-line (org-current-line))))
9588 (save-excursion (beginning-of-line 1)
9589 (looking-at org-table-auto-recalculate-regexp))
9590 (org-table-recalculate) t))
9592 (defvar org-table-formula-debug nil
9593 "Non-nil means, debug table formulas.
9594 When nil, simply write \"#ERROR\" in corrupted fields.")
9595 (make-variable-buffer-local 'org-table-formula-debug)
9597 (defvar modes)
9598 (defsubst org-set-calc-mode (var &optional value)
9599 (if (stringp var)
9600 (setq var (assoc var '(("D" calc-angle-mode deg)
9601 ("R" calc-angle-mode rad)
9602 ("F" calc-prefer-frac t)
9603 ("S" calc-symbolic-mode t)))
9604 value (nth 2 var) var (nth 1 var)))
9605 (if (memq var modes)
9606 (setcar (cdr (memq var modes)) value)
9607 (cons var (cons value modes)))
9608 modes)
9610 (defun org-table-eval-formula (&optional arg equation
9611 suppress-align suppress-const
9612 suppress-store suppress-analysis)
9613 "Replace the table field value at the cursor by the result of a calculation.
9615 This function makes use of Dave Gillespie's Calc package, in my view the
9616 most exciting program ever written for GNU Emacs. So you need to have Calc
9617 installed in order to use this function.
9619 In a table, this command replaces the value in the current field with the
9620 result of a formula. It also installs the formula as the \"current\" column
9621 formula, by storing it in a special line below the table. When called
9622 with a `C-u' prefix, the current field must ba a named field, and the
9623 formula is installed as valid in only this specific field.
9625 When called with two `C-u' prefixes, insert the active equation
9626 for the field back into the current field, so that it can be
9627 edited there. This is useful in order to use \\[org-table-show-reference]
9628 to check the referenced fields.
9630 When called, the command first prompts for a formula, which is read in
9631 the minibuffer. Previously entered formulas are available through the
9632 history list, and the last used formula is offered as a default.
9633 These stored formulas are adapted correctly when moving, inserting, or
9634 deleting columns with the corresponding commands.
9636 The formula can be any algebraic expression understood by the Calc package.
9637 For details, see the Org-mode manual.
9639 This function can also be called from Lisp programs and offers
9640 additional arguments: EQUATION can be the formula to apply. If this
9641 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9642 used to speed-up recursive calls by by-passing unnecessary aligns.
9643 SUPPRESS-CONST suppresses the interpretation of constants in the
9644 formula, assuming that this has been done already outside the function.
9645 SUPPRESS-STORE means the formula should not be stored, either because
9646 it is already stored, or because it is a modified equation that should
9647 not overwrite the stored one."
9648 (interactive "P")
9649 (org-table-check-inside-data-field)
9650 (or suppress-analysis (org-table-get-specials))
9651 (if (equal arg '(16))
9652 (let ((eq (org-table-current-field-formula)))
9653 (or eq (error "No equation active for current field"))
9654 (org-table-get-field nil eq)
9655 (org-table-align)
9656 (setq org-table-may-need-update t))
9657 (let* (fields
9658 (ndown (if (integerp arg) arg 1))
9659 (org-table-automatic-realign nil)
9660 (case-fold-search nil)
9661 (down (> ndown 1))
9662 (formula (if (and equation suppress-store)
9663 equation
9664 (org-table-get-formula equation (equal arg '(4)))))
9665 (n0 (org-table-current-column))
9666 (modes (copy-sequence org-calc-default-modes))
9667 (numbers nil) ; was a variable, now fixed default
9668 (keep-empty nil)
9669 n form form0 bw fmt x ev orig c lispp literal)
9670 ;; Parse the format string. Since we have a lot of modes, this is
9671 ;; a lot of work. However, I think calc still uses most of the time.
9672 (if (string-match ";" formula)
9673 (let ((tmp (org-split-string formula ";")))
9674 (setq formula (car tmp)
9675 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9676 (nth 1 tmp)))
9677 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9678 (setq c (string-to-char (match-string 1 fmt))
9679 n (string-to-number (match-string 2 fmt)))
9680 (if (= c ?p)
9681 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9682 (setq modes (org-set-calc-mode
9683 'calc-float-format
9684 (list (cdr (assoc c '((?n . float) (?f . fix)
9685 (?s . sci) (?e . eng))))
9686 n))))
9687 (setq fmt (replace-match "" t t fmt)))
9688 (if (string-match "[NT]" fmt)
9689 (setq numbers (equal (match-string 0 fmt) "N")
9690 fmt (replace-match "" t t fmt)))
9691 (if (string-match "L" fmt)
9692 (setq literal t
9693 fmt (replace-match "" t t fmt)))
9694 (if (string-match "E" fmt)
9695 (setq keep-empty t
9696 fmt (replace-match "" t t fmt)))
9697 (while (string-match "[DRFS]" fmt)
9698 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9699 (setq fmt (replace-match "" t t fmt)))
9700 (unless (string-match "\\S-" fmt)
9701 (setq fmt nil))))
9702 (if (and (not suppress-const) org-table-formula-use-constants)
9703 (setq formula (org-table-formula-substitute-names formula)))
9704 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9705 (while (> ndown 0)
9706 (setq fields (org-split-string
9707 (org-no-properties
9708 (buffer-substring (point-at-bol) (point-at-eol)))
9709 " *| *"))
9710 (if (eq numbers t)
9711 (setq fields (mapcar
9712 (lambda (x) (number-to-string (string-to-number x)))
9713 fields)))
9714 (setq ndown (1- ndown))
9715 (setq form (copy-sequence formula)
9716 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9717 (if (and lispp literal) (setq lispp 'literal))
9718 ;; Check for old vertical references
9719 (setq form (org-rewrite-old-row-references form))
9720 ;; Insert complex ranges
9721 (while (string-match org-table-range-regexp form)
9722 (setq form
9723 (replace-match
9724 (save-match-data
9725 (org-table-make-reference
9726 (org-table-get-range (match-string 0 form) nil n0)
9727 keep-empty numbers lispp))
9728 t t form)))
9729 ;; Insert simple ranges
9730 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9731 (setq form
9732 (replace-match
9733 (save-match-data
9734 (org-table-make-reference
9735 (org-sublist
9736 fields (string-to-number (match-string 1 form))
9737 (string-to-number (match-string 2 form)))
9738 keep-empty numbers lispp))
9739 t t form)))
9740 (setq form0 form)
9741 ;; Insert the references to fields in same row
9742 (while (string-match "\\$\\([0-9]+\\)" form)
9743 (setq n (string-to-number (match-string 1 form))
9744 x (nth (1- (if (= n 0) n0 n)) fields))
9745 (unless x (error "Invalid field specifier \"%s\""
9746 (match-string 0 form)))
9747 (setq form (replace-match
9748 (save-match-data
9749 (org-table-make-reference x nil numbers lispp))
9750 t t form)))
9752 (if lispp
9753 (setq ev (condition-case nil
9754 (eval (eval (read form)))
9755 (error "#ERROR"))
9756 ev (if (numberp ev) (number-to-string ev) ev))
9757 (or (fboundp 'calc-eval)
9758 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9759 (setq ev (calc-eval (cons form modes)
9760 (if numbers 'num))))
9762 (when org-table-formula-debug
9763 (with-output-to-temp-buffer "*Substitution History*"
9764 (princ (format "Substitution history of formula
9765 Orig: %s
9766 $xyz-> %s
9767 @r$c-> %s
9768 $1-> %s\n" orig formula form0 form))
9769 (if (listp ev)
9770 (princ (format " %s^\nError: %s"
9771 (make-string (car ev) ?\-) (nth 1 ev)))
9772 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9773 ev (or fmt "NONE")
9774 (if fmt (format fmt (string-to-number ev)) ev)))))
9775 (setq bw (get-buffer-window "*Substitution History*"))
9776 (shrink-window-if-larger-than-buffer bw)
9777 (unless (and (interactive-p) (not ndown))
9778 (unless (let (inhibit-redisplay)
9779 (y-or-n-p "Debugging Formula. Continue to next? "))
9780 (org-table-align)
9781 (error "Abort"))
9782 (delete-window bw)
9783 (message "")))
9784 (if (listp ev) (setq fmt nil ev "#ERROR"))
9785 (org-table-justify-field-maybe
9786 (if fmt (format fmt (string-to-number ev)) ev))
9787 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9788 (call-interactively 'org-return)
9789 (setq ndown 0)))
9790 (and down (org-table-maybe-recalculate-line))
9791 (or suppress-align (and org-table-may-need-update
9792 (org-table-align))))))
9794 (defun org-table-put-field-property (prop value)
9795 (save-excursion
9796 (put-text-property (progn (skip-chars-backward "^|") (point))
9797 (progn (skip-chars-forward "^|") (point))
9798 prop value)))
9800 (defun org-table-get-range (desc &optional tbeg col highlight)
9801 "Get a calc vector from a column, accorting to descriptor DESC.
9802 Optional arguments TBEG and COL can give the beginning of the table and
9803 the current column, to avoid unnecessary parsing.
9804 HIGHLIGHT means, just highlight the range."
9805 (if (not (equal (string-to-char desc) ?@))
9806 (setq desc (concat "@" desc)))
9807 (save-excursion
9808 (or tbeg (setq tbeg (org-table-begin)))
9809 (or col (setq col (org-table-current-column)))
9810 (let ((thisline (org-current-line))
9811 beg end c1 c2 r1 r2 rangep tmp)
9812 (unless (string-match org-table-range-regexp desc)
9813 (error "Invalid table range specifier `%s'" desc))
9814 (setq rangep (match-end 3)
9815 r1 (and (match-end 1) (match-string 1 desc))
9816 r2 (and (match-end 4) (match-string 4 desc))
9817 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9818 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9820 (and c1 (setq c1 (+ (string-to-number c1)
9821 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9822 (and c2 (setq c2 (+ (string-to-number c2)
9823 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9824 (if (equal r1 "") (setq r1 nil))
9825 (if (equal r2 "") (setq r2 nil))
9826 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9827 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9828 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9829 (if (not r1) (setq r1 thisline))
9830 (if (not r2) (setq r2 thisline))
9831 (if (not c1) (setq c1 col))
9832 (if (not c2) (setq c2 col))
9833 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9834 ;; just one field
9835 (progn
9836 (goto-line r1)
9837 (while (not (looking-at org-table-dataline-regexp))
9838 (beginning-of-line 2))
9839 (prog1 (org-trim (org-table-get-field c1))
9840 (if highlight (org-table-highlight-rectangle (point) (point)))))
9841 ;; A range, return a vector
9842 ;; First sort the numbers to get a regular ractangle
9843 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9844 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9845 (goto-line r1)
9846 (while (not (looking-at org-table-dataline-regexp))
9847 (beginning-of-line 2))
9848 (org-table-goto-column c1)
9849 (setq beg (point))
9850 (goto-line r2)
9851 (while (not (looking-at org-table-dataline-regexp))
9852 (beginning-of-line 0))
9853 (org-table-goto-column c2)
9854 (setq end (point))
9855 (if highlight
9856 (org-table-highlight-rectangle
9857 beg (progn (skip-chars-forward "^|\n") (point))))
9858 ;; return string representation of calc vector
9859 (mapcar 'org-trim
9860 (apply 'append (org-table-copy-region beg end)))))))
9862 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9863 "Analyze descriptor DESC and retrieve the corresponding line number.
9864 The cursor is currently in line CLINE, the table begins in line BLINE,
9865 and TABLE is a vector with line types."
9866 (if (string-match "^[0-9]+$" desc)
9867 (aref org-table-dlines (string-to-number desc))
9868 (setq cline (or cline (org-current-line))
9869 bline (or bline org-table-current-begin-line)
9870 table (or table org-table-current-line-types))
9871 (if (or
9872 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9873 ;; 1 2 3 4 5 6
9874 (and (not (match-end 3)) (not (match-end 6)))
9875 (and (match-end 3) (match-end 6) (not (match-end 5))))
9876 (error "invalid row descriptor `%s'" desc))
9877 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9878 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9879 (odir (and (match-end 5) (match-string 5 desc)))
9880 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9881 (i (- cline bline))
9882 (rel (and (match-end 6)
9883 (or (and (match-end 1) (not (match-end 3)))
9884 (match-end 5)))))
9885 (if (and hn (not hdir))
9886 (progn
9887 (setq i 0 hdir "+")
9888 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9889 (if (and (not hn) on (not odir))
9890 (error "should never happen");;(aref org-table-dlines on)
9891 (if (and hn (> hn 0))
9892 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9893 (if on
9894 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9895 (+ bline i)))))
9897 (defun org-find-row-type (table i type backwards relative n)
9898 (let ((l (length table)))
9899 (while (> n 0)
9900 (while (and (setq i (+ i (if backwards -1 1)))
9901 (>= i 0) (< i l)
9902 (not (eq (aref table i) type))
9903 (if (and relative (eq (aref table i) 'hline))
9904 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9905 t)))
9906 (setq n (1- n)))
9907 (if (or (< i 0) (>= i l))
9908 (error "Row descriptior leads outside table")
9909 i)))
9911 (defun org-rewrite-old-row-references (s)
9912 (if (string-match "&[-+0-9I]" s)
9913 (error "Formula contains old &row reference, please rewrite using @-syntax")
9916 (defun org-table-make-reference (elements keep-empty numbers lispp)
9917 "Convert list ELEMENTS to something appropriate to insert into formula.
9918 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9919 NUMBERS indicates that everything should be converted to numbers.
9920 LISPP means to return something appropriate for a Lisp list."
9921 (if (stringp elements) ; just a single val
9922 (if lispp
9923 (if (eq lispp 'literal)
9924 elements
9925 (prin1-to-string (if numbers (string-to-number elements) elements)))
9926 (if (equal elements "") (setq elements "0"))
9927 (if numbers (number-to-string (string-to-number elements)) elements))
9928 (unless keep-empty
9929 (setq elements
9930 (delq nil
9931 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9932 elements))))
9933 (setq elements (or elements '("0")))
9934 (if lispp
9935 (mapconcat
9936 (lambda (x)
9937 (if (eq lispp 'literal)
9939 (prin1-to-string (if numbers (string-to-number x) x))))
9940 elements " ")
9941 (concat "[" (mapconcat
9942 (lambda (x)
9943 (if numbers (number-to-string (string-to-number x)) x))
9944 elements
9945 ",") "]"))))
9947 (defun org-table-recalculate (&optional all noalign)
9948 "Recalculate the current table line by applying all stored formulas.
9949 With prefix arg ALL, do this for all lines in the table."
9950 (interactive "P")
9951 (or (memq this-command org-recalc-commands)
9952 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9953 (unless (org-at-table-p) (error "Not at a table"))
9954 (if (equal all '(16))
9955 (org-table-iterate)
9956 (org-table-get-specials)
9957 (let* ((eqlist (sort (org-table-get-stored-formulas)
9958 (lambda (a b) (string< (car a) (car b)))))
9959 (inhibit-redisplay (not debug-on-error))
9960 (line-re org-table-dataline-regexp)
9961 (thisline (org-current-line))
9962 (thiscol (org-table-current-column))
9963 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9964 ;; Insert constants in all formulas
9965 (setq eqlist
9966 (mapcar (lambda (x)
9967 (setcdr x (org-table-formula-substitute-names (cdr x)))
9969 eqlist))
9970 ;; Split the equation list
9971 (while (setq eq (pop eqlist))
9972 (if (<= (string-to-char (car eq)) ?9)
9973 (push eq eqlnum)
9974 (push eq eqlname)))
9975 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9976 (if all
9977 (progn
9978 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9979 (goto-char (setq beg (org-table-begin)))
9980 (if (re-search-forward org-table-calculate-mark-regexp end t)
9981 ;; This is a table with marked lines, compute selected lines
9982 (setq line-re org-table-recalculate-regexp)
9983 ;; Move forward to the first non-header line
9984 (if (and (re-search-forward org-table-dataline-regexp end t)
9985 (re-search-forward org-table-hline-regexp end t)
9986 (re-search-forward org-table-dataline-regexp end t))
9987 (setq beg (match-beginning 0))
9988 nil))) ;; just leave beg where it is
9989 (setq beg (point-at-bol)
9990 end (move-marker (make-marker) (1+ (point-at-eol)))))
9991 (goto-char beg)
9992 (and all (message "Re-applying formulas to full table..."))
9994 ;; First find the named fields, and mark them untouchanble
9995 (remove-text-properties beg end '(org-untouchable t))
9996 (while (setq eq (pop eqlname))
9997 (setq name (car eq)
9998 a (assoc name org-table-named-field-locations))
9999 (and (not a)
10000 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10001 (setq a (list name
10002 (aref org-table-dlines
10003 (string-to-number (match-string 1 name)))
10004 (string-to-number (match-string 2 name)))))
10005 (when (and a (or all (equal (nth 1 a) thisline)))
10006 (message "Re-applying formula to field: %s" name)
10007 (goto-line (nth 1 a))
10008 (org-table-goto-column (nth 2 a))
10009 (push (append a (list (cdr eq))) eqlname1)
10010 (org-table-put-field-property :org-untouchable t)))
10012 ;; Now evauluate the column formulas, but skip fields covered by
10013 ;; field formulas
10014 (goto-char beg)
10015 (while (re-search-forward line-re end t)
10016 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10017 ;; Unprotected line, recalculate
10018 (and all (message "Re-applying formulas to full table...(line %d)"
10019 (setq cnt (1+ cnt))))
10020 (setq org-last-recalc-line (org-current-line))
10021 (setq eql eqlnum)
10022 (while (setq entry (pop eql))
10023 (goto-line org-last-recalc-line)
10024 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10025 (unless (get-text-property (point) :org-untouchable)
10026 (org-table-eval-formula nil (cdr entry)
10027 'noalign 'nocst 'nostore 'noanalysis)))))
10029 ;; Now evaluate the field formulas
10030 (while (setq eq (pop eqlname1))
10031 (message "Re-applying formula to field: %s" (car eq))
10032 (goto-line (nth 1 eq))
10033 (org-table-goto-column (nth 2 eq))
10034 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10035 'nostore 'noanalysis))
10037 (goto-line thisline)
10038 (org-table-goto-column thiscol)
10039 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10040 (or noalign (and org-table-may-need-update (org-table-align))
10041 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10043 ;; back to initial position
10044 (message "Re-applying formulas...done")
10045 (goto-line thisline)
10046 (org-table-goto-column thiscol)
10047 (or noalign (and org-table-may-need-update (org-table-align))
10048 (and all (message "Re-applying formulas...done"))))))
10050 (defun org-table-iterate (&optional arg)
10051 "Recalculate the table until it does not change anymore."
10052 (interactive "P")
10053 (let ((imax (if arg (prefix-numeric-value arg) 10))
10054 (i 0)
10055 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10056 thistbl)
10057 (catch 'exit
10058 (while (< i imax)
10059 (setq i (1+ i))
10060 (org-table-recalculate 'all)
10061 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10062 (if (not (string= lasttbl thistbl))
10063 (setq lasttbl thistbl)
10064 (if (> i 1)
10065 (message "Convergence after %d iterations" i)
10066 (message "Table was already stable"))
10067 (throw 'exit t)))
10068 (error "No convergence after %d iterations" i))))
10070 (defun org-table-formula-substitute-names (f)
10071 "Replace $const with values in string F."
10072 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10073 ;; First, check for column names
10074 (while (setq start (string-match org-table-column-name-regexp f start))
10075 (setq start (1+ start))
10076 (setq a (assoc (match-string 1 f) org-table-column-names))
10077 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10078 ;; Parameters and constants
10079 (setq start 0)
10080 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10081 (setq start (1+ start))
10082 (if (setq a (save-match-data
10083 (org-table-get-constant (match-string 1 f))))
10084 (setq f (replace-match
10085 (concat (if pp "(") a (if pp ")")) t t f))))
10086 (if org-table-formula-debug
10087 (put-text-property 0 (length f) :orig-formula f1 f))
10090 (defun org-table-get-constant (const)
10091 "Find the value for a parameter or constant in a formula.
10092 Parameters get priority."
10093 (or (cdr (assoc const org-table-local-parameters))
10094 (cdr (assoc const org-table-formula-constants-local))
10095 (cdr (assoc const org-table-formula-constants))
10096 (and (fboundp 'constants-get) (constants-get const))
10097 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10098 (org-entry-get nil (substring const 5) 'inherit))
10099 "#UNDEFINED_NAME"))
10101 (defvar org-table-fedit-map
10102 (let ((map (make-sparse-keymap)))
10103 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10104 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10105 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10106 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10107 (org-defkey map "\C-c?" 'org-table-show-reference)
10108 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10109 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10110 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10111 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10112 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10113 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10114 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10115 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10116 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10117 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10118 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10119 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10120 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10121 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10122 map))
10124 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10125 '("Edit-Formulas"
10126 ["Finish and Install" org-table-fedit-finish t]
10127 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10128 ["Abort" org-table-fedit-abort t]
10129 "--"
10130 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10131 ["Complete Lisp Symbol" lisp-complete-symbol t]
10132 "--"
10133 "Shift Reference at Point"
10134 ["Up" org-table-fedit-ref-up t]
10135 ["Down" org-table-fedit-ref-down t]
10136 ["Left" org-table-fedit-ref-left t]
10137 ["Right" org-table-fedit-ref-right t]
10139 "Change Test Row for Column Formulas"
10140 ["Up" org-table-fedit-line-up t]
10141 ["Down" org-table-fedit-line-down t]
10142 "--"
10143 ["Scroll Table Window" org-table-fedit-scroll t]
10144 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10145 ["Show Table Grid" org-table-fedit-toggle-coordinates
10146 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10147 org-table-overlay-coordinates)]
10148 "--"
10149 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10150 :style toggle :selected org-table-buffer-is-an]))
10152 (defvar org-pos)
10154 (defun org-table-edit-formulas ()
10155 "Edit the formulas of the current table in a separate buffer."
10156 (interactive)
10157 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10158 (beginning-of-line 0))
10159 (unless (org-at-table-p) (error "Not at a table"))
10160 (org-table-get-specials)
10161 (let ((key (org-table-current-field-formula 'key 'noerror))
10162 (eql (sort (org-table-get-stored-formulas 'noerror)
10163 'org-table-formula-less-p))
10164 (pos (move-marker (make-marker) (point)))
10165 (startline 1)
10166 (wc (current-window-configuration))
10167 (titles '((column . "# Column Formulas\n")
10168 (field . "# Field Formulas\n")
10169 (named . "# Named Field Formulas\n")))
10170 entry s type title)
10171 (org-switch-to-buffer-other-window "*Edit Formulas*")
10172 (erase-buffer)
10173 ;; Keep global-font-lock-mode from turning on font-lock-mode
10174 (let ((font-lock-global-modes '(not fundamental-mode)))
10175 (fundamental-mode))
10176 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10177 (org-set-local 'org-pos pos)
10178 (org-set-local 'org-window-configuration wc)
10179 (use-local-map org-table-fedit-map)
10180 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10181 (easy-menu-add org-table-fedit-menu)
10182 (setq startline (org-current-line))
10183 (while (setq entry (pop eql))
10184 (setq type (cond
10185 ((equal (string-to-char (car entry)) ?@) 'field)
10186 ((string-match "^[0-9]" (car entry)) 'column)
10187 (t 'named)))
10188 (when (setq title (assq type titles))
10189 (or (bobp) (insert "\n"))
10190 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10191 (setq titles (delq title titles)))
10192 (if (equal key (car entry)) (setq startline (org-current-line)))
10193 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10194 (car entry) " = " (cdr entry) "\n"))
10195 (remove-text-properties 0 (length s) '(face nil) s)
10196 (insert s))
10197 (if (eq org-table-use-standard-references t)
10198 (org-table-fedit-toggle-ref-type))
10199 (goto-line startline)
10200 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10202 (defun org-table-fedit-post-command ()
10203 (when (not (memq this-command '(lisp-complete-symbol)))
10204 (let ((win (selected-window)))
10205 (save-excursion
10206 (condition-case nil
10207 (org-table-show-reference)
10208 (error nil))
10209 (select-window win)))))
10211 (defun org-table-formula-to-user (s)
10212 "Convert a formula from internal to user representation."
10213 (if (eq org-table-use-standard-references t)
10214 (org-table-convert-refs-to-an s)
10217 (defun org-table-formula-from-user (s)
10218 "Convert a formula from user to internal representation."
10219 (if org-table-use-standard-references
10220 (org-table-convert-refs-to-rc s)
10223 (defun org-table-convert-refs-to-rc (s)
10224 "Convert spreadsheet references from AB7 to @7$28.
10225 Works for single references, but also for entire formulas and even the
10226 full TBLFM line."
10227 (let ((start 0))
10228 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10229 (cond
10230 ((match-end 3)
10231 ;; format match, just advance
10232 (setq start (match-end 0)))
10233 ((and (> (match-beginning 0) 0)
10234 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10235 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10236 ;; 3.e5 or something like this.
10237 (setq start (match-end 0)))
10239 (setq start (match-beginning 0)
10240 s (replace-match
10241 (if (equal (match-string 2 s) "&")
10242 (format "$%d" (org-letters-to-number (match-string 1 s)))
10243 (format "@%d$%d"
10244 (string-to-number (match-string 2 s))
10245 (org-letters-to-number (match-string 1 s))))
10246 t t s)))))
10249 (defun org-table-convert-refs-to-an (s)
10250 "Convert spreadsheet references from to @7$28 to AB7.
10251 Works for single references, but also for entire formulas and even the
10252 full TBLFM line."
10253 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10254 (setq s (replace-match
10255 (format "%s%d"
10256 (org-number-to-letters
10257 (string-to-number (match-string 2 s)))
10258 (string-to-number (match-string 1 s)))
10259 t t s)))
10260 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10261 (setq s (replace-match (concat "\\1"
10262 (org-number-to-letters
10263 (string-to-number (match-string 2 s))) "&")
10264 t nil s)))
10267 (defun org-letters-to-number (s)
10268 "Convert a base 26 number represented by letters into an integer.
10269 For example: AB -> 28."
10270 (let ((n 0))
10271 (setq s (upcase s))
10272 (while (> (length s) 0)
10273 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10274 s (substring s 1)))
10277 (defun org-number-to-letters (n)
10278 "Convert an integer into a base 26 number represented by letters.
10279 For example: 28 -> AB."
10280 (let ((s ""))
10281 (while (> n 0)
10282 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10283 n (/ (1- n) 26)))
10286 (defun org-table-fedit-convert-buffer (function)
10287 "Convert all references in this buffer, using FUNTION."
10288 (let ((line (org-current-line)))
10289 (goto-char (point-min))
10290 (while (not (eobp))
10291 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10292 (delete-region (point) (point-at-eol))
10293 (or (eobp) (forward-char 1)))
10294 (goto-line line)))
10296 (defun org-table-fedit-toggle-ref-type ()
10297 "Convert all references in the buffer from B3 to @3$2 and back."
10298 (interactive)
10299 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10300 (org-table-fedit-convert-buffer
10301 (if org-table-buffer-is-an
10302 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10303 (message "Reference type switched to %s"
10304 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10306 (defun org-table-fedit-ref-up ()
10307 "Shift the reference at point one row/hline up."
10308 (interactive)
10309 (org-table-fedit-shift-reference 'up))
10310 (defun org-table-fedit-ref-down ()
10311 "Shift the reference at point one row/hline down."
10312 (interactive)
10313 (org-table-fedit-shift-reference 'down))
10314 (defun org-table-fedit-ref-left ()
10315 "Shift the reference at point one field to the left."
10316 (interactive)
10317 (org-table-fedit-shift-reference 'left))
10318 (defun org-table-fedit-ref-right ()
10319 "Shift the reference at point one field to the right."
10320 (interactive)
10321 (org-table-fedit-shift-reference 'right))
10323 (defun org-table-fedit-shift-reference (dir)
10324 (cond
10325 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10326 (if (memq dir '(left right))
10327 (org-rematch-and-replace 1 (eq dir 'left))
10328 (error "Cannot shift reference in this direction")))
10329 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10330 ;; A B3-like reference
10331 (if (memq dir '(up down))
10332 (org-rematch-and-replace 2 (eq dir 'up))
10333 (org-rematch-and-replace 1 (eq dir 'left))))
10334 ((org-at-regexp-p
10335 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10336 ;; An internal reference
10337 (if (memq dir '(up down))
10338 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10339 (org-rematch-and-replace 5 (eq dir 'left))))))
10341 (defun org-rematch-and-replace (n &optional decr hline)
10342 "Re-match the group N, and replace it with the shifted refrence."
10343 (or (match-end n) (error "Cannot shift reference in this direction"))
10344 (goto-char (match-beginning n))
10345 (and (looking-at (regexp-quote (match-string n)))
10346 (replace-match (org-shift-refpart (match-string 0) decr hline)
10347 t t)))
10349 (defun org-shift-refpart (ref &optional decr hline)
10350 "Shift a refrence part REF.
10351 If DECR is set, decrease the references row/column, else increase.
10352 If HLINE is set, this may be a hline reference, it certainly is not
10353 a translation reference."
10354 (save-match-data
10355 (let* ((sign (string-match "^[-+]" ref)) n)
10357 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10358 (cond
10359 ((and hline (string-match "^I+" ref))
10360 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10361 (setq n (+ n (if decr -1 1)))
10362 (if (= n 0) (setq n (+ n (if decr -1 1))))
10363 (if sign
10364 (setq sign (if (< n 0) "-" "+") n (abs n))
10365 (setq n (max 1 n)))
10366 (concat sign (make-string n ?I)))
10368 ((string-match "^[0-9]+" ref)
10369 (setq n (string-to-number (concat sign ref)))
10370 (setq n (+ n (if decr -1 1)))
10371 (if sign
10372 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10373 (number-to-string (max 1 n))))
10375 ((string-match "^[a-zA-Z]+" ref)
10376 (org-number-to-letters
10377 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10379 (t (error "Cannot shift reference"))))))
10381 (defun org-table-fedit-toggle-coordinates ()
10382 "Toggle the display of coordinates in the refrenced table."
10383 (interactive)
10384 (let ((pos (marker-position org-pos)))
10385 (with-current-buffer (marker-buffer org-pos)
10386 (save-excursion
10387 (goto-char pos)
10388 (org-table-toggle-coordinate-overlays)))))
10390 (defun org-table-fedit-finish (&optional arg)
10391 "Parse the buffer for formula definitions and install them.
10392 With prefix ARG, apply the new formulas to the table."
10393 (interactive "P")
10394 (org-table-remove-rectangle-highlight)
10395 (if org-table-use-standard-references
10396 (progn
10397 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10398 (setq org-table-buffer-is-an nil)))
10399 (let ((pos org-pos) eql var form)
10400 (goto-char (point-min))
10401 (while (re-search-forward
10402 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10403 nil t)
10404 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10405 form (match-string 3))
10406 (setq form (org-trim form))
10407 (when (not (equal form ""))
10408 (while (string-match "[ \t]*\n[ \t]*" form)
10409 (setq form (replace-match " " t t form)))
10410 (when (assoc var eql)
10411 (error "Double formulas for %s" var))
10412 (push (cons var form) eql)))
10413 (setq org-pos nil)
10414 (set-window-configuration org-window-configuration)
10415 (select-window (get-buffer-window (marker-buffer pos)))
10416 (goto-char pos)
10417 (unless (org-at-table-p)
10418 (error "Lost table position - cannot install formulae"))
10419 (org-table-store-formulas eql)
10420 (move-marker pos nil)
10421 (kill-buffer "*Edit Formulas*")
10422 (if arg
10423 (org-table-recalculate 'all)
10424 (message "New formulas installed - press C-u C-c C-c to apply."))))
10426 (defun org-table-fedit-abort ()
10427 "Abort editing formulas, without installing the changes."
10428 (interactive)
10429 (org-table-remove-rectangle-highlight)
10430 (let ((pos org-pos))
10431 (set-window-configuration org-window-configuration)
10432 (select-window (get-buffer-window (marker-buffer pos)))
10433 (goto-char pos)
10434 (move-marker pos nil)
10435 (message "Formula editing aborted without installing changes")))
10437 (defun org-table-fedit-lisp-indent ()
10438 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10439 (interactive)
10440 (let ((pos (point)) beg end ind)
10441 (beginning-of-line 1)
10442 (cond
10443 ((looking-at "[ \t]")
10444 (goto-char pos)
10445 (call-interactively 'lisp-indent-line))
10446 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10447 ((not (fboundp 'pp-buffer))
10448 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10449 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10450 (goto-char (- (match-end 0) 2))
10451 (setq beg (point))
10452 (setq ind (make-string (current-column) ?\ ))
10453 (condition-case nil (forward-sexp 1)
10454 (error
10455 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10456 (setq end (point))
10457 (save-restriction
10458 (narrow-to-region beg end)
10459 (if (eq last-command this-command)
10460 (progn
10461 (goto-char (point-min))
10462 (setq this-command nil)
10463 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10464 (replace-match " ")))
10465 (pp-buffer)
10466 (untabify (point-min) (point-max))
10467 (goto-char (1+ (point-min)))
10468 (while (re-search-forward "^." nil t)
10469 (beginning-of-line 1)
10470 (insert ind))
10471 (goto-char (point-max))
10472 (backward-delete-char 1)))
10473 (goto-char beg))
10474 (t nil))))
10476 (defvar org-show-positions nil)
10478 (defun org-table-show-reference (&optional local)
10479 "Show the location/value of the $ expression at point."
10480 (interactive)
10481 (org-table-remove-rectangle-highlight)
10482 (catch 'exit
10483 (let ((pos (if local (point) org-pos))
10484 (face2 'highlight)
10485 (org-inhibit-highlight-removal t)
10486 (win (selected-window))
10487 (org-show-positions nil)
10488 var name e what match dest)
10489 (if local (org-table-get-specials))
10490 (setq what (cond
10491 ((or (org-at-regexp-p org-table-range-regexp2)
10492 (org-at-regexp-p org-table-translate-regexp)
10493 (org-at-regexp-p org-table-range-regexp))
10494 (setq match
10495 (save-match-data
10496 (org-table-convert-refs-to-rc (match-string 0))))
10497 'range)
10498 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10499 ((org-at-regexp-p "\\$[0-9]+") 'column)
10500 ((not local) nil)
10501 (t (error "No reference at point")))
10502 match (and what (or match (match-string 0))))
10503 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10504 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10505 'secondary-selection))
10506 (org-add-hook 'before-change-functions
10507 'org-table-remove-rectangle-highlight)
10508 (if (eq what 'name) (setq var (substring match 1)))
10509 (when (eq what 'range)
10510 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10511 (setq match (org-table-formula-substitute-names match)))
10512 (unless local
10513 (save-excursion
10514 (end-of-line 1)
10515 (re-search-backward "^\\S-" nil t)
10516 (beginning-of-line 1)
10517 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10518 (setq dest
10519 (save-match-data
10520 (org-table-convert-refs-to-rc (match-string 1))))
10521 (org-table-add-rectangle-overlay
10522 (match-beginning 1) (match-end 1) face2))))
10523 (if (and (markerp pos) (marker-buffer pos))
10524 (if (get-buffer-window (marker-buffer pos))
10525 (select-window (get-buffer-window (marker-buffer pos)))
10526 (org-switch-to-buffer-other-window (get-buffer-window
10527 (marker-buffer pos)))))
10528 (goto-char pos)
10529 (org-table-force-dataline)
10530 (when dest
10531 (setq name (substring dest 1))
10532 (cond
10533 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10534 (setq e (assoc name org-table-named-field-locations))
10535 (goto-line (nth 1 e))
10536 (org-table-goto-column (nth 2 e)))
10537 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10538 (let ((l (string-to-number (match-string 1 dest)))
10539 (c (string-to-number (match-string 2 dest))))
10540 (goto-line (aref org-table-dlines l))
10541 (org-table-goto-column c)))
10542 (t (org-table-goto-column (string-to-number name))))
10543 (move-marker pos (point))
10544 (org-table-highlight-rectangle nil nil face2))
10545 (cond
10546 ((equal dest match))
10547 ((not match))
10548 ((eq what 'range)
10549 (condition-case nil
10550 (save-excursion
10551 (org-table-get-range match nil nil 'highlight))
10552 (error nil)))
10553 ((setq e (assoc var org-table-named-field-locations))
10554 (goto-line (nth 1 e))
10555 (org-table-goto-column (nth 2 e))
10556 (org-table-highlight-rectangle (point) (point))
10557 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10558 ((setq e (assoc var org-table-column-names))
10559 (org-table-goto-column (string-to-number (cdr e)))
10560 (org-table-highlight-rectangle (point) (point))
10561 (goto-char (org-table-begin))
10562 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10563 (org-table-end) t)
10564 (progn
10565 (goto-char (match-beginning 1))
10566 (org-table-highlight-rectangle)
10567 (message "Named column (column %s)" (cdr e)))
10568 (error "Column name not found")))
10569 ((eq what 'column)
10570 ;; column number
10571 (org-table-goto-column (string-to-number (substring match 1)))
10572 (org-table-highlight-rectangle (point) (point))
10573 (message "Column %s" (substring match 1)))
10574 ((setq e (assoc var org-table-local-parameters))
10575 (goto-char (org-table-begin))
10576 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10577 (progn
10578 (goto-char (match-beginning 1))
10579 (org-table-highlight-rectangle)
10580 (message "Local parameter."))
10581 (error "Parameter not found")))
10583 (cond
10584 ((not var) (error "No reference at point"))
10585 ((setq e (assoc var org-table-formula-constants-local))
10586 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10587 var (cdr e)))
10588 ((setq e (assoc var org-table-formula-constants))
10589 (message "Constant: $%s=%s in `org-table-formula-constants'."
10590 var (cdr e)))
10591 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10592 (message "Constant: $%s=%s, from `constants.el'%s."
10593 var e (format " (%s units)" constants-unit-system)))
10594 (t (error "Undefined name $%s" var)))))
10595 (goto-char pos)
10596 (when (and org-show-positions
10597 (not (memq this-command '(org-table-fedit-scroll
10598 org-table-fedit-scroll-down))))
10599 (push pos org-show-positions)
10600 (push org-table-current-begin-pos org-show-positions)
10601 (let ((min (apply 'min org-show-positions))
10602 (max (apply 'max org-show-positions)))
10603 (goto-char min) (recenter 0)
10604 (goto-char max)
10605 (or (pos-visible-in-window-p max) (recenter -1))))
10606 (select-window win))))
10608 (defun org-table-force-dataline ()
10609 "Make sure the cursor is in a dataline in a table."
10610 (unless (save-excursion
10611 (beginning-of-line 1)
10612 (looking-at org-table-dataline-regexp))
10613 (let* ((re org-table-dataline-regexp)
10614 (p1 (save-excursion (re-search-forward re nil 'move)))
10615 (p2 (save-excursion (re-search-backward re nil 'move))))
10616 (cond ((and p1 p2)
10617 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10618 p1 p2)))
10619 ((or p1 p2) (goto-char (or p1 p2)))
10620 (t (error "No table dataline around here"))))))
10622 (defun org-table-fedit-line-up ()
10623 "Move cursor one line up in the window showing the table."
10624 (interactive)
10625 (org-table-fedit-move 'previous-line))
10627 (defun org-table-fedit-line-down ()
10628 "Move cursor one line down in the window showing the table."
10629 (interactive)
10630 (org-table-fedit-move 'next-line))
10632 (defun org-table-fedit-move (command)
10633 "Move the cursor in the window shoinw the table.
10634 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10635 (let ((org-table-allow-automatic-line-recalculation nil)
10636 (pos org-pos) (win (selected-window)) p)
10637 (select-window (get-buffer-window (marker-buffer org-pos)))
10638 (setq p (point))
10639 (call-interactively command)
10640 (while (and (org-at-table-p)
10641 (org-at-table-hline-p))
10642 (call-interactively command))
10643 (or (org-at-table-p) (goto-char p))
10644 (move-marker pos (point))
10645 (select-window win)))
10647 (defun org-table-fedit-scroll (N)
10648 (interactive "p")
10649 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10650 (scroll-other-window N)))
10652 (defun org-table-fedit-scroll-down (N)
10653 (interactive "p")
10654 (org-table-fedit-scroll (- N)))
10656 (defvar org-table-rectangle-overlays nil)
10658 (defun org-table-add-rectangle-overlay (beg end &optional face)
10659 "Add a new overlay."
10660 (let ((ov (org-make-overlay beg end)))
10661 (org-overlay-put ov 'face (or face 'secondary-selection))
10662 (push ov org-table-rectangle-overlays)))
10664 (defun org-table-highlight-rectangle (&optional beg end face)
10665 "Highlight rectangular region in a table."
10666 (setq beg (or beg (point)) end (or end (point)))
10667 (let ((b (min beg end))
10668 (e (max beg end))
10669 l1 c1 l2 c2 tmp)
10670 (and (boundp 'org-show-positions)
10671 (setq org-show-positions (cons b (cons e org-show-positions))))
10672 (goto-char (min beg end))
10673 (setq l1 (org-current-line)
10674 c1 (org-table-current-column))
10675 (goto-char (max beg end))
10676 (setq l2 (org-current-line)
10677 c2 (org-table-current-column))
10678 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10679 (goto-line l1)
10680 (beginning-of-line 1)
10681 (loop for line from l1 to l2 do
10682 (when (looking-at org-table-dataline-regexp)
10683 (org-table-goto-column c1)
10684 (skip-chars-backward "^|\n") (setq beg (point))
10685 (org-table-goto-column c2)
10686 (skip-chars-forward "^|\n") (setq end (point))
10687 (org-table-add-rectangle-overlay beg end face))
10688 (beginning-of-line 2))
10689 (goto-char b))
10690 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10692 (defun org-table-remove-rectangle-highlight (&rest ignore)
10693 "Remove the rectangle overlays."
10694 (unless org-inhibit-highlight-removal
10695 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10696 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10697 (setq org-table-rectangle-overlays nil)))
10699 (defvar org-table-coordinate-overlays nil
10700 "Collects the cooordinate grid overlays, so that they can be removed.")
10701 (make-variable-buffer-local 'org-table-coordinate-overlays)
10703 (defun org-table-overlay-coordinates ()
10704 "Add overlays to the table at point, to show row/column coordinates."
10705 (interactive)
10706 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10707 (setq org-table-coordinate-overlays nil)
10708 (save-excursion
10709 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10710 (goto-char (org-table-begin))
10711 (while (org-at-table-p)
10712 (setq eol (point-at-eol))
10713 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10714 (push ov org-table-coordinate-overlays)
10715 (setq hline (looking-at org-table-hline-regexp))
10716 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10717 (format "%4d" (setq id (1+ id)))))
10718 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10719 (when hline
10720 (setq ic 0)
10721 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10722 (setq beg (1+ (match-beginning 0))
10723 ic (1+ ic)
10724 s1 (concat "$" (int-to-string ic))
10725 s2 (org-number-to-letters ic)
10726 str (if (eq org-table-use-standard-references t) s2 s1))
10727 (setq ov (org-make-overlay beg (+ beg (length str))))
10728 (push ov org-table-coordinate-overlays)
10729 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10730 (beginning-of-line 2)))))
10732 (defun org-table-toggle-coordinate-overlays ()
10733 "Toggle the display of Row/Column numbers in tables."
10734 (interactive)
10735 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10736 (message "Row/Column number display turned %s"
10737 (if org-table-overlay-coordinates "on" "off"))
10738 (if (and (org-at-table-p) org-table-overlay-coordinates)
10739 (org-table-align))
10740 (unless org-table-overlay-coordinates
10741 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10742 (setq org-table-coordinate-overlays nil)))
10744 (defun org-table-toggle-formula-debugger ()
10745 "Toggle the formula debugger in tables."
10746 (interactive)
10747 (setq org-table-formula-debug (not org-table-formula-debug))
10748 (message "Formula debugging has been turned %s"
10749 (if org-table-formula-debug "on" "off")))
10751 ;;; The orgtbl minor mode
10753 ;; Define a minor mode which can be used in other modes in order to
10754 ;; integrate the org-mode table editor.
10756 ;; This is really a hack, because the org-mode table editor uses several
10757 ;; keys which normally belong to the major mode, for example the TAB and
10758 ;; RET keys. Here is how it works: The minor mode defines all the keys
10759 ;; necessary to operate the table editor, but wraps the commands into a
10760 ;; function which tests if the cursor is currently inside a table. If that
10761 ;; is the case, the table editor command is executed. However, when any of
10762 ;; those keys is used outside a table, the function uses `key-binding' to
10763 ;; look up if the key has an associated command in another currently active
10764 ;; keymap (minor modes, major mode, global), and executes that command.
10765 ;; There might be problems if any of the keys used by the table editor is
10766 ;; otherwise used as a prefix key.
10768 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10769 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10770 ;; addresses this by checking explicitly for both bindings.
10772 ;; The optimized version (see variable `orgtbl-optimized') takes over
10773 ;; all keys which are bound to `self-insert-command' in the *global map*.
10774 ;; Some modes bind other commands to simple characters, for example
10775 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10776 ;; active, this binding is ignored inside tables and replaced with a
10777 ;; modified self-insert.
10779 (defvar orgtbl-mode nil
10780 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10781 table editor in arbitrary modes.")
10782 (make-variable-buffer-local 'orgtbl-mode)
10784 (defvar orgtbl-mode-map (make-keymap)
10785 "Keymap for `orgtbl-mode'.")
10787 ;;;###autoload
10788 (defun turn-on-orgtbl ()
10789 "Unconditionally turn on `orgtbl-mode'."
10790 (orgtbl-mode 1))
10792 (defvar org-old-auto-fill-inhibit-regexp nil
10793 "Local variable used by `orgtbl-mode'")
10795 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10796 "Matches a line belonging to an orgtbl.")
10798 (defconst orgtbl-extra-font-lock-keywords
10799 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10800 0 (quote 'org-table) 'prepend))
10801 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10803 ;;;###autoload
10804 (defun orgtbl-mode (&optional arg)
10805 "The `org-mode' table editor as a minor mode for use in other modes."
10806 (interactive)
10807 (if (org-mode-p)
10808 ;; Exit without error, in case some hook functions calls this
10809 ;; by accident in org-mode.
10810 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10811 (setq orgtbl-mode
10812 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10813 (if orgtbl-mode
10814 (progn
10815 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10816 ;; Make sure we are first in minor-mode-map-alist
10817 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10818 (and c (setq minor-mode-map-alist
10819 (cons c (delq c minor-mode-map-alist)))))
10820 (org-set-local (quote org-table-may-need-update) t)
10821 (org-add-hook 'before-change-functions 'org-before-change-function
10822 nil 'local)
10823 (org-set-local 'org-old-auto-fill-inhibit-regexp
10824 auto-fill-inhibit-regexp)
10825 (org-set-local 'auto-fill-inhibit-regexp
10826 (if auto-fill-inhibit-regexp
10827 (concat orgtbl-line-start-regexp "\\|"
10828 auto-fill-inhibit-regexp)
10829 orgtbl-line-start-regexp))
10830 (org-add-to-invisibility-spec '(org-cwidth))
10831 (when (fboundp 'font-lock-add-keywords)
10832 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10833 (org-restart-font-lock))
10834 (easy-menu-add orgtbl-mode-menu)
10835 (run-hooks 'orgtbl-mode-hook))
10836 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10837 (org-cleanup-narrow-column-properties)
10838 (org-remove-from-invisibility-spec '(org-cwidth))
10839 (remove-hook 'before-change-functions 'org-before-change-function t)
10840 (when (fboundp 'font-lock-remove-keywords)
10841 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10842 (org-restart-font-lock))
10843 (easy-menu-remove orgtbl-mode-menu)
10844 (force-mode-line-update 'all))))
10846 (defun org-cleanup-narrow-column-properties ()
10847 "Remove all properties related to narrow-column invisibility."
10848 (let ((s 1))
10849 (while (setq s (text-property-any s (point-max)
10850 'display org-narrow-column-arrow))
10851 (remove-text-properties s (1+ s) '(display t)))
10852 (setq s 1)
10853 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10854 (remove-text-properties s (1+ s) '(org-cwidth t)))
10855 (setq s 1)
10856 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10857 (remove-text-properties s (1+ s) '(invisible t)))))
10859 ;; Install it as a minor mode.
10860 (put 'orgtbl-mode :included t)
10861 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10862 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10864 (defun orgtbl-make-binding (fun n &rest keys)
10865 "Create a function for binding in the table minor mode.
10866 FUN is the command to call inside a table. N is used to create a unique
10867 command name. KEYS are keys that should be checked in for a command
10868 to execute outside of tables."
10869 (eval
10870 (list 'defun
10871 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10872 '(arg)
10873 (concat "In tables, run `" (symbol-name fun) "'.\n"
10874 "Outside of tables, run the binding of `"
10875 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10876 "'.")
10877 '(interactive "p")
10878 (list 'if
10879 '(org-at-table-p)
10880 (list 'call-interactively (list 'quote fun))
10881 (list 'let '(orgtbl-mode)
10882 (list 'call-interactively
10883 (append '(or)
10884 (mapcar (lambda (k)
10885 (list 'key-binding k))
10886 keys)
10887 '('orgtbl-error))))))))
10889 (defun orgtbl-error ()
10890 "Error when there is no default binding for a table key."
10891 (interactive)
10892 (error "This key is has no function outside tables"))
10894 (defun orgtbl-setup ()
10895 "Setup orgtbl keymaps."
10896 (let ((nfunc 0)
10897 (bindings
10898 (list
10899 '([(meta shift left)] org-table-delete-column)
10900 '([(meta left)] org-table-move-column-left)
10901 '([(meta right)] org-table-move-column-right)
10902 '([(meta shift right)] org-table-insert-column)
10903 '([(meta shift up)] org-table-kill-row)
10904 '([(meta shift down)] org-table-insert-row)
10905 '([(meta up)] org-table-move-row-up)
10906 '([(meta down)] org-table-move-row-down)
10907 '("\C-c\C-w" org-table-cut-region)
10908 '("\C-c\M-w" org-table-copy-region)
10909 '("\C-c\C-y" org-table-paste-rectangle)
10910 '("\C-c-" org-table-insert-hline)
10911 '("\C-c}" org-table-toggle-coordinate-overlays)
10912 '("\C-c{" org-table-toggle-formula-debugger)
10913 '("\C-m" org-table-next-row)
10914 '([(shift return)] org-table-copy-down)
10915 '("\C-c\C-q" org-table-wrap-region)
10916 '("\C-c?" org-table-field-info)
10917 '("\C-c " org-table-blank-field)
10918 '("\C-c+" org-table-sum)
10919 '("\C-c=" org-table-eval-formula)
10920 '("\C-c'" org-table-edit-formulas)
10921 '("\C-c`" org-table-edit-field)
10922 '("\C-c*" org-table-recalculate)
10923 '("\C-c|" org-table-create-or-convert-from-region)
10924 '("\C-c^" org-table-sort-lines)
10925 '([(control ?#)] org-table-rotate-recalc-marks)))
10926 elt key fun cmd)
10927 (while (setq elt (pop bindings))
10928 (setq nfunc (1+ nfunc))
10929 (setq key (org-key (car elt))
10930 fun (nth 1 elt)
10931 cmd (orgtbl-make-binding fun nfunc key))
10932 (org-defkey orgtbl-mode-map key cmd))
10934 ;; Special treatment needed for TAB and RET
10935 (org-defkey orgtbl-mode-map [(return)]
10936 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10937 (org-defkey orgtbl-mode-map "\C-m"
10938 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10940 (org-defkey orgtbl-mode-map [(tab)]
10941 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10942 (org-defkey orgtbl-mode-map "\C-i"
10943 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10945 (org-defkey orgtbl-mode-map [(shift tab)]
10946 (orgtbl-make-binding 'org-table-previous-field 104
10947 [(shift tab)] [(tab)] "\C-i"))
10949 (org-defkey orgtbl-mode-map "\M-\C-m"
10950 (orgtbl-make-binding 'org-table-wrap-region 105
10951 "\M-\C-m" [(meta return)]))
10952 (org-defkey orgtbl-mode-map [(meta return)]
10953 (orgtbl-make-binding 'org-table-wrap-region 106
10954 [(meta return)] "\M-\C-m"))
10956 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10957 (when orgtbl-optimized
10958 ;; If the user wants maximum table support, we need to hijack
10959 ;; some standard editing functions
10960 (org-remap orgtbl-mode-map
10961 'self-insert-command 'orgtbl-self-insert-command
10962 'delete-char 'org-delete-char
10963 'delete-backward-char 'org-delete-backward-char)
10964 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10965 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10966 '("OrgTbl"
10967 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10968 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10969 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10970 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10971 "--"
10972 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10973 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10974 ["Copy Field from Above"
10975 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10976 "--"
10977 ("Column"
10978 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10979 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10980 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10981 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10982 ("Row"
10983 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10984 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10985 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10986 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10987 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10988 "--"
10989 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10990 ("Rectangle"
10991 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10992 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10993 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10994 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10995 "--"
10996 ("Radio tables"
10997 ["Insert table template" orgtbl-insert-radio-table
10998 (assq major-mode orgtbl-radio-table-templates)]
10999 ["Comment/uncomment table" orgtbl-toggle-comment t])
11000 "--"
11001 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11002 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11003 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11004 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11005 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11006 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11007 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11008 ["Sum Column/Rectangle" org-table-sum
11009 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11010 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11011 ["Debug Formulas"
11012 org-table-toggle-formula-debugger :active (org-at-table-p)
11013 :keys "C-c {"
11014 :style toggle :selected org-table-formula-debug]
11015 ["Show Col/Row Numbers"
11016 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11017 :keys "C-c }"
11018 :style toggle :selected org-table-overlay-coordinates]
11022 (defun orgtbl-ctrl-c-ctrl-c (arg)
11023 "If the cursor is inside a table, realign the table.
11024 It it is a table to be sent away to a receiver, do it.
11025 With prefix arg, also recompute table."
11026 (interactive "P")
11027 (let ((pos (point)) action)
11028 (save-excursion
11029 (beginning-of-line 1)
11030 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11031 ((looking-at "[ \t]*|") pos)
11032 ((looking-at "#\\+TBLFM:") 'recalc))))
11033 (cond
11034 ((integerp action)
11035 (goto-char action)
11036 (org-table-maybe-eval-formula)
11037 (if arg
11038 (call-interactively 'org-table-recalculate)
11039 (org-table-maybe-recalculate-line))
11040 (call-interactively 'org-table-align)
11041 (orgtbl-send-table 'maybe))
11042 ((eq action 'recalc)
11043 (save-excursion
11044 (beginning-of-line 1)
11045 (skip-chars-backward " \r\n\t")
11046 (if (org-at-table-p)
11047 (org-call-with-arg 'org-table-recalculate t))))
11048 (t (let (orgtbl-mode)
11049 (call-interactively (key-binding "\C-c\C-c")))))))
11051 (defun orgtbl-tab (arg)
11052 "Justification and field motion for `orgtbl-mode'."
11053 (interactive "P")
11054 (if arg (org-table-edit-field t)
11055 (org-table-justify-field-maybe)
11056 (org-table-next-field)))
11058 (defun orgtbl-ret ()
11059 "Justification and field motion for `orgtbl-mode'."
11060 (interactive)
11061 (org-table-justify-field-maybe)
11062 (org-table-next-row))
11064 (defun orgtbl-self-insert-command (N)
11065 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11066 If the cursor is in a table looking at whitespace, the whitespace is
11067 overwritten, and the table is not marked as requiring realignment."
11068 (interactive "p")
11069 (if (and (org-at-table-p)
11071 (and org-table-auto-blank-field
11072 (member last-command
11073 '(orgtbl-hijacker-command-100
11074 orgtbl-hijacker-command-101
11075 orgtbl-hijacker-command-102
11076 orgtbl-hijacker-command-103
11077 orgtbl-hijacker-command-104
11078 orgtbl-hijacker-command-105))
11079 (org-table-blank-field))
11081 (eq N 1)
11082 (looking-at "[^|\n]* +|"))
11083 (let (org-table-may-need-update)
11084 (goto-char (1- (match-end 0)))
11085 (delete-backward-char 1)
11086 (goto-char (match-beginning 0))
11087 (self-insert-command N))
11088 (setq org-table-may-need-update t)
11089 (let (orgtbl-mode)
11090 (call-interactively (key-binding (vector last-input-event))))))
11092 (defun org-force-self-insert (N)
11093 "Needed to enforce self-insert under remapping."
11094 (interactive "p")
11095 (self-insert-command N))
11097 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11098 "Regula expression matching exponentials as produced by calc.")
11100 (defvar org-table-clean-did-remove-column nil)
11102 (defun orgtbl-export (table target)
11103 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11104 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11105 org-table-last-alignment org-table-last-column-widths
11106 maxcol column)
11107 (if (not (fboundp func))
11108 (error "Cannot export orgtbl table to %s" target))
11109 (setq lines (org-table-clean-before-export lines))
11110 (setq table
11111 (mapcar
11112 (lambda (x)
11113 (if (string-match org-table-hline-regexp x)
11114 'hline
11115 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11116 lines))
11117 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11118 table)))
11119 (loop for i from (1- maxcol) downto 0 do
11120 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11121 (setq column (delq nil column))
11122 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11123 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
11124 (funcall func table nil)))
11126 (defun orgtbl-send-table (&optional maybe)
11127 "Send a tranformed version of this table to the receiver position.
11128 With argument MAYBE, fail quietly if no transformation is defined for
11129 this table."
11130 (interactive)
11131 (catch 'exit
11132 (unless (org-at-table-p) (error "Not at a table"))
11133 ;; when non-interactive, we assume align has just happened.
11134 (when (interactive-p) (org-table-align))
11135 (save-excursion
11136 (goto-char (org-table-begin))
11137 (beginning-of-line 0)
11138 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11139 (if maybe
11140 (throw 'exit nil)
11141 (error "Don't know how to transform this table."))))
11142 (let* ((name (match-string 1))
11144 (transform (intern (match-string 2)))
11145 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11146 (skip (plist-get params :skip))
11147 (skipcols (plist-get params :skipcols))
11148 (txt (buffer-substring-no-properties
11149 (org-table-begin) (org-table-end)))
11150 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11151 (lines (org-table-clean-before-export lines))
11152 (i0 (if org-table-clean-did-remove-column 2 1))
11153 (table (mapcar
11154 (lambda (x)
11155 (if (string-match org-table-hline-regexp x)
11156 'hline
11157 (org-remove-by-index
11158 (org-split-string (org-trim x) "\\s-*|\\s-*")
11159 skipcols i0)))
11160 lines))
11161 (fun (if (= i0 2) 'cdr 'identity))
11162 (org-table-last-alignment
11163 (org-remove-by-index (funcall fun org-table-last-alignment)
11164 skipcols i0))
11165 (org-table-last-column-widths
11166 (org-remove-by-index (funcall fun org-table-last-column-widths)
11167 skipcols i0)))
11169 (unless (fboundp transform)
11170 (error "No such transformation function %s" transform))
11171 (setq txt (funcall transform table params))
11172 ;; Find the insertion place
11173 (save-excursion
11174 (goto-char (point-min))
11175 (unless (re-search-forward
11176 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11177 (error "Don't know where to insert translated table"))
11178 (goto-char (match-beginning 0))
11179 (beginning-of-line 2)
11180 (setq beg (point))
11181 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11182 (error "Cannot find end of insertion region"))
11183 (beginning-of-line 1)
11184 (delete-region beg (point))
11185 (goto-char beg)
11186 (insert txt "\n"))
11187 (message "Table converted and installed at receiver location"))))
11189 (defun org-remove-by-index (list indices &optional i0)
11190 "Remove the elements in LIST with indices in INDICES.
11191 First element has index 0, or I0 if given."
11192 (if (not indices)
11193 list
11194 (if (integerp indices) (setq indices (list indices)))
11195 (setq i0 (1- (or i0 0)))
11196 (delq :rm (mapcar (lambda (x)
11197 (setq i0 (1+ i0))
11198 (if (memq i0 indices) :rm x))
11199 list))))
11201 (defun orgtbl-toggle-comment ()
11202 "Comment or uncomment the orgtbl at point."
11203 (interactive)
11204 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11205 (re2 (concat "^" orgtbl-line-start-regexp))
11206 (commented (save-excursion (beginning-of-line 1)
11207 (cond ((looking-at re1) t)
11208 ((looking-at re2) nil)
11209 (t (error "Not at an org table")))))
11210 (re (if commented re1 re2))
11211 beg end)
11212 (save-excursion
11213 (beginning-of-line 1)
11214 (while (looking-at re) (beginning-of-line 0))
11215 (beginning-of-line 2)
11216 (setq beg (point))
11217 (while (looking-at re) (beginning-of-line 2))
11218 (setq end (point)))
11219 (comment-region beg end (if commented '(4) nil))))
11221 (defun orgtbl-insert-radio-table ()
11222 "Insert a radio table template appropriate for this major mode."
11223 (interactive)
11224 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11225 (txt (nth 1 e))
11226 name pos)
11227 (unless e (error "No radio table setup defined for %s" major-mode))
11228 (setq name (read-string "Table name: "))
11229 (while (string-match "%n" txt)
11230 (setq txt (replace-match name t t txt)))
11231 (or (bolp) (insert "\n"))
11232 (setq pos (point))
11233 (insert txt)
11234 (goto-char pos)))
11236 (defun org-get-param (params header i sym &optional hsym)
11237 "Get parameter value for symbol SYM.
11238 If this is a header line, actually get the value for the symbol with an
11239 additional \"h\" inserted after the colon.
11240 If the value is a protperty list, get the element for the current column.
11241 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11242 (let ((val (plist-get params sym)))
11243 (and hsym header (setq val (or (plist-get params hsym) val)))
11244 (if (consp val) (plist-get val i) val)))
11246 (defun orgtbl-to-generic (table params)
11247 "Convert the orgtbl-mode TABLE to some other format.
11248 This generic routine can be used for many standard cases.
11249 TABLE is a list, each entry either the symbol `hline' for a horizontal
11250 separator line, or a list of fields for that line.
11251 PARAMS is a property list of parameters that can influence the conversion.
11252 For the generic converter, some parameters are obligatory: You need to
11253 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11254 :splice, you must have :tstart and :tend.
11256 Valid parameters are
11258 :tstart String to start the table. Ignored when :splice is t.
11259 :tend String to end the table. Ignored when :splice is t.
11261 :splice When set to t, return only table body lines, don't wrap
11262 them into :tstart and :tend. Default is nil.
11264 :hline String to be inserted on horizontal separation lines.
11265 May be nil to ignore hlines.
11267 :lstart String to start a new table line.
11268 :lend String to end a table line
11269 :sep Separator between two fields
11270 :lfmt Format for entire line, with enough %s to capture all fields.
11271 If this is present, :lstart, :lend, and :sep are ignored.
11272 :fmt A format to be used to wrap the field, should contain
11273 %s for the original field value. For example, to wrap
11274 everything in dollars, you could use :fmt \"$%s$\".
11275 This may also be a property list with column numbers and
11276 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11278 :hlstart :hlend :hlsep :hlfmt :hfmt
11279 Same as above, specific for the header lines in the table.
11280 All lines before the first hline are treated as header.
11281 If any of these is not present, the data line value is used.
11283 :efmt Use this format to print numbers with exponentials.
11284 The format should have %s twice for inserting mantissa
11285 and exponent, for example \"%s\\\\times10^{%s}\". This
11286 may also be a property list with column numbers and
11287 formats. :fmt will still be applied after :efmt.
11289 In addition to this, the parameters :skip and :skipcols are always handled
11290 directly by `orgtbl-send-table'. See manual."
11291 (interactive)
11292 (let* ((p params)
11293 (splicep (plist-get p :splice))
11294 (hline (plist-get p :hline))
11295 rtn line i fm efm lfmt h)
11297 ;; Do we have a header?
11298 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11299 (setq h t))
11301 ;; Put header
11302 (unless splicep
11303 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11305 ;; Now loop over all lines
11306 (while (setq line (pop table))
11307 (if (eq line 'hline)
11308 ;; A horizontal separator line
11309 (progn (if hline (push hline rtn))
11310 (setq h nil)) ; no longer in header
11311 ;; A normal line. Convert the fields, push line onto the result list
11312 (setq i 0)
11313 (setq line
11314 (mapcar
11315 (lambda (f)
11316 (setq i (1+ i)
11317 fm (org-get-param p h i :fmt :hfmt)
11318 efm (org-get-param p h i :efmt))
11319 (if (and efm (string-match orgtbl-exp-regexp f))
11320 (setq f (format
11321 efm (match-string 1 f) (match-string 2 f))))
11322 (if fm (setq f (format fm f)))
11324 line))
11325 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11326 (push (apply 'format lfmt line) rtn)
11327 (push (concat
11328 (org-get-param p h i :lstart :hlstart)
11329 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11330 (org-get-param p h i :lend :hlend))
11331 rtn))))
11333 (unless splicep
11334 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11336 (mapconcat 'identity (nreverse rtn) "\n")))
11338 (defun orgtbl-to-latex (table params)
11339 "Convert the orgtbl-mode TABLE to LaTeX.
11340 TABLE is a list, each entry either the symbol `hline' for a horizontal
11341 separator line, or a list of fields for that line.
11342 PARAMS is a property list of parameters that can influence the conversion.
11343 Supports all parameters from `orgtbl-to-generic'. Most important for
11344 LaTeX are:
11346 :splice When set to t, return only table body lines, don't wrap
11347 them into a tabular environment. Default is nil.
11349 :fmt A format to be used to wrap the field, should contain %s for the
11350 original field value. For example, to wrap everything in dollars,
11351 use :fmt \"$%s$\". This may also be a property list with column
11352 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11354 :efmt Format for transforming numbers with exponentials. The format
11355 should have %s twice for inserting mantissa and exponent, for
11356 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11357 This may also be a property list with column numbers and formats.
11359 The general parameters :skip and :skipcols have already been applied when
11360 this function is called."
11361 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11362 org-table-last-alignment ""))
11363 (params2
11364 (list
11365 :tstart (concat "\\begin{tabular}{" alignment "}")
11366 :tend "\\end{tabular}"
11367 :lstart "" :lend " \\\\" :sep " & "
11368 :efmt "%s\\,(%s)" :hline "\\hline")))
11369 (orgtbl-to-generic table (org-combine-plists params2 params))))
11371 (defun orgtbl-to-html (table params)
11372 "Convert the orgtbl-mode TABLE to LaTeX.
11373 TABLE is a list, each entry either the symbol `hline' for a horizontal
11374 separator line, or a list of fields for that line.
11375 PARAMS is a property list of parameters that can influence the conversion.
11376 Currently this function recognizes the following parameters:
11378 :splice When set to t, return only table body lines, don't wrap
11379 them into a <table> environment. Default is nil.
11381 The general parameters :skip and :skipcols have already been applied when
11382 this function is called. The function does *not* use `orgtbl-to-generic',
11383 so you cannot specify parameters for it."
11384 (let* ((splicep (plist-get params :splice))
11385 html)
11386 ;; Just call the formatter we already have
11387 ;; We need to make text lines for it, so put the fields back together.
11388 (setq html (org-format-org-table-html
11389 (mapcar
11390 (lambda (x)
11391 (if (eq x 'hline)
11392 "|----+----|"
11393 (concat "| " (mapconcat 'identity x " | ") " |")))
11394 table)
11395 splicep))
11396 (if (string-match "\n+\\'" html)
11397 (setq html (replace-match "" t t html)))
11398 html))
11400 (defun orgtbl-to-texinfo (table params)
11401 "Convert the orgtbl-mode TABLE to TeXInfo.
11402 TABLE is a list, each entry either the symbol `hline' for a horizontal
11403 separator line, or a list of fields for that line.
11404 PARAMS is a property list of parameters that can influence the conversion.
11405 Supports all parameters from `orgtbl-to-generic'. Most important for
11406 TeXInfo are:
11408 :splice nil/t When set to t, return only table body lines, don't wrap
11409 them into a multitable environment. Default is nil.
11411 :fmt fmt A format to be used to wrap the field, should contain
11412 %s for the original field value. For example, to wrap
11413 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11414 This may also be a property list with column numbers and
11415 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11417 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11418 are computed automatically from the width of the columns
11419 under org-mode.
11421 The general parameters :skip and :skipcols have already been applied when
11422 this function is called."
11423 (let* ((total (float (apply '+ org-table-last-column-widths)))
11424 (colfrac (or (plist-get params :cf)
11425 (mapconcat
11426 (lambda (x) (format "%.3f" (/ (float x) total)))
11427 org-table-last-column-widths " ")))
11428 (params2
11429 (list
11430 :tstart (concat "@multitable @columnfractions " colfrac)
11431 :tend "@end multitable"
11432 :lstart "@item " :lend "" :sep " @tab "
11433 :hlstart "@headitem ")))
11434 (orgtbl-to-generic table (org-combine-plists params2 params))))
11436 ;;;; Link Stuff
11438 ;;; Link abbreviations
11440 (defun org-link-expand-abbrev (link)
11441 "Apply replacements as defined in `org-link-abbrev-alist."
11442 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11443 (let* ((key (match-string 1 link))
11444 (as (or (assoc key org-link-abbrev-alist-local)
11445 (assoc key org-link-abbrev-alist)))
11446 (tag (and (match-end 2) (match-string 3 link)))
11447 rpl)
11448 (if (not as)
11449 link
11450 (setq rpl (cdr as))
11451 (cond
11452 ((symbolp rpl) (funcall rpl tag))
11453 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11454 (t (concat rpl tag)))))
11455 link))
11457 ;;; Storing and inserting links
11459 (defvar org-insert-link-history nil
11460 "Minibuffer history for links inserted with `org-insert-link'.")
11462 (defvar org-stored-links nil
11463 "Contains the links stored with `org-store-link'.")
11465 (defvar org-store-link-plist nil
11466 "Plist with info about the most recently link created with `org-store-link'.")
11468 (defvar org-link-protocols nil
11469 "Link protocols added to Org-mode using `org-add-link-type'.")
11471 (defvar org-store-link-functions nil
11472 "List of functions that are called to create and store a link.
11473 Each function will be called in turn until one returns a non-nil
11474 value. Each function should check if it is responsible for creating
11475 this link (for example by looking at the major mode).
11476 If not, it must exit and return nil.
11477 If yes, it should return a non-nil value after a calling
11478 `org-store-link-props' with a list of properties and values.
11479 Special properties are:
11481 :type The link prefix. like \"http\". This must be given.
11482 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11483 This is obligatory as well.
11484 :description Optional default description for the second pair
11485 of brackets in an Org-mode link. The user can still change
11486 this when inserting this link into an Org-mode buffer.
11488 In addition to these, any additional properties can be specified
11489 and then used in remember templates.")
11491 (defun org-add-link-type (type &optional follow publish)
11492 "Add TYPE to the list of `org-link-types'.
11493 Re-compute all regular expressions depending on `org-link-types'
11494 FOLLOW and PUBLISH are two functions. Both take the link path as
11495 an argument.
11496 FOLLOW should do whatever is necessary to follow the link, for example
11497 to find a file or display a mail message.
11499 PUBLISH takes the path and retuns the string that should be used when
11500 this document is published. FIMXE: This is actually not yet implemented."
11501 (add-to-list 'org-link-types type t)
11502 (org-make-link-regexps)
11503 (add-to-list 'org-link-protocols
11504 (list type follow publish)))
11506 (defun org-add-agenda-custom-command (entry)
11507 "Replace or add a command in `org-agenda-custom-commands'.
11508 This is mostly for hacking and trying a new command - once the command
11509 works you probably want to add it to `org-agenda-custom-commands' for good."
11510 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11511 (if ass
11512 (setcdr ass (cdr entry))
11513 (push entry org-agenda-custom-commands))))
11515 ;;;###autoload
11516 (defun org-store-link (arg)
11517 "\\<org-mode-map>Store an org-link to the current location.
11518 This link can later be inserted into an org-buffer with
11519 \\[org-insert-link].
11520 For some link types, a prefix arg is interpreted:
11521 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11522 For file links, arg negates `org-context-in-file-links'."
11523 (interactive "P")
11524 (setq org-store-link-plist nil) ; reset
11525 (let (link cpltxt desc description search txt)
11526 (cond
11528 ((run-hook-with-args-until-success 'org-store-link-functions)
11529 (setq link (plist-get org-store-link-plist :link)
11530 desc (or (plist-get org-store-link-plist :description) link)))
11532 ((eq major-mode 'bbdb-mode)
11533 (let ((name (bbdb-record-name (bbdb-current-record)))
11534 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11535 (setq cpltxt (concat "bbdb:" (or name company))
11536 link (org-make-link cpltxt))
11537 (org-store-link-props :type "bbdb" :name name :company company)))
11539 ((eq major-mode 'Info-mode)
11540 (setq link (org-make-link "info:"
11541 (file-name-nondirectory Info-current-file)
11542 ":" Info-current-node))
11543 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11544 ":" Info-current-node))
11545 (org-store-link-props :type "info" :file Info-current-file
11546 :node Info-current-node))
11548 ((eq major-mode 'calendar-mode)
11549 (let ((cd (calendar-cursor-to-date)))
11550 (setq link
11551 (format-time-string
11552 (car org-time-stamp-formats)
11553 (apply 'encode-time
11554 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11555 nil nil nil))))
11556 (org-store-link-props :type "calendar" :date cd)))
11558 ((or (eq major-mode 'vm-summary-mode)
11559 (eq major-mode 'vm-presentation-mode))
11560 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11561 (vm-follow-summary-cursor)
11562 (save-excursion
11563 (vm-select-folder-buffer)
11564 (let* ((message (car vm-message-pointer))
11565 (folder buffer-file-name)
11566 (subject (vm-su-subject message))
11567 (to (vm-get-header-contents message "To"))
11568 (from (vm-get-header-contents message "From"))
11569 (message-id (vm-su-message-id message)))
11570 (org-store-link-props :type "vm" :from from :to to :subject subject
11571 :message-id message-id)
11572 (setq message-id (org-remove-angle-brackets message-id))
11573 (setq folder (abbreviate-file-name folder))
11574 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11575 folder)
11576 (setq folder (replace-match "" t t folder)))
11577 (setq cpltxt (org-email-link-description))
11578 (setq link (org-make-link "vm:" folder "#" message-id)))))
11580 ((eq major-mode 'wl-summary-mode)
11581 (let* ((msgnum (wl-summary-message-number))
11582 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11583 msgnum 'message-id))
11584 (wl-message-entity
11585 (if (fboundp 'elmo-message-entity)
11586 (elmo-message-entity
11587 wl-summary-buffer-elmo-folder msgnum)
11588 (elmo-msgdb-overview-get-entity
11589 msgnum (wl-summary-buffer-msgdb))))
11590 (from (wl-summary-line-from))
11591 (to (elmo-message-entity-field wl-message-entity 'to))
11592 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11593 (wl-summary-line-subject))))
11594 (org-store-link-props :type "wl" :from from :to to
11595 :subject subject :message-id message-id)
11596 (setq message-id (org-remove-angle-brackets message-id))
11597 (setq cpltxt (org-email-link-description))
11598 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11599 "#" message-id))))
11601 ((or (equal major-mode 'mh-folder-mode)
11602 (equal major-mode 'mh-show-mode))
11603 (let ((from (org-mhe-get-header "From:"))
11604 (to (org-mhe-get-header "To:"))
11605 (message-id (org-mhe-get-header "Message-Id:"))
11606 (subject (org-mhe-get-header "Subject:")))
11607 (org-store-link-props :type "mh" :from from :to to
11608 :subject subject :message-id message-id)
11609 (setq cpltxt (org-email-link-description))
11610 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11611 (org-remove-angle-brackets message-id)))))
11613 ((eq major-mode 'rmail-mode)
11614 (save-excursion
11615 (save-restriction
11616 (rmail-narrow-to-non-pruned-header)
11617 (let ((folder buffer-file-name)
11618 (message-id (mail-fetch-field "message-id"))
11619 (from (mail-fetch-field "from"))
11620 (to (mail-fetch-field "to"))
11621 (subject (mail-fetch-field "subject")))
11622 (org-store-link-props
11623 :type "rmail" :from from :to to
11624 :subject subject :message-id message-id)
11625 (setq message-id (org-remove-angle-brackets message-id))
11626 (setq cpltxt (org-email-link-description))
11627 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11629 ((eq major-mode 'gnus-group-mode)
11630 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11631 (gnus-group-group-name)) ; version
11632 ((fboundp 'gnus-group-name)
11633 (gnus-group-name))
11634 (t "???"))))
11635 (unless group (error "Not on a group"))
11636 (org-store-link-props :type "gnus" :group group)
11637 (setq cpltxt (concat
11638 (if (org-xor arg org-usenet-links-prefer-google)
11639 "http://groups.google.com/groups?group="
11640 "gnus:")
11641 group)
11642 link (org-make-link cpltxt))))
11644 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11645 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11646 (let* ((group gnus-newsgroup-name)
11647 (article (gnus-summary-article-number))
11648 (header (gnus-summary-article-header article))
11649 (from (mail-header-from header))
11650 (message-id (mail-header-id header))
11651 (date (mail-header-date header))
11652 (subject (gnus-summary-subject-string)))
11653 (org-store-link-props :type "gnus" :from from :subject subject
11654 :message-id message-id :group group)
11655 (setq cpltxt (org-email-link-description))
11656 (if (org-xor arg org-usenet-links-prefer-google)
11657 (setq link
11658 (concat
11659 cpltxt "\n "
11660 (format "http://groups.google.com/groups?as_umsgid=%s"
11661 (org-fixup-message-id-for-http message-id))))
11662 (setq link (org-make-link "gnus:" group
11663 "#" (number-to-string article))))))
11665 ((eq major-mode 'w3-mode)
11666 (setq cpltxt (url-view-url t)
11667 link (org-make-link cpltxt))
11668 (org-store-link-props :type "w3" :url (url-view-url t)))
11670 ((eq major-mode 'w3m-mode)
11671 (setq cpltxt (or w3m-current-title w3m-current-url)
11672 link (org-make-link w3m-current-url))
11673 (org-store-link-props :type "w3m" :url (url-view-url t)))
11675 ((setq search (run-hook-with-args-until-success
11676 'org-create-file-search-functions))
11677 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11678 "::" search))
11679 (setq cpltxt (or description link)))
11681 ((eq major-mode 'image-mode)
11682 (setq cpltxt (concat "file:"
11683 (abbreviate-file-name buffer-file-name))
11684 link (org-make-link cpltxt))
11685 (org-store-link-props :type "image" :file buffer-file-name))
11687 ((eq major-mode 'dired-mode)
11688 ;; link to the file in the current line
11689 (setq cpltxt (concat "file:"
11690 (abbreviate-file-name
11691 (expand-file-name
11692 (dired-get-filename nil t))))
11693 link (org-make-link cpltxt)))
11695 ((and buffer-file-name (org-mode-p))
11696 ;; Just link to current headline
11697 (setq cpltxt (concat "file:"
11698 (abbreviate-file-name buffer-file-name)))
11699 ;; Add a context search string
11700 (when (org-xor org-context-in-file-links arg)
11701 ;; Check if we are on a target
11702 (if (org-in-regexp "<<\\(.*?\\)>>")
11703 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11704 (setq txt (cond
11705 ((org-on-heading-p) nil)
11706 ((org-region-active-p)
11707 (buffer-substring (region-beginning) (region-end)))
11708 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11709 (when (or (null txt) (string-match "\\S-" txt))
11710 (setq cpltxt
11711 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11712 desc "NONE"))))
11713 (if (string-match "::\\'" cpltxt)
11714 (setq cpltxt (substring cpltxt 0 -2)))
11715 (setq link (org-make-link cpltxt)))
11717 ((buffer-file-name (buffer-base-buffer))
11718 ;; Just link to this file here.
11719 (setq cpltxt (concat "file:"
11720 (abbreviate-file-name
11721 (buffer-file-name (buffer-base-buffer)))))
11722 ;; Add a context string
11723 (when (org-xor org-context-in-file-links arg)
11724 (setq txt (if (org-region-active-p)
11725 (buffer-substring (region-beginning) (region-end))
11726 (buffer-substring (point-at-bol) (point-at-eol))))
11727 ;; Only use search option if there is some text.
11728 (when (string-match "\\S-" txt)
11729 (setq cpltxt
11730 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11731 desc "NONE")))
11732 (setq link (org-make-link cpltxt)))
11734 ((interactive-p)
11735 (error "Cannot link to a buffer which is not visiting a file"))
11737 (t (setq link nil)))
11739 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11740 (setq link (or link cpltxt)
11741 desc (or desc cpltxt))
11742 (if (equal desc "NONE") (setq desc nil))
11744 (if (and (interactive-p) link)
11745 (progn
11746 (setq org-stored-links
11747 (cons (list link desc) org-stored-links))
11748 (message "Stored: %s" (or desc link)))
11749 (and link (org-make-link-string link desc)))))
11751 (defun org-store-link-props (&rest plist)
11752 "Store link properties, extract names and addresses."
11753 (let (x adr)
11754 (when (setq x (plist-get plist :from))
11755 (setq adr (mail-extract-address-components x))
11756 (plist-put plist :fromname (car adr))
11757 (plist-put plist :fromaddress (nth 1 adr)))
11758 (when (setq x (plist-get plist :to))
11759 (setq adr (mail-extract-address-components x))
11760 (plist-put plist :toname (car adr))
11761 (plist-put plist :toaddress (nth 1 adr))))
11762 (let ((from (plist-get plist :from))
11763 (to (plist-get plist :to)))
11764 (when (and from to org-from-is-user-regexp)
11765 (plist-put plist :fromto
11766 (if (string-match org-from-is-user-regexp from)
11767 (concat "to %t")
11768 (concat "from %f")))))
11769 (setq org-store-link-plist plist))
11771 (defun org-email-link-description (&optional fmt)
11772 "Return the description part of an email link.
11773 This takes information from `org-store-link-plist' and formats it
11774 according to FMT (default from `org-email-link-description-format')."
11775 (setq fmt (or fmt org-email-link-description-format))
11776 (let* ((p org-store-link-plist)
11777 (to (plist-get p :toaddress))
11778 (from (plist-get p :fromaddress))
11779 (table
11780 (list
11781 (cons "%c" (plist-get p :fromto))
11782 (cons "%F" (plist-get p :from))
11783 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11784 (cons "%T" (plist-get p :to))
11785 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11786 (cons "%s" (plist-get p :subject))
11787 (cons "%m" (plist-get p :message-id)))))
11788 (when (string-match "%c" fmt)
11789 ;; Check if the user wrote this message
11790 (if (and org-from-is-user-regexp from to
11791 (save-match-data (string-match org-from-is-user-regexp from)))
11792 (setq fmt (replace-match "to %t" t t fmt))
11793 (setq fmt (replace-match "from %f" t t fmt))))
11794 (org-replace-escapes fmt table)))
11796 (defun org-make-org-heading-search-string (&optional string heading)
11797 "Make search string for STRING or current headline."
11798 (interactive)
11799 (let ((s (or string (org-get-heading))))
11800 (unless (and string (not heading))
11801 ;; We are using a headline, clean up garbage in there.
11802 (if (string-match org-todo-regexp s)
11803 (setq s (replace-match "" t t s)))
11804 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11805 (setq s (replace-match "" t t s)))
11806 (setq s (org-trim s))
11807 (if (string-match (concat "^\\(" org-quote-string "\\|"
11808 org-comment-string "\\)") s)
11809 (setq s (replace-match "" t t s)))
11810 (while (string-match org-ts-regexp s)
11811 (setq s (replace-match "" t t s))))
11812 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11813 (setq s (replace-match " " t t s)))
11814 (or string (setq s (concat "*" s))) ; Add * for headlines
11815 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11817 (defun org-make-link (&rest strings)
11818 "Concatenate STRINGS."
11819 (apply 'concat strings))
11821 (defun org-make-link-string (link &optional description)
11822 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11823 (unless (string-match "\\S-" link)
11824 (error "Empty link"))
11825 (when (stringp description)
11826 ;; Remove brackets from the description, they are fatal.
11827 (while (string-match "\\[\\|\\]" description)
11828 (setq description (replace-match "" t t description))))
11829 (when (equal (org-link-escape link) description)
11830 ;; No description needed, it is identical
11831 (setq description nil))
11832 (when (and (not description)
11833 (not (equal link (org-link-escape link))))
11834 (setq description link))
11835 (concat "[[" (org-link-escape link) "]"
11836 (if description (concat "[" description "]") "")
11837 "]"))
11839 (defconst org-link-escape-chars
11840 '((?\ . "%20")
11841 (?\[ . "%5B")
11842 (?\] . "%5d")
11843 (?\340 . "%E0") ; `a
11844 (?\342 . "%E2") ; ^a
11845 (?\347 . "%E7") ; ,c
11846 (?\350 . "%E8") ; `e
11847 (?\351 . "%E9") ; 'e
11848 (?\352 . "%EA") ; ^e
11849 (?\356 . "%EE") ; ^i
11850 (?\364 . "%F4") ; ^o
11851 (?\371 . "%F9") ; `u
11852 (?\373 . "%FB") ; ^u
11853 (?\; . "%3B")
11854 (?? . "%3F")
11855 (?= . "%3D")
11856 (?+ . "%2B")
11858 "Association list of escapes for some characters problematic in links.
11859 This is the list that is used for internal purposes.")
11861 (defconst org-link-escape-chars-browser
11862 '((?\ . "%20")) ; 32 for the SPC char
11864 "Association list of escapes for some characters problematic in links.
11865 This is the list that is used before handing over to the browser.")
11867 (defun org-link-escape (text &optional table)
11868 "Escape charaters in TEXT that are problematic for links."
11869 (setq table (or table org-link-escape-chars))
11870 (when text
11871 (let ((re (mapconcat (lambda (x) (regexp-quote
11872 (char-to-string (car x))))
11873 table "\\|")))
11874 (while (string-match re text)
11875 (setq text
11876 (replace-match
11877 (cdr (assoc (string-to-char (match-string 0 text))
11878 table))
11879 t t text)))
11880 text)))
11882 (defun org-link-unescape (text &optional table)
11883 "Reverse the action of `org-link-escape'."
11884 (setq table (or table org-link-escape-chars))
11885 (when text
11886 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11887 table "\\|")))
11888 (while (string-match re text)
11889 (setq text
11890 (replace-match
11891 (char-to-string (car (rassoc (match-string 0 text) table)))
11892 t t text)))
11893 text)))
11895 (defun org-xor (a b)
11896 "Exclusive or."
11897 (if a (not b) b))
11899 (defun org-get-header (header)
11900 "Find a header field in the current buffer."
11901 (save-excursion
11902 (goto-char (point-min))
11903 (let ((case-fold-search t) s)
11904 (cond
11905 ((eq header 'from)
11906 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11907 (setq s (match-string 1)))
11908 (while (string-match "\"" s)
11909 (setq s (replace-match "" t t s)))
11910 (if (string-match "[<(].*" s)
11911 (setq s (replace-match "" t t s))))
11912 ((eq header 'message-id)
11913 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11914 (setq s (match-string 1))))
11915 ((eq header 'subject)
11916 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11917 (setq s (match-string 1)))))
11918 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11919 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11920 s)))
11923 (defun org-fixup-message-id-for-http (s)
11924 "Replace special characters in a message id, so it can be used in an http query."
11925 (while (string-match "<" s)
11926 (setq s (replace-match "%3C" t t s)))
11927 (while (string-match ">" s)
11928 (setq s (replace-match "%3E" t t s)))
11929 (while (string-match "@" s)
11930 (setq s (replace-match "%40" t t s)))
11933 ;;;###autoload
11934 (defun org-insert-link-global ()
11935 "Insert a link like Org-mode does.
11936 This command can be called in any mode to insert a link in Org-mode syntax."
11937 (interactive)
11938 (org-run-like-in-org-mode 'org-insert-link))
11940 (defun org-insert-link (&optional complete-file)
11941 "Insert a link. At the prompt, enter the link.
11943 Completion can be used to select a link previously stored with
11944 `org-store-link'. When the empty string is entered (i.e. if you just
11945 press RET at the prompt), the link defaults to the most recently
11946 stored link. As SPC triggers completion in the minibuffer, you need to
11947 use M-SPC or C-q SPC to force the insertion of a space character.
11949 You will also be prompted for a description, and if one is given, it will
11950 be displayed in the buffer instead of the link.
11952 If there is already a link at point, this command will allow you to edit link
11953 and description parts.
11955 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11956 selected using completion. The path to the file will be relative to
11957 the current directory if the file is in the current directory or a
11958 subdirectory. Otherwise, the link will be the absolute path as
11959 completed in the minibuffer (i.e. normally ~/path/to/file).
11961 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11962 is in the current directory or below.
11963 With three \\[universal-argument] prefixes, negate the meaning of
11964 `org-keep-stored-link-after-insertion'."
11965 (interactive "P")
11966 (let* ((wcf (current-window-configuration))
11967 (region (if (org-region-active-p)
11968 (buffer-substring (region-beginning) (region-end))))
11969 (remove (and region (list (region-beginning) (region-end))))
11970 (desc region)
11971 tmphist ; byte-compile incorrectly complains about this
11972 link entry file)
11973 (cond
11974 ((org-in-regexp org-bracket-link-regexp 1)
11975 ;; We do have a link at point, and we are going to edit it.
11976 (setq remove (list (match-beginning 0) (match-end 0)))
11977 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11978 (setq link (read-string "Link: "
11979 (org-link-unescape
11980 (org-match-string-no-properties 1)))))
11981 ((or (org-in-regexp org-angle-link-re)
11982 (org-in-regexp org-plain-link-re))
11983 ;; Convert to bracket link
11984 (setq remove (list (match-beginning 0) (match-end 0))
11985 link (read-string "Link: "
11986 (org-remove-angle-brackets (match-string 0)))))
11987 ((equal complete-file '(4))
11988 ;; Completing read for file names.
11989 (setq file (read-file-name "File: "))
11990 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11991 (pwd1 (file-name-as-directory (abbreviate-file-name
11992 (expand-file-name ".")))))
11993 (cond
11994 ((equal complete-file '(16))
11995 (setq link (org-make-link
11996 "file:"
11997 (abbreviate-file-name (expand-file-name file)))))
11998 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11999 (setq link (org-make-link "file:" (match-string 1 file))))
12000 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12001 (expand-file-name file))
12002 (setq link (org-make-link
12003 "file:" (match-string 1 (expand-file-name file)))))
12004 (t (setq link (org-make-link "file:" file))))))
12006 ;; Read link, with completion for stored links.
12007 (with-output-to-temp-buffer "*Org Links*"
12008 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12009 (when org-stored-links
12010 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12011 (princ (mapconcat
12012 (lambda (x)
12013 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12014 (reverse org-stored-links) "\n"))))
12015 (let ((cw (selected-window)))
12016 (select-window (get-buffer-window "*Org Links*"))
12017 (shrink-window-if-larger-than-buffer)
12018 (setq truncate-lines t)
12019 (select-window cw))
12020 ;; Fake a link history, containing the stored links.
12021 (setq tmphist (append (mapcar 'car org-stored-links)
12022 org-insert-link-history))
12023 (unwind-protect
12024 (setq link (org-completing-read
12025 "Link: "
12026 (append
12027 (mapcar (lambda (x) (list (concat (car x) ":")))
12028 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12029 (mapcar (lambda (x) (list (concat x ":")))
12030 org-link-types))
12031 nil nil nil
12032 'tmphist
12033 (or (car (car org-stored-links)))))
12034 (set-window-configuration wcf)
12035 (kill-buffer "*Org Links*"))
12036 (setq entry (assoc link org-stored-links))
12037 (or entry (push link org-insert-link-history))
12038 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12039 (not org-keep-stored-link-after-insertion))
12040 (setq org-stored-links (delq (assoc link org-stored-links)
12041 org-stored-links)))
12042 (setq desc (or desc (nth 1 entry)))))
12044 (if (string-match org-plain-link-re link)
12045 ;; URL-like link, normalize the use of angular brackets.
12046 (setq link (org-make-link (org-remove-angle-brackets link))))
12048 ;; Check if we are linking to the current file with a search option
12049 ;; If yes, simplify the link by using only the search option.
12050 (when (and buffer-file-name
12051 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12052 (let* ((path (match-string 1 link))
12053 (case-fold-search nil)
12054 (search (match-string 2 link)))
12055 (save-match-data
12056 (if (equal (file-truename buffer-file-name) (file-truename path))
12057 ;; We are linking to this same file, with a search option
12058 (setq link search)))))
12060 ;; Check if we can/should use a relative path. If yes, simplify the link
12061 (when (string-match "\\<file:\\(.*\\)" link)
12062 (let* ((path (match-string 1 link))
12063 (origpath path)
12064 (desc-is-link (equal link desc))
12065 (case-fold-search nil))
12066 (cond
12067 ((eq org-link-file-path-type 'absolute)
12068 (setq path (abbreviate-file-name (expand-file-name path))))
12069 ((eq org-link-file-path-type 'noabbrev)
12070 (setq path (expand-file-name path)))
12071 ((eq org-link-file-path-type 'relative)
12072 (setq path (file-relative-name path)))
12074 (save-match-data
12075 (if (string-match (concat "^" (regexp-quote
12076 (file-name-as-directory
12077 (expand-file-name "."))))
12078 (expand-file-name path))
12079 ;; We are linking a file with relative path name.
12080 (setq path (substring (expand-file-name path)
12081 (match-end 0)))))))
12082 (setq link (concat "file:" path))
12083 (if (equal desc origpath)
12084 (setq desc path))))
12086 (setq desc (read-string "Description: " desc))
12087 (unless (string-match "\\S-" desc) (setq desc nil))
12088 (if remove (apply 'delete-region remove))
12089 (insert (org-make-link-string link desc))))
12091 (defun org-completing-read (&rest args)
12092 (let ((minibuffer-local-completion-map
12093 (copy-keymap minibuffer-local-completion-map)))
12094 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12095 (apply 'completing-read args)))
12097 ;;; Opening/following a link
12098 (defvar org-link-search-failed nil)
12100 (defun org-next-link ()
12101 "Move forward to the next link.
12102 If the link is in hidden text, expose it."
12103 (interactive)
12104 (when (and org-link-search-failed (eq this-command last-command))
12105 (goto-char (point-min))
12106 (message "Link search wrapped back to beginning of buffer"))
12107 (setq org-link-search-failed nil)
12108 (let* ((pos (point))
12109 (ct (org-context))
12110 (a (assoc :link ct)))
12111 (if a (goto-char (nth 2 a)))
12112 (if (re-search-forward org-any-link-re nil t)
12113 (progn
12114 (goto-char (match-beginning 0))
12115 (if (org-invisible-p) (org-show-context)))
12116 (goto-char pos)
12117 (setq org-link-search-failed t)
12118 (error "No further link found"))))
12120 (defun org-previous-link ()
12121 "Move backward to the previous link.
12122 If the link is in hidden text, expose it."
12123 (interactive)
12124 (when (and org-link-search-failed (eq this-command last-command))
12125 (goto-char (point-max))
12126 (message "Link search wrapped back to end of buffer"))
12127 (setq org-link-search-failed nil)
12128 (let* ((pos (point))
12129 (ct (org-context))
12130 (a (assoc :link ct)))
12131 (if a (goto-char (nth 1 a)))
12132 (if (re-search-backward org-any-link-re nil t)
12133 (progn
12134 (goto-char (match-beginning 0))
12135 (if (org-invisible-p) (org-show-context)))
12136 (goto-char pos)
12137 (setq org-link-search-failed t)
12138 (error "No further link found"))))
12140 (defun org-find-file-at-mouse (ev)
12141 "Open file link or URL at mouse."
12142 (interactive "e")
12143 (mouse-set-point ev)
12144 (org-open-at-point 'in-emacs))
12146 (defun org-open-at-mouse (ev)
12147 "Open file link or URL at mouse."
12148 (interactive "e")
12149 (mouse-set-point ev)
12150 (org-open-at-point))
12152 (defvar org-window-config-before-follow-link nil
12153 "The window configuration before following a link.
12154 This is saved in case the need arises to restore it.")
12156 (defvar org-open-link-marker (make-marker)
12157 "Marker pointing to the location where `org-open-at-point; was called.")
12159 ;;;###autoload
12160 (defun org-open-at-point-global ()
12161 "Follow a link like Org-mode does.
12162 This command can be called in any mode to follow a link that has
12163 Org-mode syntax."
12164 (interactive)
12165 (org-run-like-in-org-mode 'org-open-at-point))
12167 (defun org-open-at-point (&optional in-emacs)
12168 "Open link at or after point.
12169 If there is no link at point, this function will search forward up to
12170 the end of the current subtree.
12171 Normally, files will be opened by an appropriate application. If the
12172 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12173 (interactive "P")
12174 (catch 'abort
12175 (move-marker org-open-link-marker (point))
12176 (setq org-window-config-before-follow-link (current-window-configuration))
12177 (org-remove-occur-highlights nil nil t)
12178 (if (org-at-timestamp-p t)
12179 (org-follow-timestamp-link)
12180 (let (type path link line search (pos (point)))
12181 (catch 'match
12182 (save-excursion
12183 (skip-chars-forward "^]\n\r")
12184 (when (org-in-regexp org-bracket-link-regexp)
12185 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12186 (while (string-match " *\n *" link)
12187 (setq link (replace-match " " t t link)))
12188 (setq link (org-link-expand-abbrev link))
12189 (if (string-match org-link-re-with-space2 link)
12190 (setq type (match-string 1 link) path (match-string 2 link))
12191 (setq type "thisfile" path link))
12192 (throw 'match t)))
12194 (when (get-text-property (point) 'org-linked-text)
12195 (setq type "thisfile"
12196 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12197 (1+ (point)) (point))
12198 path (buffer-substring
12199 (previous-single-property-change pos 'org-linked-text)
12200 (next-single-property-change pos 'org-linked-text)))
12201 (throw 'match t))
12203 (save-excursion
12204 (when (or (org-in-regexp org-angle-link-re)
12205 (org-in-regexp org-plain-link-re))
12206 (setq type (match-string 1) path (match-string 2))
12207 (throw 'match t)))
12208 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12209 (setq type "tree-match"
12210 path (match-string 1))
12211 (throw 'match t))
12212 (save-excursion
12213 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12214 (setq type "tags"
12215 path (match-string 1))
12216 (while (string-match ":" path)
12217 (setq path (replace-match "+" t t path)))
12218 (throw 'match t))))
12219 (unless path
12220 (error "No link found"))
12221 ;; Remove any trailing spaces in path
12222 (if (string-match " +\\'" path)
12223 (setq path (replace-match "" t t path)))
12225 (cond
12227 ((assoc type org-link-protocols)
12228 (funcall (nth 1 (assoc type org-link-protocols)) path))
12230 ((equal type "mailto")
12231 (let ((cmd (car org-link-mailto-program))
12232 (args (cdr org-link-mailto-program)) args1
12233 (address path) (subject "") a)
12234 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12235 (setq address (match-string 1 path)
12236 subject (org-link-escape (match-string 2 path))))
12237 (while args
12238 (cond
12239 ((not (stringp (car args))) (push (pop args) args1))
12240 (t (setq a (pop args))
12241 (if (string-match "%a" a)
12242 (setq a (replace-match address t t a)))
12243 (if (string-match "%s" a)
12244 (setq a (replace-match subject t t a)))
12245 (push a args1))))
12246 (apply cmd (nreverse args1))))
12248 ((member type '("http" "https" "ftp" "news"))
12249 (browse-url (concat type ":" (org-link-escape
12250 path org-link-escape-chars-browser))))
12252 ((string= type "tags")
12253 (org-tags-view in-emacs path))
12254 ((string= type "thisfile")
12255 (if in-emacs
12256 (switch-to-buffer-other-window
12257 (org-get-buffer-for-internal-link (current-buffer)))
12258 (org-mark-ring-push))
12259 (let ((cmd `(org-link-search
12260 ,path
12261 ,(cond ((equal in-emacs '(4)) 'occur)
12262 ((equal in-emacs '(16)) 'org-occur)
12263 (t nil))
12264 ,pos)))
12265 (condition-case nil (eval cmd)
12266 (error (progn (widen) (eval cmd))))))
12268 ((string= type "tree-match")
12269 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12271 ((string= type "file")
12272 (if (string-match "::\\([0-9]+\\)\\'" path)
12273 (setq line (string-to-number (match-string 1 path))
12274 path (substring path 0 (match-beginning 0)))
12275 (if (string-match "::\\(.+\\)\\'" path)
12276 (setq search (match-string 1 path)
12277 path (substring path 0 (match-beginning 0)))))
12278 (if (string-match "[*?{]" (file-name-nondirectory path))
12279 (dired path)
12280 (org-open-file path in-emacs line search)))
12282 ((string= type "news")
12283 (org-follow-gnus-link path))
12285 ((string= type "bbdb")
12286 (org-follow-bbdb-link path))
12288 ((string= type "info")
12289 (org-follow-info-link path))
12291 ((string= type "gnus")
12292 (let (group article)
12293 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12294 (error "Error in Gnus link"))
12295 (setq group (match-string 1 path)
12296 article (match-string 3 path))
12297 (org-follow-gnus-link group article)))
12299 ((string= type "vm")
12300 (let (folder article)
12301 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12302 (error "Error in VM link"))
12303 (setq folder (match-string 1 path)
12304 article (match-string 3 path))
12305 ;; in-emacs is the prefix arg, will be interpreted as read-only
12306 (org-follow-vm-link folder article in-emacs)))
12308 ((string= type "wl")
12309 (let (folder article)
12310 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12311 (error "Error in Wanderlust link"))
12312 (setq folder (match-string 1 path)
12313 article (match-string 3 path))
12314 (org-follow-wl-link folder article)))
12316 ((string= type "mhe")
12317 (let (folder article)
12318 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12319 (error "Error in MHE link"))
12320 (setq folder (match-string 1 path)
12321 article (match-string 3 path))
12322 (org-follow-mhe-link folder article)))
12324 ((string= type "rmail")
12325 (let (folder article)
12326 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12327 (error "Error in RMAIL link"))
12328 (setq folder (match-string 1 path)
12329 article (match-string 3 path))
12330 (org-follow-rmail-link folder article)))
12332 ((string= type "shell")
12333 (let ((cmd path))
12334 (if (or (not org-confirm-shell-link-function)
12335 (funcall org-confirm-shell-link-function
12336 (format "Execute \"%s\" in shell? "
12337 (org-add-props cmd nil
12338 'face 'org-warning))))
12339 (progn
12340 (message "Executing %s" cmd)
12341 (shell-command cmd))
12342 (error "Abort"))))
12344 ((string= type "elisp")
12345 (let ((cmd path))
12346 (if (or (not org-confirm-elisp-link-function)
12347 (funcall org-confirm-elisp-link-function
12348 (format "Execute \"%s\" as elisp? "
12349 (org-add-props cmd nil
12350 'face 'org-warning))))
12351 (message "%s => %s" cmd (eval (read cmd)))
12352 (error "Abort"))))
12355 (browse-url-at-point)))))
12356 (move-marker org-open-link-marker nil)))
12358 ;;; File search
12360 (defvar org-create-file-search-functions nil
12361 "List of functions to construct the right search string for a file link.
12362 These functions are called in turn with point at the location to
12363 which the link should point.
12365 A function in the hook should first test if it would like to
12366 handle this file type, for example by checking the major-mode or
12367 the file extension. If it decides not to handle this file, it
12368 should just return nil to give other functions a chance. If it
12369 does handle the file, it must return the search string to be used
12370 when following the link. The search string will be part of the
12371 file link, given after a double colon, and `org-open-at-point'
12372 will automatically search for it. If special measures must be
12373 taken to make the search successful, another function should be
12374 added to the companion hook `org-execute-file-search-functions',
12375 which see.
12377 A function in this hook may also use `setq' to set the variable
12378 `description' to provide a suggestion for the descriptive text to
12379 be used for this link when it gets inserted into an Org-mode
12380 buffer with \\[org-insert-link].")
12382 (defvar org-execute-file-search-functions nil
12383 "List of functions to execute a file search triggered by a link.
12385 Functions added to this hook must accept a single argument, the
12386 search string that was part of the file link, the part after the
12387 double colon. The function must first check if it would like to
12388 handle this search, for example by checking the major-mode or the
12389 file extension. If it decides not to handle this search, it
12390 should just return nil to give other functions a chance. If it
12391 does handle the search, it must return a non-nil value to keep
12392 other functions from trying.
12394 Each function can access the current prefix argument through the
12395 variable `current-prefix-argument'. Note that a single prefix is
12396 used to force opening a link in Emacs, so it may be good to only
12397 use a numeric or double prefix to guide the search function.
12399 In case this is needed, a function in this hook can also restore
12400 the window configuration before `org-open-at-point' was called using:
12402 (set-window-configuration org-window-config-before-follow-link)")
12404 (defun org-link-search (s &optional type avoid-pos)
12405 "Search for a link search option.
12406 If S is surrounded by forward slashes, it is interpreted as a
12407 regular expression. In org-mode files, this will create an `org-occur'
12408 sparse tree. In ordinary files, `occur' will be used to list matches.
12409 If the current buffer is in `dired-mode', grep will be used to search
12410 in all files. If AVOID-POS is given, ignore matches near that position."
12411 (let ((case-fold-search t)
12412 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12413 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12414 (append '(("") (" ") ("\t") ("\n"))
12415 org-emphasis-alist)
12416 "\\|") "\\)"))
12417 (pos (point))
12418 (pre "") (post "")
12419 words re0 re1 re2 re3 re4 re5 re2a reall)
12420 (cond
12421 ;; First check if there are any special
12422 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12423 ;; Now try the builtin stuff
12424 ((save-excursion
12425 (goto-char (point-min))
12426 (and
12427 (re-search-forward
12428 (concat "<<" (regexp-quote s0) ">>") nil t)
12429 (setq pos (match-beginning 0))))
12430 ;; There is an exact target for this
12431 (goto-char pos))
12432 ((string-match "^/\\(.*\\)/$" s)
12433 ;; A regular expression
12434 (cond
12435 ((org-mode-p)
12436 (org-occur (match-string 1 s)))
12437 ;;((eq major-mode 'dired-mode)
12438 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12439 (t (org-do-occur (match-string 1 s)))))
12441 ;; A normal search strings
12442 (when (equal (string-to-char s) ?*)
12443 ;; Anchor on headlines, post may include tags.
12444 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12445 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12446 s (substring s 1)))
12447 (remove-text-properties
12448 0 (length s)
12449 '(face nil mouse-face nil keymap nil fontified nil) s)
12450 ;; Make a series of regular expressions to find a match
12451 (setq words (org-split-string s "[ \n\r\t]+")
12452 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12453 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12454 "\\)" markers)
12455 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12456 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12457 re1 (concat pre re2 post)
12458 re3 (concat pre re4 post)
12459 re5 (concat pre ".*" re4)
12460 re2 (concat pre re2)
12461 re2a (concat pre re2a)
12462 re4 (concat pre re4)
12463 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12464 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12465 re5 "\\)"
12467 (cond
12468 ((eq type 'org-occur) (org-occur reall))
12469 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12470 (t (goto-char (point-min))
12471 (if (or (org-search-not-self 1 re0 nil t)
12472 (org-search-not-self 1 re1 nil t)
12473 (org-search-not-self 1 re2 nil t)
12474 (org-search-not-self 1 re2a nil t)
12475 (org-search-not-self 1 re3 nil t)
12476 (org-search-not-self 1 re4 nil t)
12477 (org-search-not-self 1 re5 nil t)
12479 (goto-char (match-beginning 1))
12480 (goto-char pos)
12481 (error "No match")))))
12483 ;; Normal string-search
12484 (goto-char (point-min))
12485 (if (search-forward s nil t)
12486 (goto-char (match-beginning 0))
12487 (error "No match"))))
12488 (and (org-mode-p) (org-show-context 'link-search))))
12490 (defun org-search-not-self (group &rest args)
12491 "Execute `re-search-forward', but only accept matches that do not
12492 enclose the position of `org-open-link-marker'."
12493 (let ((m org-open-link-marker))
12494 (catch 'exit
12495 (while (apply 're-search-forward args)
12496 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12497 (goto-char (match-end group))
12498 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12499 (> (match-beginning 0) (marker-position m))
12500 (< (match-end 0) (marker-position m)))
12501 (save-match-data
12502 (or (not (org-in-regexp
12503 org-bracket-link-analytic-regexp 1))
12504 (not (match-end 4)) ; no description
12505 (and (<= (match-beginning 4) (point))
12506 (>= (match-end 4) (point))))))
12507 (throw 'exit (point))))))))
12509 (defun org-get-buffer-for-internal-link (buffer)
12510 "Return a buffer to be used for displaying the link target of internal links."
12511 (cond
12512 ((not org-display-internal-link-with-indirect-buffer)
12513 buffer)
12514 ((string-match "(Clone)$" (buffer-name buffer))
12515 (message "Buffer is already a clone, not making another one")
12516 ;; we also do not modify visibility in this case
12517 buffer)
12518 (t ; make a new indirect buffer for displaying the link
12519 (let* ((bn (buffer-name buffer))
12520 (ibn (concat bn "(Clone)"))
12521 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12522 (with-current-buffer ib (org-overview))
12523 ib))))
12525 (defun org-do-occur (regexp &optional cleanup)
12526 "Call the Emacs command `occur'.
12527 If CLEANUP is non-nil, remove the printout of the regular expression
12528 in the *Occur* buffer. This is useful if the regex is long and not useful
12529 to read."
12530 (occur regexp)
12531 (when cleanup
12532 (let ((cwin (selected-window)) win beg end)
12533 (when (setq win (get-buffer-window "*Occur*"))
12534 (select-window win))
12535 (goto-char (point-min))
12536 (when (re-search-forward "match[a-z]+" nil t)
12537 (setq beg (match-end 0))
12538 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12539 (setq end (1- (match-beginning 0)))))
12540 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12541 (goto-char (point-min))
12542 (select-window cwin))))
12544 ;;; The mark ring for links jumps
12546 (defvar org-mark-ring nil
12547 "Mark ring for positions before jumps in Org-mode.")
12548 (defvar org-mark-ring-last-goto nil
12549 "Last position in the mark ring used to go back.")
12550 ;; Fill and close the ring
12551 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12552 (loop for i from 1 to org-mark-ring-length do
12553 (push (make-marker) org-mark-ring))
12554 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12555 org-mark-ring)
12557 (defun org-mark-ring-push (&optional pos buffer)
12558 "Put the current position or POS into the mark ring and rotate it."
12559 (interactive)
12560 (setq pos (or pos (point)))
12561 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12562 (move-marker (car org-mark-ring)
12563 (or pos (point))
12564 (or buffer (current-buffer)))
12565 (message
12566 (substitute-command-keys
12567 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12569 (defun org-mark-ring-goto (&optional n)
12570 "Jump to the previous position in the mark ring.
12571 With prefix arg N, jump back that many stored positions. When
12572 called several times in succession, walk through the entire ring.
12573 Org-mode commands jumping to a different position in the current file,
12574 or to another Org-mode file, automatically push the old position
12575 onto the ring."
12576 (interactive "p")
12577 (let (p m)
12578 (if (eq last-command this-command)
12579 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12580 (setq p org-mark-ring))
12581 (setq org-mark-ring-last-goto p)
12582 (setq m (car p))
12583 (switch-to-buffer (marker-buffer m))
12584 (goto-char m)
12585 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12587 (defun org-remove-angle-brackets (s)
12588 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12589 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12591 (defun org-add-angle-brackets (s)
12592 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12593 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12596 ;;; Following specific links
12598 (defun org-follow-timestamp-link ()
12599 (cond
12600 ((org-at-date-range-p t)
12601 (let ((org-agenda-start-on-weekday)
12602 (t1 (match-string 1))
12603 (t2 (match-string 2)))
12604 (setq t1 (time-to-days (org-time-string-to-time t1))
12605 t2 (time-to-days (org-time-string-to-time t2)))
12606 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12607 ((org-at-timestamp-p t)
12608 (org-agenda-list nil (time-to-days (org-time-string-to-time
12609 (substring (match-string 1) 0 10)))
12611 (t (error "This should not happen"))))
12614 (defun org-follow-bbdb-link (name)
12615 "Follow a BBDB link to NAME."
12616 (require 'bbdb)
12617 (let ((inhibit-redisplay (not debug-on-error))
12618 (bbdb-electric-p nil))
12619 (catch 'exit
12620 ;; Exact match on name
12621 (bbdb-name (concat "\\`" name "\\'") nil)
12622 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12623 ;; Exact match on name
12624 (bbdb-company (concat "\\`" name "\\'") nil)
12625 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12626 ;; Partial match on name
12627 (bbdb-name name nil)
12628 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12629 ;; Partial match on company
12630 (bbdb-company name nil)
12631 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12632 ;; General match including network address and notes
12633 (bbdb name nil)
12634 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12635 (delete-window (get-buffer-window "*BBDB*"))
12636 (error "No matching BBDB record")))))
12638 (defun org-follow-info-link (name)
12639 "Follow an info file & node link to NAME."
12640 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12641 (string-match "\\(.*\\)" name))
12642 (progn
12643 (require 'info)
12644 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12645 (Info-find-node (match-string 1 name) (match-string 2 name))
12646 (Info-find-node (match-string 1 name) "Top")))
12647 (message (concat "Could not open: " name))))
12649 (defun org-follow-gnus-link (&optional group article)
12650 "Follow a Gnus link to GROUP and ARTICLE."
12651 (require 'gnus)
12652 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12653 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12654 (cond ((and group article)
12655 (gnus-group-read-group 1 nil group)
12656 (gnus-summary-goto-article (string-to-number article) nil t))
12657 (group (gnus-group-jump-to-group group))))
12659 (defun org-follow-vm-link (&optional folder article readonly)
12660 "Follow a VM link to FOLDER and ARTICLE."
12661 (require 'vm)
12662 (setq article (org-add-angle-brackets article))
12663 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12664 ;; ange-ftp or efs or tramp access
12665 (let ((user (or (match-string 1 folder) (user-login-name)))
12666 (host (match-string 2 folder))
12667 (file (match-string 3 folder)))
12668 (cond
12669 ((featurep 'tramp)
12670 ;; use tramp to access the file
12671 (if (featurep 'xemacs)
12672 (setq folder (format "[%s@%s]%s" user host file))
12673 (setq folder (format "/%s@%s:%s" user host file))))
12675 ;; use ange-ftp or efs
12676 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12677 (setq folder (format "/%s@%s:%s" user host file))))))
12678 (when folder
12679 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12680 (sit-for 0.1)
12681 (when article
12682 (vm-select-folder-buffer)
12683 (widen)
12684 (let ((case-fold-search t))
12685 (goto-char (point-min))
12686 (if (not (re-search-forward
12687 (concat "^" "message-id: *" (regexp-quote article))))
12688 (error "Could not find the specified message in this folder"))
12689 (vm-isearch-update)
12690 (vm-isearch-narrow)
12691 (vm-beginning-of-message)
12692 (vm-summarize)))))
12694 (defun org-follow-wl-link (folder article)
12695 "Follow a Wanderlust link to FOLDER and ARTICLE."
12696 (if (and (string= folder "%")
12697 article
12698 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12699 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12700 ;; Thus, we recompose folder and article ids.
12701 (setq folder (format "%s#%s" folder (match-string 1 article))
12702 article (match-string 3 article)))
12703 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12704 (error "No such folder: %s" folder))
12705 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12706 (and article
12707 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12708 (wl-summary-redisplay)))
12710 (defun org-follow-rmail-link (folder article)
12711 "Follow an RMAIL link to FOLDER and ARTICLE."
12712 (setq article (org-add-angle-brackets article))
12713 (let (message-number)
12714 (save-excursion
12715 (save-window-excursion
12716 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12717 (setq message-number
12718 (save-restriction
12719 (widen)
12720 (goto-char (point-max))
12721 (if (re-search-backward
12722 (concat "^Message-ID:\\s-+" (regexp-quote
12723 (or article "")))
12724 nil t)
12725 (rmail-what-message))))))
12726 (if message-number
12727 (progn
12728 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12729 (rmail-show-message message-number)
12730 message-number)
12731 (error "Message not found"))))
12733 ;;; mh-e integration based on planner-mode
12734 (defun org-mhe-get-message-real-folder ()
12735 "Return the name of the current message real folder, so if you use
12736 sequences, it will now work."
12737 (save-excursion
12738 (let* ((folder
12739 (if (equal major-mode 'mh-folder-mode)
12740 mh-current-folder
12741 ;; Refer to the show buffer
12742 mh-show-folder-buffer))
12743 (end-index
12744 (if (boundp 'mh-index-folder)
12745 (min (length mh-index-folder) (length folder))))
12747 ;; a simple test on mh-index-data does not work, because
12748 ;; mh-index-data is always nil in a show buffer.
12749 (if (and (boundp 'mh-index-folder)
12750 (string= mh-index-folder (substring folder 0 end-index)))
12751 (if (equal major-mode 'mh-show-mode)
12752 (save-window-excursion
12753 (let (pop-up-frames)
12754 (when (buffer-live-p (get-buffer folder))
12755 (progn
12756 (pop-to-buffer folder)
12757 (org-mhe-get-message-folder-from-index)
12760 (org-mhe-get-message-folder-from-index)
12762 folder
12766 (defun org-mhe-get-message-folder-from-index ()
12767 "Returns the name of the message folder in a index folder buffer."
12768 (save-excursion
12769 (mh-index-previous-folder)
12770 (re-search-forward "^\\(+.*\\)$" nil t)
12771 (message (match-string 1))))
12773 (defun org-mhe-get-message-folder ()
12774 "Return the name of the current message folder. Be careful if you
12775 use sequences."
12776 (save-excursion
12777 (if (equal major-mode 'mh-folder-mode)
12778 mh-current-folder
12779 ;; Refer to the show buffer
12780 mh-show-folder-buffer)))
12782 (defun org-mhe-get-message-num ()
12783 "Return the number of the current message. Be careful if you
12784 use sequences."
12785 (save-excursion
12786 (if (equal major-mode 'mh-folder-mode)
12787 (mh-get-msg-num nil)
12788 ;; Refer to the show buffer
12789 (mh-show-buffer-message-number))))
12791 (defun org-mhe-get-header (header)
12792 "Return a header of the message in folder mode. This will create a
12793 show buffer for the corresponding message. If you have a more clever
12794 idea..."
12795 (let* ((folder (org-mhe-get-message-folder))
12796 (num (org-mhe-get-message-num))
12797 (buffer (get-buffer-create (concat "show-" folder)))
12798 (header-field))
12799 (with-current-buffer buffer
12800 (mh-display-msg num folder)
12801 (if (equal major-mode 'mh-folder-mode)
12802 (mh-header-display)
12803 (mh-show-header-display))
12804 (set-buffer buffer)
12805 (setq header-field (mh-get-header-field header))
12806 (if (equal major-mode 'mh-folder-mode)
12807 (mh-show)
12808 (mh-show-show))
12809 header-field)))
12811 (defun org-follow-mhe-link (folder article)
12812 "Follow an MHE link to FOLDER and ARTICLE.
12813 If ARTICLE is nil FOLDER is shown. If the configuration variable
12814 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12815 ARTICLE is searched in all folders. Indexed searches (swish++,
12816 namazu, and others supported by MH-E) will always search in all
12817 folders."
12818 (require 'mh-e)
12819 (require 'mh-search)
12820 (require 'mh-utils)
12821 (mh-find-path)
12822 (if (not article)
12823 (mh-visit-folder (mh-normalize-folder-name folder))
12824 (setq article (org-add-angle-brackets article))
12825 (mh-search-choose)
12826 (if (equal mh-searcher 'pick)
12827 (progn
12828 (mh-search folder (list "--message-id" article))
12829 (when (and org-mhe-search-all-folders
12830 (not (org-mhe-get-message-real-folder)))
12831 (kill-this-buffer)
12832 (mh-search "+" (list "--message-id" article))))
12833 (mh-search "+" article))
12834 (if (org-mhe-get-message-real-folder)
12835 (mh-show-msg 1)
12836 (kill-this-buffer)
12837 (error "Message not found"))))
12839 ;;; BibTeX links
12841 ;; Use the custom search meachnism to construct and use search strings for
12842 ;; file links to BibTeX database entries.
12844 (defun org-create-file-search-in-bibtex ()
12845 "Create the search string and description for a BibTeX database entry."
12846 (when (eq major-mode 'bibtex-mode)
12847 ;; yes, we want to construct this search string.
12848 ;; Make a good description for this entry, using names, year and the title
12849 ;; Put it into the `description' variable which is dynamically scoped.
12850 (let ((bibtex-autokey-names 1)
12851 (bibtex-autokey-names-stretch 1)
12852 (bibtex-autokey-name-case-convert-function 'identity)
12853 (bibtex-autokey-name-separator " & ")
12854 (bibtex-autokey-additional-names " et al.")
12855 (bibtex-autokey-year-length 4)
12856 (bibtex-autokey-name-year-separator " ")
12857 (bibtex-autokey-titlewords 3)
12858 (bibtex-autokey-titleword-separator " ")
12859 (bibtex-autokey-titleword-case-convert-function 'identity)
12860 (bibtex-autokey-titleword-length 'infty)
12861 (bibtex-autokey-year-title-separator ": "))
12862 (setq description (bibtex-generate-autokey)))
12863 ;; Now parse the entry, get the key and return it.
12864 (save-excursion
12865 (bibtex-beginning-of-entry)
12866 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12868 (defun org-execute-file-search-in-bibtex (s)
12869 "Find the link search string S as a key for a database entry."
12870 (when (eq major-mode 'bibtex-mode)
12871 ;; Yes, we want to do the search in this file.
12872 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12873 (goto-char (point-min))
12874 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12875 (regexp-quote s) "[ \t\n]*,") nil t)
12876 (goto-char (match-beginning 0)))
12877 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12878 ;; Use double prefix to indicate that any web link should be browsed
12879 (let ((b (current-buffer)) (p (point)))
12880 ;; Restore the window configuration because we just use the web link
12881 (set-window-configuration org-window-config-before-follow-link)
12882 (save-excursion (set-buffer b) (goto-char p)
12883 (bibtex-url)))
12884 (recenter 0)) ; Move entry start to beginning of window
12885 ;; return t to indicate that the search is done.
12888 ;; Finally add the functions to the right hooks.
12889 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12890 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12892 ;; end of Bibtex link setup
12894 ;;; Following file links
12896 (defun org-open-file (path &optional in-emacs line search)
12897 "Open the file at PATH.
12898 First, this expands any special file name abbreviations. Then the
12899 configuration variable `org-file-apps' is checked if it contains an
12900 entry for this file type, and if yes, the corresponding command is launched.
12901 If no application is found, Emacs simply visits the file.
12902 With optional argument IN-EMACS, Emacs will visit the file.
12903 Optional LINE specifies a line to go to, optional SEARCH a string to
12904 search for. If LINE or SEARCH is given, the file will always be
12905 opened in Emacs.
12906 If the file does not exist, an error is thrown."
12907 (setq in-emacs (or in-emacs line search))
12908 (let* ((file (if (equal path "")
12909 buffer-file-name
12910 (substitute-in-file-name (expand-file-name path))))
12911 (apps (append org-file-apps (org-default-apps)))
12912 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12913 (dirp (if remp nil (file-directory-p file)))
12914 (dfile (downcase file))
12915 (old-buffer (current-buffer))
12916 (old-pos (point))
12917 (old-mode major-mode)
12918 ext cmd)
12919 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12920 (setq ext (match-string 1 dfile))
12921 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12922 (setq ext (match-string 1 dfile))))
12923 (if in-emacs
12924 (setq cmd 'emacs)
12925 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12926 (and dirp (cdr (assoc 'directory apps)))
12927 (cdr (assoc ext apps))
12928 (cdr (assoc t apps)))))
12929 (when (eq cmd 'mailcap)
12930 (require 'mailcap)
12931 (mailcap-parse-mailcaps)
12932 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12933 (command (mailcap-mime-info mime-type)))
12934 (if (stringp command)
12935 (setq cmd command)
12936 (setq cmd 'emacs))))
12937 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12938 (not (file-exists-p file))
12939 (not org-open-non-existing-files))
12940 (error "No such file: %s" file))
12941 (cond
12942 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12943 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12944 (if (string-match "['\"]%s['\"]" cmd)
12945 (setq cmd (replace-match "%s" t t cmd)))
12946 (setq cmd (format cmd (shell-quote-argument file)))
12947 (save-window-excursion
12948 (start-process-shell-command cmd nil cmd)))
12949 ((or (stringp cmd)
12950 (eq cmd 'emacs))
12951 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12952 (widen)
12953 (if line (goto-line line)
12954 (if search (org-link-search search))))
12955 ((consp cmd)
12956 (eval cmd))
12957 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12958 (and (org-mode-p) (eq old-mode 'org-mode)
12959 (or (not (equal old-buffer (current-buffer)))
12960 (not (equal old-pos (point))))
12961 (org-mark-ring-push old-pos old-buffer))))
12963 (defun org-default-apps ()
12964 "Return the default applications for this operating system."
12965 (cond
12966 ((eq system-type 'darwin)
12967 org-file-apps-defaults-macosx)
12968 ((eq system-type 'windows-nt)
12969 org-file-apps-defaults-windowsnt)
12970 (t org-file-apps-defaults-gnu)))
12972 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12973 (defun org-file-remote-p (file)
12974 "Test whether FILE specifies a location on a remote system.
12975 Return non-nil if the location is indeed remote.
12977 For example, the filename \"/user@host:/foo\" specifies a location
12978 on the system \"/user@host:\"."
12979 (cond ((fboundp 'file-remote-p)
12980 (file-remote-p file))
12981 ((fboundp 'tramp-handle-file-remote-p)
12982 (tramp-handle-file-remote-p file))
12983 ((and (boundp 'ange-ftp-name-format)
12984 (string-match (car ange-ftp-name-format) file))
12986 (t nil)))
12989 ;;;; Hooks for remember.el, and refiling
12991 ;;;###autoload
12992 (defun org-remember-insinuate ()
12993 "Setup remember.el for use wiht Org-mode."
12994 (require 'remember)
12995 (setq remember-annotation-functions '(org-remember-annotation))
12996 (setq remember-handler-functions '(org-remember-handler))
12997 (add-hook 'remember-mode-hook 'org-remember-apply-template))
12999 ;;;###autoload
13000 (defun org-remember-annotation ()
13001 "Return a link to the current location as an annotation for remember.el.
13002 If you are using Org-mode files as target for data storage with
13003 remember.el, then the annotations should include a link compatible with the
13004 conventions in Org-mode. This function returns such a link."
13005 (org-store-link nil))
13007 (defconst org-remember-help
13008 "Select a destination location for the note.
13009 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13010 RET on headline -> Store as sublevel entry to current headline
13011 RET at beg-of-buf -> Append to file as level 2 headline
13012 <left>/<right> -> before/after current headline, same headings level")
13014 (defvar org-remember-previous-location nil)
13015 (defvar org-force-remember-template-char) ;; dynamically scoped
13017 (defun org-select-remember-template (&optional use-char)
13018 (when org-remember-templates
13019 (let* ((templates (mapcar (lambda (x)
13020 (if (stringp (car x))
13021 (append (list (nth 1 x) (car x)) (cddr x))
13022 (append (list (car x) "") (cdr x))))
13023 org-remember-templates))
13024 (char (or use-char
13025 (cond
13026 ((= (length templates) 1)
13027 (caar templates))
13028 ((and (boundp 'org-force-remember-template-char)
13029 org-force-remember-template-char)
13030 (if (stringp org-force-remember-template-char)
13031 (string-to-char org-force-remember-template-char)
13032 org-force-remember-template-char))
13034 (message "Select template: %s"
13035 (mapconcat
13036 (lambda (x)
13037 (cond
13038 ((not (string-match "\\S-" (nth 1 x)))
13039 (format "[%c]" (car x)))
13040 ((equal (downcase (car x))
13041 (downcase (aref (nth 1 x) 0)))
13042 (format "[%c]%s" (car x)
13043 (substring (nth 1 x) 1)))
13044 (t (format "[%c]%s" (car x) (nth 1 x)))))
13045 templates " "))
13046 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13047 (when (equal char0 ?\C-g)
13048 (jump-to-register remember-register)
13049 (kill-buffer remember-buffer))
13050 char0))))))
13051 (cddr (assoc char templates)))))
13053 (defvar x-last-selected-text)
13054 (defvar x-last-selected-text-primary)
13056 ;;;###autoload
13057 (defun org-remember-apply-template (&optional use-char skip-interactive)
13058 "Initialize *remember* buffer with template, invoke `org-mode'.
13059 This function should be placed into `remember-mode-hook' and in fact requires
13060 to be run from that hook to function properly."
13061 (unless (fboundp 'remember-finalize)
13062 (defalias 'remember-finalize 'remember-buffer))
13063 (if org-remember-templates
13064 (let* ((entry (org-select-remember-template use-char))
13065 (tpl (car entry))
13066 (plist-p (if org-store-link-plist t nil))
13067 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13068 (string-match "\\S-" (nth 1 entry)))
13069 (nth 1 entry)
13070 org-default-notes-file))
13071 (headline (nth 2 entry))
13072 (v-c (if (or (and (eq window-system 'x)
13073 (x-cut-buffer-or-selection-value))
13074 (bound-and-true-p 'x-last-selected-text)
13075 (bound-and-true-p 'x-last-selected-text-primary))
13076 x-last-selected-text-primary
13077 (if (> (length kill-ring) 0)
13078 (current-kill 0)
13079 nil)))
13080 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13081 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13082 (v-u (concat "[" (substring v-t 1 -1) "]"))
13083 (v-U (concat "[" (substring v-T 1 -1) "]"))
13084 ;; `initial' and `annotation' are bound in `remember'
13085 (v-i (if (boundp 'initial) initial))
13086 (v-a (if (and (boundp 'annotation) annotation)
13087 (if (equal annotation "[[]]") "" annotation)
13088 ""))
13089 (v-A (if (and v-a
13090 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13091 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13092 v-a))
13093 (v-n user-full-name)
13094 (org-startup-folded nil)
13095 org-time-was-given org-end-time-was-given x prompt char time pos)
13096 (setq org-store-link-plist
13097 (append (list :annotation v-a :initial v-i)
13098 org-store-link-plist))
13099 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13100 (erase-buffer)
13101 (insert (substitute-command-keys
13102 (format
13103 "## Filing location: Select interactively, default, or last used:
13104 ## %s to select file and header location interactively.
13105 ## %s \"%s\" -> \"* %s\"
13106 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13107 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13108 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13109 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13110 (abbreviate-file-name (or file org-default-notes-file))
13111 (or headline "")
13112 (or (car org-remember-previous-location) "???")
13113 (or (cdr org-remember-previous-location) "???"))))
13114 (insert tpl) (goto-char (point-min))
13115 ;; Simple %-escapes
13116 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13117 (when (and initial (equal (match-string 0) "%i"))
13118 (save-match-data
13119 (let* ((lead (buffer-substring
13120 (point-at-bol) (match-beginning 0))))
13121 (setq v-i (mapconcat 'identity
13122 (org-split-string initial "\n")
13123 (concat "\n" lead))))))
13124 (replace-match
13125 (or (eval (intern (concat "v-" (match-string 1)))) "")
13126 t t))
13128 ;; %[] Insert contents of a file.
13129 (goto-char (point-min))
13130 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13131 (let ((start (match-beginning 0))
13132 (end (match-end 0))
13133 (filename (expand-file-name (match-string 1))))
13134 (goto-char start)
13135 (delete-region start end)
13136 (condition-case error
13137 (insert-file-contents filename)
13138 (error (insert (format "%%![Couldn't insert %s: %s]"
13139 filename error))))))
13140 ;; %() embedded elisp
13141 (goto-char (point-min))
13142 (while (re-search-forward "%\\((.+)\\)" nil t)
13143 (goto-char (match-beginning 0))
13144 (let ((template-start (point)))
13145 (forward-char 1)
13146 (let ((result
13147 (condition-case error
13148 (eval (read (current-buffer)))
13149 (error (format "%%![Error: %s]" error)))))
13150 (delete-region template-start (point))
13151 (insert result))))
13153 ;; From the property list
13154 (when plist-p
13155 (goto-char (point-min))
13156 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13157 (and (setq x (or (plist-get org-store-link-plist
13158 (intern (match-string 1))) ""))
13159 (replace-match x t t))))
13161 ;; Turn on org-mode in the remember buffer, set local variables
13162 (org-mode)
13163 (org-set-local 'org-finish-function 'remember-finalize)
13164 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13165 (org-set-local 'org-default-notes-file file))
13166 (if (and headline (stringp headline) (string-match "\\S-" headline))
13167 (org-set-local 'org-remember-default-headline headline))
13168 ;; Interactive template entries
13169 (goto-char (point-min))
13170 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13171 (setq char (if (match-end 3) (match-string 3))
13172 prompt (if (match-end 2) (match-string 2)))
13173 (goto-char (match-beginning 0))
13174 (replace-match "")
13175 (cond
13176 ((member char '("G" "g"))
13177 (let* ((org-last-tags-completion-table
13178 (org-global-tags-completion-table
13179 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13180 (org-add-colon-after-tag-completion t)
13181 (ins (completing-read
13182 (if prompt (concat prompt ": ") "Tags: ")
13183 'org-tags-completion-function nil nil nil
13184 'org-tags-history)))
13185 (setq ins (mapconcat 'identity
13186 (org-split-string ins (org-re "[^[:alnum:]]+"))
13187 ":"))
13188 (when (string-match "\\S-" ins)
13189 (or (equal (char-before) ?:) (insert ":"))
13190 (insert ins)
13191 (or (equal (char-after) ?:) (insert ":")))))
13192 (char
13193 (setq org-time-was-given (equal (upcase char) char))
13194 (setq time (org-read-date (equal (upcase char) "U") t nil
13195 prompt))
13196 (org-insert-time-stamp time org-time-was-given
13197 (member char '("u" "U"))
13198 nil nil (list org-end-time-was-given)))
13200 (insert (read-string
13201 (if prompt (concat prompt ": ") "Enter string"))))))
13202 (goto-char (point-min))
13203 (if (re-search-forward "%\\?" nil t)
13204 (replace-match "")
13205 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13206 (org-mode)
13207 (org-set-local 'org-finish-function 'remember-finalize)))
13209 ;;;###autoload
13210 (defun org-remember (&optional goto org-force-remember-template-char)
13211 "Call `remember'. If this is already a remember buffer, re-apply template.
13212 If there is an active region, make sure remember uses it as initial content
13213 of the remember buffer.
13215 When called interactively with a `C-u' prefix argument GOTO, don't remember
13216 anything, just go to the file/headline where the selected templated usually
13217 stores its notes.
13219 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13220 associated with a template in `org-remember-tempates'."
13221 (interactive "P")
13222 (if (equal goto '(4))
13223 (org-go-to-remember-target)
13224 (if (eq org-finish-function 'remember-buffer)
13225 (progn
13226 (when (< (length org-remember-templates) 2)
13227 (error "No other template available"))
13228 (erase-buffer)
13229 (let ((annotation (plist-get org-store-link-plist :annotation))
13230 (initial (plist-get org-store-link-plist :initial)))
13231 (org-remember-apply-template))
13232 (message "Press C-c C-c to remember data"))
13233 (if (org-region-active-p)
13234 (remember (buffer-substring (point) (mark)))
13235 (call-interactively 'remember)))))
13237 (defun org-go-to-remember-target (&optional template-key)
13238 "Go to the target location of a remember template.
13239 The user is queried for the template."
13240 (interactive)
13241 (let* ((entry (org-select-remember-template template-key))
13242 (file (nth 1 entry))
13243 (heading (nth 2 entry))
13244 visiting)
13245 (unless (and file (stringp file) (string-match "\\S-" file))
13246 (setq file org-default-notes-file))
13247 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13248 (setq heading org-remember-default-headline))
13249 (setq visiting (org-find-base-buffer-visiting file))
13250 (if (not visiting) (find-file-noselect file))
13251 (switch-to-buffer (or visiting (get-file-buffer file)))
13252 (widen)
13253 (goto-char (point-min))
13254 (if (re-search-forward
13255 (concat "^\\*+[ \t]+" (regexp-quote heading)
13256 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13257 nil t)
13258 (goto-char (match-beginning 0))
13259 (error "Target headline not found: %s" heading))))
13261 (defvar org-note-abort nil) ; dynamically scoped
13263 ;;;###autoload
13264 (defun org-remember-handler ()
13265 "Store stuff from remember.el into an org file.
13266 First prompts for an org file. If the user just presses return, the value
13267 of `org-default-notes-file' is used.
13268 Then the command offers the headings tree of the selected file in order to
13269 file the text at a specific location.
13270 You can either immediately press RET to get the note appended to the
13271 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13272 find a better place. Then press RET or <left> or <right> in insert the note.
13274 Key Cursor position Note gets inserted
13275 -----------------------------------------------------------------------------
13276 RET buffer-start as level 1 heading at end of file
13277 RET on headline as sublevel of the heading at cursor
13278 RET no heading at cursor position, level taken from context.
13279 Or use prefix arg to specify level manually.
13280 <left> on headline as same level, before current heading
13281 <right> on headline as same level, after current heading
13283 So the fastest way to store the note is to press RET RET to append it to
13284 the default file. This way your current train of thought is not
13285 interrupted, in accordance with the principles of remember.el.
13286 You can also get the fast execution without prompting by using
13287 C-u C-c C-c to exit the remember buffer. See also the variable
13288 `org-remember-store-without-prompt'.
13290 Before being stored away, the function ensures that the text has a
13291 headline, i.e. a first line that starts with a \"*\". If not, a headline
13292 is constructed from the current date and some additional data.
13294 If the variable `org-adapt-indentation' is non-nil, the entire text is
13295 also indented so that it starts in the same column as the headline
13296 \(i.e. after the stars).
13298 See also the variable `org-reverse-note-order'."
13299 (goto-char (point-min))
13300 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13301 (replace-match ""))
13302 (goto-char (point-max))
13303 (catch 'quit
13304 (if org-note-abort (throw 'quit nil))
13305 (let* ((txt (buffer-substring (point-min) (point-max)))
13306 (fastp (org-xor (equal current-prefix-arg '(4))
13307 org-remember-store-without-prompt))
13308 (file (if fastp org-default-notes-file (org-get-org-file)))
13309 (heading org-remember-default-headline)
13310 (visiting (org-find-base-buffer-visiting file))
13311 (org-startup-folded nil)
13312 (org-startup-align-all-tables nil)
13313 (org-goto-start-pos 1)
13314 spos exitcmd level indent reversed)
13315 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13316 (setq file (car org-remember-previous-location)
13317 heading (cdr org-remember-previous-location)))
13318 (setq current-prefix-arg nil)
13319 ;; Modify text so that it becomes a nice subtree which can be inserted
13320 ;; into an org tree.
13321 (let* ((lines (split-string txt "\n"))
13322 first)
13323 (setq first (car lines) lines (cdr lines))
13324 (if (string-match "^\\*+ " first)
13325 ;; Is already a headline
13326 (setq indent nil)
13327 ;; We need to add a headline: Use time and first buffer line
13328 (setq lines (cons first lines)
13329 first (concat "* " (current-time-string)
13330 " (" (remember-buffer-desc) ")")
13331 indent " "))
13332 (if (and org-adapt-indentation indent)
13333 (setq lines (mapcar
13334 (lambda (x)
13335 (if (string-match "\\S-" x)
13336 (concat indent x) x))
13337 lines)))
13338 (setq txt (concat first "\n"
13339 (mapconcat 'identity lines "\n"))))
13340 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13341 (setq txt (replace-match "\n\n" t t txt))
13342 (if (string-match "[ \t\n]*\\'" txt)
13343 (setq txt (replace-match "\n" t t txt))))
13344 ;; Find the file
13345 (if (not visiting) (find-file-noselect file))
13346 (with-current-buffer (or visiting (get-file-buffer file))
13347 (unless (org-mode-p)
13348 (error "Target files for remember notes must be in Org-mode"))
13349 (save-excursion
13350 (save-restriction
13351 (widen)
13352 (and (goto-char (point-min))
13353 (not (re-search-forward "^\\* " nil t))
13354 (insert "\n* " (or heading "Notes") "\n"))
13355 (setq reversed (org-notes-order-reversed-p))
13357 ;; Find the default location
13358 (when (and heading (stringp heading) (string-match "\\S-" heading))
13359 (goto-char (point-min))
13360 (if (re-search-forward
13361 (concat "^\\*+[ \t]+" (regexp-quote heading)
13362 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13363 nil t)
13364 (setq org-goto-start-pos (match-beginning 0))
13365 (when fastp
13366 (goto-char (point-max))
13367 (unless (bolp) (newline))
13368 (insert "* " heading "\n")
13369 (setq org-goto-start-pos (point-at-bol 0)))))
13371 ;; Ask the User for a location
13372 (if fastp
13373 (setq spos org-goto-start-pos
13374 exitcmd 'return)
13375 (setq spos (org-get-location (current-buffer) org-remember-help)
13376 exitcmd (cdr spos)
13377 spos (car spos)))
13378 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13379 ; not handle this note
13380 (goto-char spos)
13381 (cond ((org-on-heading-p t)
13382 (org-back-to-heading t)
13383 (setq level (funcall outline-level))
13384 (cond
13385 ((eq exitcmd 'return)
13386 ;; sublevel of current
13387 (setq org-remember-previous-location
13388 (cons (abbreviate-file-name file)
13389 (org-get-heading 'notags)))
13390 (if reversed
13391 (outline-next-heading)
13392 (org-end-of-subtree)
13393 (if (not (bolp))
13394 (if (looking-at "[ \t]*\n")
13395 (beginning-of-line 2)
13396 (end-of-line 1)
13397 (insert "\n"))))
13398 (org-paste-subtree (org-get-legal-level level 1) txt))
13399 ((eq exitcmd 'left)
13400 ;; before current
13401 (org-paste-subtree level txt))
13402 ((eq exitcmd 'right)
13403 ;; after current
13404 (org-end-of-subtree t)
13405 (org-paste-subtree level txt))
13406 (t (error "This should not happen"))))
13408 ((and (bobp) (not reversed))
13409 ;; Put it at the end, one level below level 1
13410 (save-restriction
13411 (widen)
13412 (goto-char (point-max))
13413 (if (not (bolp)) (newline))
13414 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13416 ((and (bobp) reversed)
13417 ;; Put it at the start, as level 1
13418 (save-restriction
13419 (widen)
13420 (goto-char (point-min))
13421 (re-search-forward "^\\*+ " nil t)
13422 (beginning-of-line 1)
13423 (org-paste-subtree 1 txt)))
13425 ;; Put it right there, with automatic level determined by
13426 ;; org-paste-subtree or from prefix arg
13427 (org-paste-subtree
13428 (if (numberp current-prefix-arg) current-prefix-arg)
13429 txt)))
13430 (when remember-save-after-remembering
13431 (save-buffer)
13432 (if (not visiting) (kill-buffer (current-buffer)))))))))
13433 t) ;; return t to indicate that we took care of this note.
13435 (defun org-get-org-file ()
13436 "Read a filename, with default directory `org-directory'."
13437 (let ((default (or org-default-notes-file remember-data-file)))
13438 (read-file-name (format "File name [%s]: " default)
13439 (file-name-as-directory org-directory)
13440 default)))
13442 (defun org-notes-order-reversed-p ()
13443 "Check if the current file should receive notes in reversed order."
13444 (cond
13445 ((not org-reverse-note-order) nil)
13446 ((eq t org-reverse-note-order) t)
13447 ((not (listp org-reverse-note-order)) nil)
13448 (t (catch 'exit
13449 (let ((all org-reverse-note-order)
13450 entry)
13451 (while (setq entry (pop all))
13452 (if (string-match (car entry) buffer-file-name)
13453 (throw 'exit (cdr entry))))
13454 nil)))))
13456 ;;; Refiling
13458 (defvar org-refile-target-table nil
13459 "The list of refile targets, created by `org-refile'.")
13461 (defvar org-agenda-new-buffers nil
13462 "Buffers created to visit agenda files.")
13464 (defun org-get-refile-targets ()
13465 "Produce a table with refile targets."
13466 (let ((entries org-refile-targets)
13467 org-agenda-new-files targets txt re files f desc descre)
13468 (while (setq entry (pop entries))
13469 (setq files (car entry) desc (cdr entry))
13470 (cond
13471 ((null files) (setq files (list (current-buffer))))
13472 ((eq files 'org-agenda-files)
13473 (setq files (org-agenda-files 'unrestricted)))
13474 ((and (symbolp files) (fboundp files))
13475 (setq files (funcall files)))
13476 ((and (symbolp files) (boundp files))
13477 (setq files (symbol-value files))))
13478 (if (stringp files) (setq files (list files)))
13479 (cond
13480 ((eq (car desc) :tag)
13481 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13482 ((eq (car desc) :todo)
13483 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13484 ((eq (car desc) :regexp)
13485 (setq descre (cdr desc)))
13486 ((eq (car desc) :level)
13487 (setq descre (concat "^\\*\\{" (number-to-string
13488 (if org-odd-levels-only
13489 (1- (* 2 (cdr desc)))
13490 (cdr desc)))
13491 "\\}[ \t]")))
13492 (t (error "Bad refiling target description %s" desc)))
13493 (while (setq f (pop files))
13494 (save-excursion
13495 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13496 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13497 (save-excursion
13498 (save-restriction
13499 (widen)
13500 (goto-char (point-min))
13501 (while (re-search-forward descre nil t)
13502 (goto-char (point-at-bol))
13503 (when (looking-at org-complex-heading-regexp)
13504 (setq txt (match-string 4)
13505 re (concat "^" (regexp-quote
13506 (buffer-substring (match-beginning 1)
13507 (match-end 4)))))
13508 (if (match-end 5) (setq re (concat re "[ \t]+"
13509 (regexp-quote
13510 (match-string 5)))))
13511 (setq re (concat re "[ \t]*$"))
13512 (push (list txt f re (point)) targets))
13513 (goto-char (point-at-eol))))))))
13514 (org-release-buffers org-agenda-new-buffers)
13515 (nreverse targets)))
13517 (defun org-refile (&optional reversed-or-update)
13518 "Move the entry at point to another heading.
13519 The list of target headings is compiled using the information in
13520 `org-refile-targets', which see. This list is created upon first use, and
13521 you can update it by calling this command with a double prefix (`C-u C-u').
13523 At the target location, the entry is filed as a subitem of the target heading.
13524 Depending on `org-reverse-note-order', the new subitem will either be the
13525 first of the last subitem. A single C-u prefix will toggle the value of this
13526 variable for the duration of the command."
13527 (interactive "P")
13528 (if (equal reversed-or-update '(16))
13529 (progn
13530 (setq org-refile-target-table (org-get-refile-targets))
13531 (message "Refile targets updated (%d targets)"
13532 (length org-refile-target-table)))
13533 (when (or (not org-refile-target-table)
13534 (and (= (length org-refile-targets) 1)
13535 (not (caar org-refile-targets))))
13536 (setq org-refile-target-table (org-get-refile-targets)))
13537 (unless org-refile-target-table
13538 (error "No refile targets"))
13539 (let* ((cbuf (current-buffer))
13540 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13541 (fname (and filename (file-truename filename)))
13542 (tbl (mapcar
13543 (lambda (x)
13544 (if (not (equal fname (file-truename (nth 1 x))))
13545 (cons (concat (car x) " (" (file-name-nondirectory
13546 (nth 1 x)) ")")
13547 (cdr x))
13549 org-refile-target-table))
13550 (completion-ignore-case t)
13551 pos it nbuf file re level reversed)
13552 (when (setq it (completing-read "Refile to: " tbl
13553 nil t nil 'org-refile-history))
13554 (setq it (assoc it tbl)
13555 file (nth 1 it)
13556 re (nth 2 it))
13557 (org-copy-special)
13558 (save-excursion
13559 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13560 (find-file-noselect file))))
13561 (setq reversed (org-notes-order-reversed-p))
13562 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13563 (save-excursion
13564 (save-restriction
13565 (widen)
13566 (goto-char (point-min))
13567 (unless (re-search-forward re nil t)
13568 (error "Cannot find target location - try again with `C-u' prefix."))
13569 (goto-char (match-beginning 0))
13570 (looking-at outline-regexp)
13571 (setq level (org-get-legal-level (funcall outline-level) 1))
13572 (goto-char (or (save-excursion
13573 (if reversed
13574 (outline-next-heading)
13575 (outline-get-next-sibling)))
13576 (point-max)))
13577 (org-paste-subtree level))))
13578 (org-cut-special)
13579 (message "Entry refiled to \"%s\"" (car it))))))
13581 ;;;; Dynamic blocks
13583 (defun org-find-dblock (name)
13584 "Find the first dynamic block with name NAME in the buffer.
13585 If not found, stay at current position and return nil."
13586 (let (pos)
13587 (save-excursion
13588 (goto-char (point-min))
13589 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13590 nil t)
13591 (match-beginning 0))))
13592 (if pos (goto-char pos))
13593 pos))
13595 (defconst org-dblock-start-re
13596 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13597 "Matches the startline of a dynamic block, with parameters.")
13599 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13600 "Matches the end of a dyhamic block.")
13602 (defun org-create-dblock (plist)
13603 "Create a dynamic block section, with parameters taken from PLIST.
13604 PLIST must containe a :name entry which is used as name of the block."
13605 (unless (bolp) (newline))
13606 (let ((name (plist-get plist :name)))
13607 (insert "#+BEGIN: " name)
13608 (while plist
13609 (if (eq (car plist) :name)
13610 (setq plist (cddr plist))
13611 (insert " " (prin1-to-string (pop plist)))))
13612 (insert "\n\n#+END:\n")
13613 (beginning-of-line -2)))
13615 (defun org-prepare-dblock ()
13616 "Prepare dynamic block for refresh.
13617 This empties the block, puts the cursor at the insert position and returns
13618 the property list including an extra property :name with the block name."
13619 (unless (looking-at org-dblock-start-re)
13620 (error "Not at a dynamic block"))
13621 (let* ((begdel (1+ (match-end 0)))
13622 (name (org-no-properties (match-string 1)))
13623 (params (append (list :name name)
13624 (read (concat "(" (match-string 3) ")")))))
13625 (unless (re-search-forward org-dblock-end-re nil t)
13626 (error "Dynamic block not terminated"))
13627 (delete-region begdel (match-beginning 0))
13628 (goto-char begdel)
13629 (open-line 1)
13630 params))
13632 (defun org-map-dblocks (&optional command)
13633 "Apply COMMAND to all dynamic blocks in the current buffer.
13634 If COMMAND is not given, use `org-update-dblock'."
13635 (let ((cmd (or command 'org-update-dblock))
13636 pos)
13637 (save-excursion
13638 (goto-char (point-min))
13639 (while (re-search-forward org-dblock-start-re nil t)
13640 (goto-char (setq pos (match-beginning 0)))
13641 (condition-case nil
13642 (funcall cmd)
13643 (error (message "Error during update of dynamic block")))
13644 (goto-char pos)
13645 (unless (re-search-forward org-dblock-end-re nil t)
13646 (error "Dynamic block not terminated"))))))
13648 (defun org-dblock-update (&optional arg)
13649 "User command for updating dynamic blocks.
13650 Update the dynamic block at point. With prefix ARG, update all dynamic
13651 blocks in the buffer."
13652 (interactive "P")
13653 (if arg
13654 (org-update-all-dblocks)
13655 (or (looking-at org-dblock-start-re)
13656 (org-beginning-of-dblock))
13657 (org-update-dblock)))
13659 (defun org-update-dblock ()
13660 "Update the dynamic block at point
13661 This means to empty the block, parse for parameters and then call
13662 the correct writing function."
13663 (save-window-excursion
13664 (let* ((pos (point))
13665 (line (org-current-line))
13666 (params (org-prepare-dblock))
13667 (name (plist-get params :name))
13668 (cmd (intern (concat "org-dblock-write:" name))))
13669 (message "Updating dynamic block `%s' at line %d..." name line)
13670 (funcall cmd params)
13671 (message "Updating dynamic block `%s' at line %d...done" name line)
13672 (goto-char pos))))
13674 (defun org-beginning-of-dblock ()
13675 "Find the beginning of the dynamic block at point.
13676 Error if there is no scuh block at point."
13677 (let ((pos (point))
13678 beg)
13679 (end-of-line 1)
13680 (if (and (re-search-backward org-dblock-start-re nil t)
13681 (setq beg (match-beginning 0))
13682 (re-search-forward org-dblock-end-re nil t)
13683 (> (match-end 0) pos))
13684 (goto-char beg)
13685 (goto-char pos)
13686 (error "Not in a dynamic block"))))
13688 (defun org-update-all-dblocks ()
13689 "Update all dynamic blocks in the buffer.
13690 This function can be used in a hook."
13691 (when (org-mode-p)
13692 (org-map-dblocks 'org-update-dblock)))
13695 ;;;; Completion
13697 (defconst org-additional-option-like-keywords
13698 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13699 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
13700 "BEGIN_EXAMPLE" "END_EXAMPLE"))
13702 (defun org-complete (&optional arg)
13703 "Perform completion on word at point.
13704 At the beginning of a headline, this completes TODO keywords as given in
13705 `org-todo-keywords'.
13706 If the current word is preceded by a backslash, completes the TeX symbols
13707 that are supported for HTML support.
13708 If the current word is preceded by \"#+\", completes special words for
13709 setting file options.
13710 In the line after \"#+STARTUP:, complete valid keywords.\"
13711 At all other locations, this simply calls the value of
13712 `org-completion-fallback-command'."
13713 (interactive "P")
13714 (org-without-partial-completion
13715 (catch 'exit
13716 (let* ((end (point))
13717 (beg1 (save-excursion
13718 (skip-chars-backward (org-re "[:alnum:]_@"))
13719 (point)))
13720 (beg (save-excursion
13721 (skip-chars-backward "a-zA-Z0-9_:$")
13722 (point)))
13723 (confirm (lambda (x) (stringp (car x))))
13724 (searchhead (equal (char-before beg) ?*))
13725 (tag (and (equal (char-before beg1) ?:)
13726 (equal (char-after (point-at-bol)) ?*)))
13727 (prop (and (equal (char-before beg1) ?:)
13728 (not (equal (char-after (point-at-bol)) ?*))))
13729 (texp (equal (char-before beg) ?\\))
13730 (link (equal (char-before beg) ?\[))
13731 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13732 beg)
13733 "#+"))
13734 (startup (string-match "^#\\+STARTUP:.*"
13735 (buffer-substring (point-at-bol) (point))))
13736 (completion-ignore-case opt)
13737 (type nil)
13738 (tbl nil)
13739 (table (cond
13740 (opt
13741 (setq type :opt)
13742 (append
13743 (mapcar
13744 (lambda (x)
13745 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13746 (cons (match-string 2 x) (match-string 1 x)))
13747 (org-split-string (org-get-current-options) "\n"))
13748 (mapcar 'list org-additional-option-like-keywords)))
13749 (startup
13750 (setq type :startup)
13751 org-startup-options)
13752 (link (append org-link-abbrev-alist-local
13753 org-link-abbrev-alist))
13754 (texp
13755 (setq type :tex)
13756 org-html-entities)
13757 ((string-match "\\`\\*+[ \t]+\\'"
13758 (buffer-substring (point-at-bol) beg))
13759 (setq type :todo)
13760 (mapcar 'list org-todo-keywords-1))
13761 (searchhead
13762 (setq type :searchhead)
13763 (save-excursion
13764 (goto-char (point-min))
13765 (while (re-search-forward org-todo-line-regexp nil t)
13766 (push (list
13767 (org-make-org-heading-search-string
13768 (match-string 3) t))
13769 tbl)))
13770 tbl)
13771 (tag (setq type :tag beg beg1)
13772 (or org-tag-alist (org-get-buffer-tags)))
13773 (prop (setq type :prop beg beg1)
13774 (mapcar 'list (org-buffer-property-keys)))
13775 (t (progn
13776 (call-interactively org-completion-fallback-command)
13777 (throw 'exit nil)))))
13778 (pattern (buffer-substring-no-properties beg end))
13779 (completion (try-completion pattern table confirm)))
13780 (cond ((eq completion t)
13781 (if (not (assoc (upcase pattern) table))
13782 (message "Already complete")
13783 (if (equal type :opt)
13784 (insert (substring (cdr (assoc (upcase pattern) table))
13785 (length pattern)))
13786 (if (memq type '(:tag :prop)) (insert ":")))))
13787 ((null completion)
13788 (message "Can't find completion for \"%s\"" pattern)
13789 (ding))
13790 ((not (string= pattern completion))
13791 (delete-region beg end)
13792 (if (string-match " +$" completion)
13793 (setq completion (replace-match "" t t completion)))
13794 (insert completion)
13795 (if (get-buffer-window "*Completions*")
13796 (delete-window (get-buffer-window "*Completions*")))
13797 (if (assoc completion table)
13798 (if (eq type :todo) (insert " ")
13799 (if (memq type '(:tag :prop)) (insert ":"))))
13800 (if (and (equal type :opt) (assoc completion table))
13801 (message "%s" (substitute-command-keys
13802 "Press \\[org-complete] again to insert example settings"))))
13804 (message "Making completion list...")
13805 (let ((list (sort (all-completions pattern table confirm)
13806 'string<)))
13807 (with-output-to-temp-buffer "*Completions*"
13808 (condition-case nil
13809 ;; Protection needed for XEmacs and emacs 21
13810 (display-completion-list list pattern)
13811 (error (display-completion-list list)))))
13812 (message "Making completion list...%s" "done")))))))
13814 ;;;; TODO, DEADLINE, Comments
13816 (defun org-toggle-comment ()
13817 "Change the COMMENT state of an entry."
13818 (interactive)
13819 (save-excursion
13820 (org-back-to-heading)
13821 (let (case-fold-search)
13822 (if (looking-at (concat outline-regexp
13823 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13824 (replace-match "" t t nil 1)
13825 (if (looking-at outline-regexp)
13826 (progn
13827 (goto-char (match-end 0))
13828 (insert org-comment-string " ")))))))
13830 (defvar org-last-todo-state-is-todo nil
13831 "This is non-nil when the last TODO state change led to a TODO state.
13832 If the last change removed the TODO tag or switched to DONE, then
13833 this is nil.")
13835 (defvar org-setting-tags nil) ; dynamically skiped
13837 ;; FIXME: better place
13838 (defun org-property-or-variable-value (var &optional inherit)
13839 "Check if there is a property fixing the value of VAR.
13840 If yes, return this value. If not, return the current value of the variable."
13841 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13842 (if (and prop (stringp prop) (string-match "\\S-" prop))
13843 (read prop)
13844 (symbol-value var))))
13846 (defun org-parse-local-options (string var)
13847 "Parse STRING for startup setting relevant for variable VAR."
13848 (let ((rtn (symbol-value var))
13849 e opts)
13850 (save-match-data
13851 (if (or (not string) (not (string-match "\\S-" string)))
13853 (setq opts (delq nil (mapcar (lambda (x)
13854 (setq e (assoc x org-startup-options))
13855 (if (eq (nth 1 e) var) e nil))
13856 (org-split-string string "[ \t]+"))))
13857 (if (not opts)
13859 (setq rtn nil)
13860 (while (setq e (pop opts))
13861 (if (not (nth 3 e))
13862 (setq rtn (nth 2 e))
13863 (if (not (listp rtn)) (setq rtn nil))
13864 (push (nth 2 e) rtn)))
13865 rtn)))))
13867 (defvar org-blocker-hook nil
13868 "Hook for functions that are allowed to block a state change.
13870 Each function gets as its single argument a property list, see
13871 `org-trigger-hook' for more information about this list.
13873 If any of the functions in this hook returns nil, the state change
13874 is blocked.")
13876 (defvar org-trigger-hook nil
13877 "Hook for functions that are triggered by a state change.
13879 Each function gets as its single argument a property list with at least
13880 the following elements:
13882 (:type type-of-change :position pos-at-entry-start
13883 :from old-state :to new-state)
13885 Depending on the type, more properties may be present.
13887 This mechanism is currently implemented for:
13889 TODO state changes
13890 ------------------
13891 :type todo-state-change
13892 :from previous state (keyword as a string), or nil
13893 :to new state (keyword as a string), or nil")
13896 (defun org-todo (&optional arg)
13897 "Change the TODO state of an item.
13898 The state of an item is given by a keyword at the start of the heading,
13899 like
13900 *** TODO Write paper
13901 *** DONE Call mom
13903 The different keywords are specified in the variable `org-todo-keywords'.
13904 By default the available states are \"TODO\" and \"DONE\".
13905 So for this example: when the item starts with TODO, it is changed to DONE.
13906 When it starts with DONE, the DONE is removed. And when neither TODO nor
13907 DONE are present, add TODO at the beginning of the heading.
13909 With C-u prefix arg, use completion to determine the new state.
13910 With numeric prefix arg, switch to that state.
13912 For calling through lisp, arg is also interpreted in the following way:
13913 'none -> empty state
13914 \"\"(empty string) -> switch to empty state
13915 'done -> switch to DONE
13916 'nextset -> switch to the next set of keywords
13917 'previousset -> switch to the previous set of keywords
13918 \"WAITING\" -> switch to the specified keyword, but only if it
13919 really is a member of `org-todo-keywords'."
13920 (interactive "P")
13921 (save-excursion
13922 (catch 'exit
13923 (org-back-to-heading)
13924 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13925 (or (looking-at (concat " +" org-todo-regexp " *"))
13926 (looking-at " *"))
13927 (let* ((match-data (match-data))
13928 (startpos (point-at-bol))
13929 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13930 (org-log-done (org-parse-local-options logging 'org-log-done))
13931 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13932 (this (match-string 1))
13933 (hl-pos (match-beginning 0))
13934 (head (org-get-todo-sequence-head this))
13935 (ass (assoc head org-todo-kwd-alist))
13936 (interpret (nth 1 ass))
13937 (done-word (nth 3 ass))
13938 (final-done-word (nth 4 ass))
13939 (last-state (or this ""))
13940 (completion-ignore-case t)
13941 (member (member this org-todo-keywords-1))
13942 (tail (cdr member))
13943 (state (cond
13944 ((and org-todo-key-trigger
13945 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13946 (and (not arg) org-use-fast-todo-selection
13947 (not (eq org-use-fast-todo-selection 'prefix)))))
13948 ;; Use fast selection
13949 (org-fast-todo-selection))
13950 ((and (equal arg '(4))
13951 (or (not org-use-fast-todo-selection)
13952 (not org-todo-key-trigger)))
13953 ;; Read a state with completion
13954 (completing-read "State: " (mapcar (lambda(x) (list x))
13955 org-todo-keywords-1)
13956 nil t))
13957 ((eq arg 'right)
13958 (if this
13959 (if tail (car tail) nil)
13960 (car org-todo-keywords-1)))
13961 ((eq arg 'left)
13962 (if (equal member org-todo-keywords-1)
13964 (if this
13965 (nth (- (length org-todo-keywords-1) (length tail) 2)
13966 org-todo-keywords-1)
13967 (org-last org-todo-keywords-1))))
13968 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13969 (setq arg nil))) ; hack to fall back to cycling
13970 (arg
13971 ;; user or caller requests a specific state
13972 (cond
13973 ((equal arg "") nil)
13974 ((eq arg 'none) nil)
13975 ((eq arg 'done) (or done-word (car org-done-keywords)))
13976 ((eq arg 'nextset)
13977 (or (car (cdr (member head org-todo-heads)))
13978 (car org-todo-heads)))
13979 ((eq arg 'previousset)
13980 (let ((org-todo-heads (reverse org-todo-heads)))
13981 (or (car (cdr (member head org-todo-heads)))
13982 (car org-todo-heads))))
13983 ((car (member arg org-todo-keywords-1)))
13984 ((nth (1- (prefix-numeric-value arg))
13985 org-todo-keywords-1))))
13986 ((null member) (or head (car org-todo-keywords-1)))
13987 ((equal this final-done-word) nil) ;; -> make empty
13988 ((null tail) nil) ;; -> first entry
13989 ((eq interpret 'sequence)
13990 (car tail))
13991 ((memq interpret '(type priority))
13992 (if (eq this-command last-command)
13993 (car tail)
13994 (if (> (length tail) 0)
13995 (or done-word (car org-done-keywords))
13996 nil)))
13997 (t nil)))
13998 (next (if state (concat " " state " ") " "))
13999 (change-plist (list :type 'todo-state-change :from this :to state
14000 :position startpos))
14001 dostates)
14002 (when org-blocker-hook
14003 (unless (save-excursion
14004 (save-match-data
14005 (run-hook-with-args-until-failure
14006 'org-blocker-hook change-plist)))
14007 (if (interactive-p)
14008 (error "TODO state change from %s to %s blocked" this state)
14009 ;; fail silently
14010 (message "TODO state change from %s to %s blocked" this state)
14011 (throw 'exit nil))))
14012 (store-match-data match-data)
14013 (replace-match next t t)
14014 (unless (pos-visible-in-window-p hl-pos)
14015 (message "TODO state changed to %s" (org-trim next)))
14016 (unless head
14017 (setq head (org-get-todo-sequence-head state)
14018 ass (assoc head org-todo-kwd-alist)
14019 interpret (nth 1 ass)
14020 done-word (nth 3 ass)
14021 final-done-word (nth 4 ass)))
14022 (when (memq arg '(nextset previousset))
14023 (message "Keyword-Set %d/%d: %s"
14024 (- (length org-todo-sets) -1
14025 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14026 (length org-todo-sets)
14027 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14028 (setq org-last-todo-state-is-todo
14029 (not (member state org-done-keywords)))
14030 (when (and org-log-done (not (memq arg '(nextset previousset))))
14031 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14032 (or (not org-todo-log-states)
14033 (member state org-todo-log-states))))
14035 (cond
14036 ((and state (member state org-not-done-keywords)
14037 (not (member this org-not-done-keywords)))
14038 ;; This is now a todo state and was not one before
14039 ;; Remove any CLOSED timestamp, and possibly log the state change
14040 (org-add-planning-info nil nil 'closed)
14041 (and dostates (org-add-log-maybe 'state state 'findpos)))
14042 ((and state dostates)
14043 ;; This is a non-nil state, and we need to log it
14044 (org-add-log-maybe 'state state 'findpos))
14045 ((and (member state org-done-keywords)
14046 (not (member this org-done-keywords)))
14047 ;; It is now done, and it was not done before
14048 (org-add-planning-info 'closed (org-current-time))
14049 (org-add-log-maybe 'done state 'findpos))))
14050 ;; Fixup tag positioning
14051 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14052 (run-hooks 'org-after-todo-state-change-hook)
14053 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14054 (if (and arg (not (member state org-done-keywords)))
14055 (setq head (org-get-todo-sequence-head state)))
14056 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14057 ;; Fixup cursor location if close to the keyword
14058 (if (and (outline-on-heading-p)
14059 (not (bolp))
14060 (save-excursion (beginning-of-line 1)
14061 (looking-at org-todo-line-regexp))
14062 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14063 (progn
14064 (goto-char (or (match-end 2) (match-end 1)))
14065 (just-one-space)))
14066 (when org-trigger-hook
14067 (save-excursion
14068 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14070 (defun org-get-todo-sequence-head (kwd)
14071 "Return the head of the TODO sequence to which KWD belongs.
14072 If KWD is not set, check if there is a text property remembering the
14073 right sequence."
14074 (let (p)
14075 (cond
14076 ((not kwd)
14077 (or (get-text-property (point-at-bol) 'org-todo-head)
14078 (progn
14079 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14080 nil (point-at-eol)))
14081 (get-text-property p 'org-todo-head))))
14082 ((not (member kwd org-todo-keywords-1))
14083 (car org-todo-keywords-1))
14084 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14086 (defun org-fast-todo-selection ()
14087 "Fast TODO keyword selection with single keys.
14088 Returns the new TODO keyword, or nil if no state change should occur."
14089 (let* ((fulltable org-todo-key-alist)
14090 (done-keywords org-done-keywords) ;; needed for the faces.
14091 (maxlen (apply 'max (mapcar
14092 (lambda (x)
14093 (if (stringp (car x)) (string-width (car x)) 0))
14094 fulltable)))
14095 (expert nil)
14096 (fwidth (+ maxlen 3 1 3))
14097 (ncol (/ (- (window-width) 4) fwidth))
14098 tg cnt e c tbl
14099 groups ingroup)
14100 (save-window-excursion
14101 (if expert
14102 (set-buffer (get-buffer-create " *Org todo*"))
14103 ; (delete-other-windows)
14104 ; (split-window-vertically)
14105 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14106 (erase-buffer)
14107 (org-set-local 'org-done-keywords done-keywords)
14108 (setq tbl fulltable cnt 0)
14109 (while (setq e (pop tbl))
14110 (cond
14111 ((equal e '(:startgroup))
14112 (push '() groups) (setq ingroup t)
14113 (when (not (= cnt 0))
14114 (setq cnt 0)
14115 (insert "\n"))
14116 (insert "{ "))
14117 ((equal e '(:endgroup))
14118 (setq ingroup nil cnt 0)
14119 (insert "}\n"))
14121 (setq tg (car e) c (cdr e))
14122 (if ingroup (push tg (car groups)))
14123 (setq tg (org-add-props tg nil 'face
14124 (org-get-todo-face tg)))
14125 (if (and (= cnt 0) (not ingroup)) (insert " "))
14126 (insert "[" c "] " tg (make-string
14127 (- fwidth 4 (length tg)) ?\ ))
14128 (when (= (setq cnt (1+ cnt)) ncol)
14129 (insert "\n")
14130 (if ingroup (insert " "))
14131 (setq cnt 0)))))
14132 (insert "\n")
14133 (goto-char (point-min))
14134 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14135 (fit-window-to-buffer))
14136 (message "[a-z..]:Set [SPC]:clear")
14137 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14138 (cond
14139 ((or (= c ?\C-g)
14140 (and (= c ?q) (not (rassoc c fulltable))))
14141 (setq quit-flag t))
14142 ((= c ?\ ) nil)
14143 ((setq e (rassoc c fulltable) tg (car e))
14145 (t (setq quit-flag t))))))
14147 (defun org-get-repeat ()
14148 "Check if tere is a deadline/schedule with repeater in this entry."
14149 (save-match-data
14150 (save-excursion
14151 (org-back-to-heading t)
14152 (if (re-search-forward
14153 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14154 (match-string 1)))))
14156 (defvar org-last-changed-timestamp)
14157 (defvar org-log-post-message)
14158 (defun org-auto-repeat-maybe ()
14159 "Check if the current headline contains a repeated deadline/schedule.
14160 If yes, set TODO state back to what it was and change the base date
14161 of repeating deadline/scheduled time stamps to new date.
14162 This function should be run in the `org-after-todo-state-change-hook'."
14163 ;; last-state is dynamically scoped into this function
14164 (let* ((repeat (org-get-repeat))
14165 (aa (assoc last-state org-todo-kwd-alist))
14166 (interpret (nth 1 aa))
14167 (head (nth 2 aa))
14168 (done-word (nth 3 aa))
14169 (whata '(("d" . day) ("m" . month) ("y" . year)))
14170 (msg "Entry repeats: ")
14171 (org-log-done)
14172 re type n what ts)
14173 (when repeat
14174 (org-todo (if (eq interpret 'type) last-state head))
14175 (when (and org-log-repeat
14176 (not (memq 'org-add-log-note
14177 (default-value 'post-command-hook))))
14178 ;; Make sure a note is taken
14179 (let ((org-log-done '(done)))
14180 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14181 'findpos)))
14182 (org-back-to-heading t)
14183 (org-add-planning-info nil nil 'closed)
14184 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14185 org-deadline-time-regexp "\\)"))
14186 (while (re-search-forward
14187 re (save-excursion (outline-next-heading) (point)) t)
14188 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14189 ts (match-string (if (match-end 2) 2 4)))
14190 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14191 (setq n (string-to-number (match-string 1 ts))
14192 what (match-string 2 ts))
14193 (if (equal what "w") (setq n (* n 7) what "d"))
14194 (org-timestamp-change n (cdr (assoc what whata))))
14195 (setq msg (concat msg type org-last-changed-timestamp " ")))
14196 (setq org-log-post-message msg)
14197 (message msg))))
14199 (defun org-show-todo-tree (arg)
14200 "Make a compact tree which shows all headlines marked with TODO.
14201 The tree will show the lines where the regexp matches, and all higher
14202 headlines above the match.
14203 With \\[universal-argument] prefix, also show the DONE entries.
14204 With a numeric prefix N, construct a sparse tree for the Nth element
14205 of `org-todo-keywords-1'."
14206 (interactive "P")
14207 (let ((case-fold-search nil)
14208 (kwd-re
14209 (cond ((null arg) org-not-done-regexp)
14210 ((equal arg '(4))
14211 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14212 (mapcar 'list org-todo-keywords-1))))
14213 (concat "\\("
14214 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14215 "\\)\\>")))
14216 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14217 (regexp-quote (nth (1- (prefix-numeric-value arg))
14218 org-todo-keywords-1)))
14219 (t (error "Invalid prefix argument: %s" arg)))))
14220 (message "%d TODO entries found"
14221 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14223 (defun org-deadline (&optional remove)
14224 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14225 With argument REMOVE, remove any deadline from the item."
14226 (interactive "P")
14227 (if remove
14228 (progn
14229 (org-add-planning-info nil nil 'deadline)
14230 (message "Item no longer has a deadline."))
14231 (org-add-planning-info 'deadline nil 'closed)))
14233 (defun org-schedule (&optional remove)
14234 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14235 With argument REMOVE, remove any scheduling date from the item."
14236 (interactive "P")
14237 (if remove
14238 (progn
14239 (org-add-planning-info nil nil 'scheduled)
14240 (message "Item is no longer scheduled."))
14241 (org-add-planning-info 'scheduled nil 'closed)))
14243 (defun org-add-planning-info (what &optional time &rest remove)
14244 "Insert new timestamp with keyword in the line directly after the headline.
14245 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14246 If non is given, the user is prompted for a date.
14247 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14248 be removed."
14249 (interactive)
14250 (let (org-time-was-given org-end-time-was-given)
14251 (when what (setq time (or time (org-read-date nil 'to-time))))
14252 (when (and org-insert-labeled-timestamps-at-point
14253 (member what '(scheduled deadline)))
14254 (insert
14255 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14256 (org-insert-time-stamp time org-time-was-given
14257 nil nil nil (list org-end-time-was-given))
14258 (setq what nil))
14259 (save-excursion
14260 (save-restriction
14261 (let (col list elt ts buffer-invisibility-spec)
14262 (org-back-to-heading t)
14263 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14264 (goto-char (match-end 1))
14265 (setq col (current-column))
14266 (goto-char (match-end 0))
14267 (if (eobp) (insert "\n") (forward-char 1))
14268 (if (and (not (looking-at outline-regexp))
14269 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14270 "[^\r\n]*"))
14271 (not (equal (match-string 1) org-clock-string)))
14272 (narrow-to-region (match-beginning 0) (match-end 0))
14273 (insert-before-markers "\n")
14274 (backward-char 1)
14275 (narrow-to-region (point) (point))
14276 (indent-to-column col))
14277 ;; Check if we have to remove something.
14278 (setq list (cons what remove))
14279 (while list
14280 (setq elt (pop list))
14281 (goto-char (point-min))
14282 (when (or (and (eq elt 'scheduled)
14283 (re-search-forward org-scheduled-time-regexp nil t))
14284 (and (eq elt 'deadline)
14285 (re-search-forward org-deadline-time-regexp nil t))
14286 (and (eq elt 'closed)
14287 (re-search-forward org-closed-time-regexp nil t)))
14288 (replace-match "")
14289 (if (looking-at "--+<[^>]+>") (replace-match ""))
14290 (if (looking-at " +") (replace-match ""))))
14291 (goto-char (point-max))
14292 (when what
14293 (insert
14294 (if (not (equal (char-before) ?\ )) " " "")
14295 (cond ((eq what 'scheduled) org-scheduled-string)
14296 ((eq what 'deadline) org-deadline-string)
14297 ((eq what 'closed) org-closed-string))
14298 " ")
14299 (setq ts (org-insert-time-stamp
14300 time
14301 (or org-time-was-given
14302 (and (eq what 'closed) org-log-done-with-time))
14303 (eq what 'closed)
14304 nil nil (list org-end-time-was-given)))
14305 (end-of-line 1))
14306 (goto-char (point-min))
14307 (widen)
14308 (if (looking-at "[ \t]+\r?\n")
14309 (replace-match ""))
14310 ts)))))
14312 (defvar org-log-note-marker (make-marker))
14313 (defvar org-log-note-purpose nil)
14314 (defvar org-log-note-state nil)
14315 (defvar org-log-note-window-configuration nil)
14316 (defvar org-log-note-return-to (make-marker))
14317 (defvar org-log-post-message nil
14318 "Message to be displayed after a log note has been stored.
14319 The auto-repeater uses this.")
14321 (defun org-add-log-maybe (&optional purpose state findpos)
14322 "Set up the post command hook to take a note."
14323 (save-excursion
14324 (when (and (listp org-log-done)
14325 (memq purpose org-log-done))
14326 (when findpos
14327 (org-back-to-heading t)
14328 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14329 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14330 "[^\r\n]*\\)?"))
14331 (goto-char (match-end 0))
14332 (unless org-log-states-order-reversed
14333 (and (= (char-after) ?\n) (forward-char 1))
14334 (org-skip-over-state-notes)
14335 (skip-chars-backward " \t\n\r")))
14336 (move-marker org-log-note-marker (point))
14337 (setq org-log-note-purpose purpose)
14338 (setq org-log-note-state state)
14339 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14341 (defun org-skip-over-state-notes ()
14342 "Skip past the list of State notes in an entry."
14343 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14344 (while (looking-at "[ \t]*- State")
14345 (condition-case nil
14346 (org-next-item)
14347 (error (org-end-of-item)))))
14349 (defun org-add-log-note (&optional purpose)
14350 "Pop up a window for taking a note, and add this note later at point."
14351 (remove-hook 'post-command-hook 'org-add-log-note)
14352 (setq org-log-note-window-configuration (current-window-configuration))
14353 (delete-other-windows)
14354 (move-marker org-log-note-return-to (point))
14355 (switch-to-buffer (marker-buffer org-log-note-marker))
14356 (goto-char org-log-note-marker)
14357 (org-switch-to-buffer-other-window "*Org Note*")
14358 (erase-buffer)
14359 (let ((org-inhibit-startup t)) (org-mode))
14360 (insert (format "# Insert note for %s.
14361 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14362 (cond
14363 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14364 ((eq org-log-note-purpose 'done) "closed todo item")
14365 ((eq org-log-note-purpose 'state)
14366 (format "state change to \"%s\"" org-log-note-state))
14367 (t (error "This should not happen")))))
14368 (org-set-local 'org-finish-function 'org-store-log-note))
14370 (defun org-store-log-note ()
14371 "Finish taking a log note, and insert it to where it belongs."
14372 (let ((txt (buffer-string))
14373 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14374 lines ind)
14375 (kill-buffer (current-buffer))
14376 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14377 (setq txt (replace-match "" t t txt)))
14378 (if (string-match "\\s-+\\'" txt)
14379 (setq txt (replace-match "" t t txt)))
14380 (setq lines (org-split-string txt "\n"))
14381 (when (and note (string-match "\\S-" note))
14382 (setq note
14383 (org-replace-escapes
14384 note
14385 (list (cons "%u" (user-login-name))
14386 (cons "%U" user-full-name)
14387 (cons "%t" (format-time-string
14388 (org-time-stamp-format 'long 'inactive)
14389 (current-time)))
14390 (cons "%s" (if org-log-note-state
14391 (concat "\"" org-log-note-state "\"")
14392 "")))))
14393 (if lines (setq note (concat note " \\\\")))
14394 (push note lines))
14395 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14396 (when lines
14397 (save-excursion
14398 (set-buffer (marker-buffer org-log-note-marker))
14399 (save-excursion
14400 (goto-char org-log-note-marker)
14401 (move-marker org-log-note-marker nil)
14402 (end-of-line 1)
14403 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14404 (indent-relative nil)
14405 (insert "- " (pop lines))
14406 (org-indent-line-function)
14407 (beginning-of-line 1)
14408 (looking-at "[ \t]*")
14409 (setq ind (concat (match-string 0) " "))
14410 (end-of-line 1)
14411 (while lines (insert "\n" ind (pop lines)))))))
14412 (set-window-configuration org-log-note-window-configuration)
14413 (with-current-buffer (marker-buffer org-log-note-return-to)
14414 (goto-char org-log-note-return-to))
14415 (move-marker org-log-note-return-to nil)
14416 (and org-log-post-message (message org-log-post-message)))
14418 ;; FIXME: what else would be useful?
14419 ;; - priority
14420 ;; - date
14422 (defun org-sparse-tree (&optional arg)
14423 "Create a sparse tree, prompt for the details.
14424 This command can create sparse trees. You first need to select the type
14425 of match used to create the tree:
14427 t Show entries with a specific TODO keyword.
14428 T Show entries selected by a tags match.
14429 p Enter a property name and its value (both with completion on existing
14430 names/values) and show entries with that property.
14431 r Show entries matching a regular expression"
14432 (interactive "P")
14433 (let (ans kwd value)
14434 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines")
14435 (setq ans (read-char-exclusive))
14436 (cond
14437 ((equal ans ?d)
14438 (call-interactively 'org-check-deadlines))
14439 ((equal ans ?t)
14440 (org-show-todo-tree '(4)))
14441 ((equal ans ?T)
14442 (call-interactively 'org-tags-sparse-tree))
14443 ((member ans '(?p ?P))
14444 (setq kwd (completing-read "Property: "
14445 (mapcar 'list (org-buffer-property-keys))))
14446 (setq value (completing-read "Value: "
14447 (mapcar 'list (org-property-values kwd))))
14448 (unless (string-match "\\`{.*}\\'" value)
14449 (setq value (concat "\"" value "\"")))
14450 (org-tags-sparse-tree arg (concat kwd "=" value)))
14451 ((member ans '(?r ?R ?/))
14452 (call-interactively 'org-occur))
14453 (t (error "No such sparse tree command \"%c\"" ans)))))
14455 (defvar org-occur-highlights nil)
14456 (make-variable-buffer-local 'org-occur-highlights)
14458 (defun org-occur (regexp &optional keep-previous callback)
14459 "Make a compact tree which shows all matches of REGEXP.
14460 The tree will show the lines where the regexp matches, and all higher
14461 headlines above the match. It will also show the heading after the match,
14462 to make sure editing the matching entry is easy.
14463 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14464 call to `org-occur' will be kept, to allow stacking of calls to this
14465 command.
14466 If CALLBACK is non-nil, it is a function which is called to confirm
14467 that the match should indeed be shown."
14468 (interactive "sRegexp: \nP")
14469 (or keep-previous (org-remove-occur-highlights nil nil t))
14470 (let ((cnt 0))
14471 (save-excursion
14472 (goto-char (point-min))
14473 (if (or (not keep-previous) ; do not want to keep
14474 (not org-occur-highlights)) ; no previous matches
14475 ;; hide everything
14476 (org-overview))
14477 (while (re-search-forward regexp nil t)
14478 (when (or (not callback)
14479 (save-match-data (funcall callback)))
14480 (setq cnt (1+ cnt))
14481 (when org-highlight-sparse-tree-matches
14482 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14483 (org-show-context 'occur-tree))))
14484 (when org-remove-highlights-with-change
14485 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14486 nil 'local))
14487 (unless org-sparse-tree-open-archived-trees
14488 (org-hide-archived-subtrees (point-min) (point-max)))
14489 (run-hooks 'org-occur-hook)
14490 (if (interactive-p)
14491 (message "%d match(es) for regexp %s" cnt regexp))
14492 cnt))
14494 (defun org-show-context (&optional key)
14495 "Make sure point and context and visible.
14496 How much context is shown depends upon the variables
14497 `org-show-hierarchy-above', `org-show-following-heading'. and
14498 `org-show-siblings'."
14499 (let ((heading-p (org-on-heading-p t))
14500 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14501 (following-p (org-get-alist-option org-show-following-heading key))
14502 (entry-p (org-get-alist-option org-show-entry-below key))
14503 (siblings-p (org-get-alist-option org-show-siblings key)))
14504 (catch 'exit
14505 ;; Show heading or entry text
14506 (if (and heading-p (not entry-p))
14507 (org-flag-heading nil) ; only show the heading
14508 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14509 (org-show-hidden-entry))) ; show entire entry
14510 (when following-p
14511 ;; Show next sibling, or heading below text
14512 (save-excursion
14513 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14514 (org-flag-heading nil))))
14515 (when siblings-p (org-show-siblings))
14516 (when hierarchy-p
14517 ;; show all higher headings, possibly with siblings
14518 (save-excursion
14519 (while (and (condition-case nil
14520 (progn (org-up-heading-all 1) t)
14521 (error nil))
14522 (not (bobp)))
14523 (org-flag-heading nil)
14524 (when siblings-p (org-show-siblings))))))))
14526 (defun org-reveal (&optional siblings)
14527 "Show current entry, hierarchy above it, and the following headline.
14528 This can be used to show a consistent set of context around locations
14529 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14530 not t for the search context.
14532 With optional argument SIBLINGS, on each level of the hierarchy all
14533 siblings are shown. This repairs the tree structure to what it would
14534 look like when opened with hierarchical calls to `org-cycle'."
14535 (interactive "P")
14536 (let ((org-show-hierarchy-above t)
14537 (org-show-following-heading t)
14538 (org-show-siblings (if siblings t org-show-siblings)))
14539 (org-show-context nil)))
14541 (defun org-highlight-new-match (beg end)
14542 "Highlight from BEG to END and mark the highlight is an occur headline."
14543 (let ((ov (org-make-overlay beg end)))
14544 (org-overlay-put ov 'face 'secondary-selection)
14545 (push ov org-occur-highlights)))
14547 (defun org-remove-occur-highlights (&optional beg end noremove)
14548 "Remove the occur highlights from the buffer.
14549 BEG and END are ignored. If NOREMOVE is nil, remove this function
14550 from the `before-change-functions' in the current buffer."
14551 (interactive)
14552 (unless org-inhibit-highlight-removal
14553 (mapc 'org-delete-overlay org-occur-highlights)
14554 (setq org-occur-highlights nil)
14555 (unless noremove
14556 (remove-hook 'before-change-functions
14557 'org-remove-occur-highlights 'local))))
14559 ;;;; Priorities
14561 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14562 "Regular expression matching the priority indicator.")
14564 (defvar org-remove-priority-next-time nil)
14566 (defun org-priority-up ()
14567 "Increase the priority of the current item."
14568 (interactive)
14569 (org-priority 'up))
14571 (defun org-priority-down ()
14572 "Decrease the priority of the current item."
14573 (interactive)
14574 (org-priority 'down))
14576 (defun org-priority (&optional action)
14577 "Change the priority of an item by ARG.
14578 ACTION can be `set', `up', `down', or a character."
14579 (interactive)
14580 (setq action (or action 'set))
14581 (let (current new news have remove)
14582 (save-excursion
14583 (org-back-to-heading)
14584 (if (looking-at org-priority-regexp)
14585 (setq current (string-to-char (match-string 2))
14586 have t)
14587 (setq current org-default-priority))
14588 (cond
14589 ((or (eq action 'set) (integerp action))
14590 (if (integerp action)
14591 (setq new action)
14592 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14593 (setq new (read-char-exclusive)))
14594 (if (and (= (upcase org-highest-priority) org-highest-priority)
14595 (= (upcase org-lowest-priority) org-lowest-priority))
14596 (setq new (upcase new)))
14597 (cond ((equal new ?\ ) (setq remove t))
14598 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14599 (error "Priority must be between `%c' and `%c'"
14600 org-highest-priority org-lowest-priority))))
14601 ((eq action 'up)
14602 (if (and (not have) (eq last-command this-command))
14603 (setq new org-lowest-priority)
14604 (setq new (if (and org-priority-start-cycle-with-default (not have))
14605 org-default-priority (1- current)))))
14606 ((eq action 'down)
14607 (if (and (not have) (eq last-command this-command))
14608 (setq new org-highest-priority)
14609 (setq new (if (and org-priority-start-cycle-with-default (not have))
14610 org-default-priority (1+ current)))))
14611 (t (error "Invalid action")))
14612 (if (or (< (upcase new) org-highest-priority)
14613 (> (upcase new) org-lowest-priority))
14614 (setq remove t))
14615 (setq news (format "%c" new))
14616 (if have
14617 (if remove
14618 (replace-match "" t t nil 1)
14619 (replace-match news t t nil 2))
14620 (if remove
14621 (error "No priority cookie found in line")
14622 (looking-at org-todo-line-regexp)
14623 (if (match-end 2)
14624 (progn
14625 (goto-char (match-end 2))
14626 (insert " [#" news "]"))
14627 (goto-char (match-beginning 3))
14628 (insert "[#" news "] ")))))
14629 (org-preserve-lc (org-set-tags nil 'align))
14630 (if remove
14631 (message "Priority removed")
14632 (message "Priority of current item set to %s" news))))
14635 (defun org-get-priority (s)
14636 "Find priority cookie and return priority."
14637 (save-match-data
14638 (if (not (string-match org-priority-regexp s))
14639 (* 1000 (- org-lowest-priority org-default-priority))
14640 (* 1000 (- org-lowest-priority
14641 (string-to-char (match-string 2 s)))))))
14643 ;;;; Tags
14645 (defun org-scan-tags (action matcher &optional todo-only)
14646 "Scan headline tags with inheritance and produce output ACTION.
14647 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14648 evaluated, testing if a given set of tags qualifies a headline for
14649 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14650 are included in the output."
14651 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14652 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14653 (org-re
14654 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14655 (props (list 'face nil
14656 'done-face 'org-done
14657 'undone-face nil
14658 'mouse-face 'highlight
14659 'org-not-done-regexp org-not-done-regexp
14660 'org-todo-regexp org-todo-regexp
14661 'keymap org-agenda-keymap
14662 'help-echo
14663 (format "mouse-2 or RET jump to org file %s"
14664 (abbreviate-file-name
14665 (or (buffer-file-name (buffer-base-buffer))
14666 (buffer-name (buffer-base-buffer)))))))
14667 (case-fold-search nil)
14668 lspos
14669 tags tags-list tags-alist (llast 0) rtn level category i txt
14670 todo marker entry priority)
14671 (save-excursion
14672 (goto-char (point-min))
14673 (when (eq action 'sparse-tree)
14674 (org-overview)
14675 (org-remove-occur-highlights))
14676 (while (re-search-forward re nil t)
14677 (catch :skip
14678 (setq todo (if (match-end 1) (match-string 2))
14679 tags (if (match-end 4) (match-string 4)))
14680 (goto-char (setq lspos (1+ (match-beginning 0))))
14681 (setq level (org-reduced-level (funcall outline-level))
14682 category (org-get-category))
14683 (setq i llast llast level)
14684 ;; remove tag lists from same and sublevels
14685 (while (>= i level)
14686 (when (setq entry (assoc i tags-alist))
14687 (setq tags-alist (delete entry tags-alist)))
14688 (setq i (1- i)))
14689 ;; add the nex tags
14690 (when tags
14691 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14692 tags-alist
14693 (cons (cons level tags) tags-alist)))
14694 ;; compile tags for current headline
14695 (setq tags-list
14696 (if org-use-tag-inheritance
14697 (apply 'append (mapcar 'cdr tags-alist))
14698 tags))
14699 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14700 (eval matcher)
14701 (or (not org-agenda-skip-archived-trees)
14702 (not (member org-archive-tag tags-list))))
14703 (and (eq action 'agenda) (org-agenda-skip))
14704 ;; list this headline
14706 (if (eq action 'sparse-tree)
14707 (progn
14708 (and org-highlight-sparse-tree-matches
14709 (org-get-heading) (match-end 0)
14710 (org-highlight-new-match
14711 (match-beginning 0) (match-beginning 1)))
14712 (org-show-context 'tags-tree))
14713 (setq txt (org-format-agenda-item
14715 (concat
14716 (if org-tags-match-list-sublevels
14717 (make-string (1- level) ?.) "")
14718 (org-get-heading))
14719 category tags-list)
14720 priority (org-get-priority txt))
14721 (goto-char lspos)
14722 (setq marker (org-agenda-new-marker))
14723 (org-add-props txt props
14724 'org-marker marker 'org-hd-marker marker 'org-category category
14725 'priority priority 'type "tagsmatch")
14726 (push txt rtn))
14727 ;; if we are to skip sublevels, jump to end of subtree
14728 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14729 (when (and (eq action 'sparse-tree)
14730 (not org-sparse-tree-open-archived-trees))
14731 (org-hide-archived-subtrees (point-min) (point-max)))
14732 (nreverse rtn)))
14734 (defvar todo-only) ;; dynamically scoped
14736 (defun org-tags-sparse-tree (&optional todo-only match)
14737 "Create a sparse tree according to tags string MATCH.
14738 MATCH can contain positive and negative selection of tags, like
14739 \"+WORK+URGENT-WITHBOSS\".
14740 If optional argument TODO_ONLY is non-nil, only select lines that are
14741 also TODO lines."
14742 (interactive "P")
14743 (org-prepare-agenda-buffers (list (current-buffer)))
14744 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14746 (defvar org-cached-props nil)
14747 (defun org-cached-entry-get (pom property)
14748 (if (or (eq t org-use-property-inheritance)
14749 (member property org-use-property-inheritance))
14750 ;; Caching is not possible, check it directly
14751 (org-entry-get pom property 'inherit)
14752 ;; Get all properties, so that we can do complicated checks easily
14753 (cdr (assoc property (or org-cached-props
14754 (setq org-cached-props
14755 (org-entry-properties pom)))))))
14757 (defun org-global-tags-completion-table (&optional files)
14758 "Return the list of all tags in all agenda buffer/files."
14759 (save-excursion
14760 (org-uniquify
14761 (apply 'append
14762 (mapcar
14763 (lambda (file)
14764 (set-buffer (find-file-noselect file))
14765 (org-get-buffer-tags))
14766 (if (and files (car files))
14767 files
14768 (org-agenda-files)))))))
14770 (defun org-make-tags-matcher (match)
14771 "Create the TAGS//TODO matcher form for the selection string MATCH."
14772 ;; todo-only is scoped dynamically into this function, and the function
14773 ;; may change it it the matcher asksk for it.
14774 (unless match
14775 ;; Get a new match request, with completion
14776 (let ((org-last-tags-completion-table
14777 (org-global-tags-completion-table)))
14778 (setq match (completing-read
14779 "Match: " 'org-tags-completion-function nil nil nil
14780 'org-tags-history))))
14782 ;; Parse the string and create a lisp form
14783 (let ((match0 match)
14784 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14785 minus tag mm
14786 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14787 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
14788 (if (string-match "/+" match)
14789 ;; match contains also a todo-matching request
14790 (progn
14791 (setq tagsmatch (substring match 0 (match-beginning 0))
14792 todomatch (substring match (match-end 0)))
14793 (if (string-match "^!" todomatch)
14794 (setq todo-only t todomatch (substring todomatch 1)))
14795 (if (string-match "^\\s-*$" todomatch)
14796 (setq todomatch nil)))
14797 ;; only matching tags
14798 (setq tagsmatch match todomatch nil))
14800 ;; Make the tags matcher
14801 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14802 (setq tagsmatcher t)
14803 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14804 (while (setq term (pop orterms))
14805 (while (and (equal (substring term -1) "\\") orterms)
14806 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14807 (while (string-match re term)
14808 (setq minus (and (match-end 1)
14809 (equal (match-string 1 term) "-"))
14810 tag (match-string 2 term)
14811 re-p (equal (string-to-char tag) ?{)
14812 level-p (match-end 3)
14813 prop-p (match-end 4)
14814 mm (cond
14815 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14816 (level-p `(= level ,(string-to-number
14817 (match-string 3 term))))
14818 (prop-p
14819 (setq pn (match-string 4 term)
14820 pv (match-string 5 term)
14821 cat-p (equal pn "CATEGORY")
14822 re-p (equal (string-to-char pv) ?{)
14823 pv (substring pv 1 -1))
14824 (if (equal pn "CATEGORY")
14825 (setq gv '(get-text-property (point) 'org-category))
14826 (setq gv `(org-cached-entry-get nil ,pn)))
14827 (if re-p
14828 `(string-match ,pv (or ,gv ""))
14829 `(equal ,pv ,gv)))
14830 (t `(member ,(downcase tag) tags-list)))
14831 mm (if minus (list 'not mm) mm)
14832 term (substring term (match-end 0)))
14833 (push mm tagsmatcher))
14834 (push (if (> (length tagsmatcher) 1)
14835 (cons 'and tagsmatcher)
14836 (car tagsmatcher))
14837 orlist)
14838 (setq tagsmatcher nil))
14839 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14840 (setq tagsmatcher
14841 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14843 ;; Make the todo matcher
14844 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14845 (setq todomatcher t)
14846 (setq orterms (org-split-string todomatch "|") orlist nil)
14847 (while (setq term (pop orterms))
14848 (while (string-match re term)
14849 (setq minus (and (match-end 1)
14850 (equal (match-string 1 term) "-"))
14851 kwd (match-string 2 term)
14852 re-p (equal (string-to-char kwd) ?{)
14853 term (substring term (match-end 0))
14854 mm (if re-p
14855 `(string-match ,(substring kwd 1 -1) todo)
14856 (list 'equal 'todo kwd))
14857 mm (if minus (list 'not mm) mm))
14858 (push mm todomatcher))
14859 (push (if (> (length todomatcher) 1)
14860 (cons 'and todomatcher)
14861 (car todomatcher))
14862 orlist)
14863 (setq todomatcher nil))
14864 (setq todomatcher (if (> (length orlist) 1)
14865 (cons 'or orlist) (car orlist))))
14867 ;; Return the string and lisp forms of the matcher
14868 (setq matcher (if todomatcher
14869 (list 'and tagsmatcher todomatcher)
14870 tagsmatcher))
14871 (cons match0 matcher)))
14873 (defun org-match-any-p (re list)
14874 "Does re match any element of list?"
14875 (setq list (mapcar (lambda (x) (string-match re x)) list))
14876 (delq nil list))
14878 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14879 (defvar org-tags-overlay (org-make-overlay 1 1))
14880 (org-detach-overlay org-tags-overlay)
14882 (defun org-align-tags-here (to-col)
14883 ;; Assumes that this is a headline
14884 (let ((pos (point)) (col (current-column)) tags)
14885 (beginning-of-line 1)
14886 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14887 (< pos (match-beginning 2)))
14888 (progn
14889 (setq tags (match-string 2))
14890 (goto-char (match-beginning 1))
14891 (insert " ")
14892 (delete-region (point) (1+ (match-end 0)))
14893 (backward-char 1)
14894 (move-to-column
14895 (max (1+ (current-column))
14896 (1+ col)
14897 (if (> to-col 0)
14898 to-col
14899 (- (abs to-col) (length tags))))
14901 (insert tags)
14902 (move-to-column (min (current-column) col) t))
14903 (goto-char pos))))
14905 (defun org-set-tags (&optional arg just-align)
14906 "Set the tags for the current headline.
14907 With prefix ARG, realign all tags in headings in the current buffer."
14908 (interactive "P")
14909 (let* ((re (concat "^" outline-regexp))
14910 (current (org-get-tags-string))
14911 (col (current-column))
14912 (org-setting-tags t)
14913 table current-tags inherited-tags ; computed below when needed
14914 tags p0 c0 c1 rpl)
14915 (if arg
14916 (save-excursion
14917 (goto-char (point-min))
14918 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14919 (while (re-search-forward re nil t)
14920 (org-set-tags nil t)
14921 (end-of-line 1)))
14922 (message "All tags realigned to column %d" org-tags-column))
14923 (if just-align
14924 (setq tags current)
14925 ;; Get a new set of tags from the user
14926 (save-excursion
14927 (setq table (or org-tag-alist (org-get-buffer-tags))
14928 org-last-tags-completion-table table
14929 current-tags (org-split-string current ":")
14930 inherited-tags (nreverse
14931 (nthcdr (length current-tags)
14932 (nreverse (org-get-tags-at))))
14933 tags
14934 (if (or (eq t org-use-fast-tag-selection)
14935 (and org-use-fast-tag-selection
14936 (delq nil (mapcar 'cdr table))))
14937 (org-fast-tag-selection
14938 current-tags inherited-tags table
14939 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14940 (let ((org-add-colon-after-tag-completion t))
14941 (org-trim
14942 (org-without-partial-completion
14943 (completing-read "Tags: " 'org-tags-completion-function
14944 nil nil current 'org-tags-history)))))))
14945 (while (string-match "[-+&]+" tags)
14946 ;; No boolean logic, just a list
14947 (setq tags (replace-match ":" t t tags))))
14949 (if (string-match "\\`[\t ]*\\'" tags)
14950 (setq tags "")
14951 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14952 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14954 ;; Insert new tags at the correct column
14955 (beginning-of-line 1)
14956 (cond
14957 ((and (equal current "") (equal tags "")))
14958 ((re-search-forward
14959 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14960 (point-at-eol) t)
14961 (if (equal tags "")
14962 (setq rpl "")
14963 (goto-char (match-beginning 0))
14964 (setq c0 (current-column) p0 (point)
14965 c1 (max (1+ c0) (if (> org-tags-column 0)
14966 org-tags-column
14967 (- (- org-tags-column) (length tags))))
14968 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14969 (replace-match rpl t t)
14970 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14971 tags)
14972 (t (error "Tags alignment failed")))
14973 (move-to-column col)
14974 (unless just-align
14975 (run-hooks 'org-after-tags-change-hook)))))
14977 (defun org-change-tag-in-region (beg end tag off)
14978 "Add or remove TAG for each entry in the region.
14979 This works in the agenda, and also in an org-mode buffer."
14980 (interactive
14981 (list (region-beginning) (region-end)
14982 (let ((org-last-tags-completion-table
14983 (if (org-mode-p)
14984 (org-get-buffer-tags)
14985 (org-global-tags-completion-table))))
14986 (completing-read
14987 "Tag: " 'org-tags-completion-function nil nil nil
14988 'org-tags-history))
14989 (progn
14990 (message "[s]et or [r]emove? ")
14991 (equal (read-char-exclusive) ?r))))
14992 (if (fboundp 'deactivate-mark) (deactivate-mark))
14993 (let ((agendap (equal major-mode 'org-agenda-mode))
14994 l1 l2 m buf pos newhead (cnt 0))
14995 (goto-char end)
14996 (setq l2 (1- (org-current-line)))
14997 (goto-char beg)
14998 (setq l1 (org-current-line))
14999 (loop for l from l1 to l2 do
15000 (goto-line l)
15001 (setq m (get-text-property (point) 'org-hd-marker))
15002 (when (or (and (org-mode-p) (org-on-heading-p))
15003 (and agendap m))
15004 (setq buf (if agendap (marker-buffer m) (current-buffer))
15005 pos (if agendap m (point)))
15006 (with-current-buffer buf
15007 (save-excursion
15008 (save-restriction
15009 (goto-char pos)
15010 (setq cnt (1+ cnt))
15011 (org-toggle-tag tag (if off 'off 'on))
15012 (setq newhead (org-get-heading)))))
15013 (and agendap (org-agenda-change-all-lines newhead m))))
15014 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15016 (defun org-tags-completion-function (string predicate &optional flag)
15017 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15018 (confirm (lambda (x) (stringp (car x)))))
15019 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15020 (setq s1 (match-string 1 string)
15021 s2 (match-string 2 string))
15022 (setq s1 "" s2 string))
15023 (cond
15024 ((eq flag nil)
15025 ;; try completion
15026 (setq rtn (try-completion s2 ctable confirm))
15027 (if (stringp rtn)
15028 (setq rtn
15029 (concat s1 s2 (substring rtn (length s2))
15030 (if (and org-add-colon-after-tag-completion
15031 (assoc rtn ctable))
15032 ":" ""))))
15033 rtn)
15034 ((eq flag t)
15035 ;; all-completions
15036 (all-completions s2 ctable confirm)
15038 ((eq flag 'lambda)
15039 ;; exact match?
15040 (assoc s2 ctable)))
15043 (defun org-fast-tag-insert (kwd tags face &optional end)
15044 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15045 (insert (format "%-12s" (concat kwd ":"))
15046 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15047 (or end "")))
15049 (defun org-fast-tag-show-exit (flag)
15050 (save-excursion
15051 (goto-line 3)
15052 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15053 (replace-match ""))
15054 (when flag
15055 (end-of-line 1)
15056 (move-to-column (- (window-width) 19) t)
15057 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15059 (defun org-set-current-tags-overlay (current prefix)
15060 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15061 (if (featurep 'xemacs)
15062 (org-overlay-display org-tags-overlay (concat prefix s)
15063 'secondary-selection)
15064 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15065 (org-overlay-display org-tags-overlay (concat prefix s)))))
15067 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15068 "Fast tag selection with single keys.
15069 CURRENT is the current list of tags in the headline, INHERITED is the
15070 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15071 possibly with grouping information. TODO-TABLE is a similar table with
15072 TODO keywords, should these have keys assigned to them.
15073 If the keys are nil, a-z are automatically assigned.
15074 Returns the new tags string, or nil to not change the current settings."
15075 (let* ((fulltable (append table todo-table))
15076 (maxlen (apply 'max (mapcar
15077 (lambda (x)
15078 (if (stringp (car x)) (string-width (car x)) 0))
15079 fulltable)))
15080 (buf (current-buffer))
15081 (expert (eq org-fast-tag-selection-single-key 'expert))
15082 (buffer-tags nil)
15083 (fwidth (+ maxlen 3 1 3))
15084 (ncol (/ (- (window-width) 4) fwidth))
15085 (i-face 'org-done)
15086 (c-face 'org-todo)
15087 tg cnt e c char c1 c2 ntable tbl rtn
15088 ov-start ov-end ov-prefix
15089 (exit-after-next org-fast-tag-selection-single-key)
15090 (done-keywords org-done-keywords)
15091 groups ingroup)
15092 (save-excursion
15093 (beginning-of-line 1)
15094 (if (looking-at
15095 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15096 (setq ov-start (match-beginning 1)
15097 ov-end (match-end 1)
15098 ov-prefix "")
15099 (setq ov-start (1- (point-at-eol))
15100 ov-end (1+ ov-start))
15101 (skip-chars-forward "^\n\r")
15102 (setq ov-prefix
15103 (concat
15104 (buffer-substring (1- (point)) (point))
15105 (if (> (current-column) org-tags-column)
15107 (make-string (- org-tags-column (current-column)) ?\ ))))))
15108 (org-move-overlay org-tags-overlay ov-start ov-end)
15109 (save-window-excursion
15110 (if expert
15111 (set-buffer (get-buffer-create " *Org tags*"))
15112 (delete-other-windows)
15113 (split-window-vertically)
15114 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15115 (erase-buffer)
15116 (org-set-local 'org-done-keywords done-keywords)
15117 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15118 (org-fast-tag-insert "Current" current c-face "\n\n")
15119 (org-fast-tag-show-exit exit-after-next)
15120 (org-set-current-tags-overlay current ov-prefix)
15121 (setq tbl fulltable char ?a cnt 0)
15122 (while (setq e (pop tbl))
15123 (cond
15124 ((equal e '(:startgroup))
15125 (push '() groups) (setq ingroup t)
15126 (when (not (= cnt 0))
15127 (setq cnt 0)
15128 (insert "\n"))
15129 (insert "{ "))
15130 ((equal e '(:endgroup))
15131 (setq ingroup nil cnt 0)
15132 (insert "}\n"))
15134 (setq tg (car e) c2 nil)
15135 (if (cdr e)
15136 (setq c (cdr e))
15137 ;; automatically assign a character.
15138 (setq c1 (string-to-char
15139 (downcase (substring
15140 tg (if (= (string-to-char tg) ?@) 1 0)))))
15141 (if (or (rassoc c1 ntable) (rassoc c1 table))
15142 (while (or (rassoc char ntable) (rassoc char table))
15143 (setq char (1+ char)))
15144 (setq c2 c1))
15145 (setq c (or c2 char)))
15146 (if ingroup (push tg (car groups)))
15147 (setq tg (org-add-props tg nil 'face
15148 (cond
15149 ((not (assoc tg table))
15150 (org-get-todo-face tg))
15151 ((member tg current) c-face)
15152 ((member tg inherited) i-face)
15153 (t nil))))
15154 (if (and (= cnt 0) (not ingroup)) (insert " "))
15155 (insert "[" c "] " tg (make-string
15156 (- fwidth 4 (length tg)) ?\ ))
15157 (push (cons tg c) ntable)
15158 (when (= (setq cnt (1+ cnt)) ncol)
15159 (insert "\n")
15160 (if ingroup (insert " "))
15161 (setq cnt 0)))))
15162 (setq ntable (nreverse ntable))
15163 (insert "\n")
15164 (goto-char (point-min))
15165 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15166 (fit-window-to-buffer))
15167 (setq rtn
15168 (catch 'exit
15169 (while t
15170 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15171 (if groups " [!] no groups" " [!]groups")
15172 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15173 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15174 (cond
15175 ((= c ?\r) (throw 'exit t))
15176 ((= c ?!)
15177 (setq groups (not groups))
15178 (goto-char (point-min))
15179 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15180 ((= c ?\C-c)
15181 (if (not expert)
15182 (org-fast-tag-show-exit
15183 (setq exit-after-next (not exit-after-next)))
15184 (setq expert nil)
15185 (delete-other-windows)
15186 (split-window-vertically)
15187 (org-switch-to-buffer-other-window " *Org tags*")
15188 (and (fboundp 'fit-window-to-buffer)
15189 (fit-window-to-buffer))))
15190 ((or (= c ?\C-g)
15191 (and (= c ?q) (not (rassoc c ntable))))
15192 (org-detach-overlay org-tags-overlay)
15193 (setq quit-flag t))
15194 ((= c ?\ )
15195 (setq current nil)
15196 (if exit-after-next (setq exit-after-next 'now)))
15197 ((= c ?\t)
15198 (condition-case nil
15199 (setq tg (completing-read
15200 "Tag: "
15201 (or buffer-tags
15202 (with-current-buffer buf
15203 (org-get-buffer-tags)))))
15204 (quit (setq tg "")))
15205 (when (string-match "\\S-" tg)
15206 (add-to-list 'buffer-tags (list tg))
15207 (if (member tg current)
15208 (setq current (delete tg current))
15209 (push tg current)))
15210 (if exit-after-next (setq exit-after-next 'now)))
15211 ((setq e (rassoc c todo-table) tg (car e))
15212 (with-current-buffer buf
15213 (save-excursion (org-todo tg)))
15214 (if exit-after-next (setq exit-after-next 'now)))
15215 ((setq e (rassoc c ntable) tg (car e))
15216 (if (member tg current)
15217 (setq current (delete tg current))
15218 (loop for g in groups do
15219 (if (member tg g)
15220 (mapc (lambda (x)
15221 (setq current (delete x current)))
15222 g)))
15223 (push tg current))
15224 (if exit-after-next (setq exit-after-next 'now))))
15226 ;; Create a sorted list
15227 (setq current
15228 (sort current
15229 (lambda (a b)
15230 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15231 (if (eq exit-after-next 'now) (throw 'exit t))
15232 (goto-char (point-min))
15233 (beginning-of-line 2)
15234 (delete-region (point) (point-at-eol))
15235 (org-fast-tag-insert "Current" current c-face)
15236 (org-set-current-tags-overlay current ov-prefix)
15237 (while (re-search-forward
15238 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15239 (setq tg (match-string 1))
15240 (add-text-properties
15241 (match-beginning 1) (match-end 1)
15242 (list 'face
15243 (cond
15244 ((member tg current) c-face)
15245 ((member tg inherited) i-face)
15246 (t (get-text-property (match-beginning 1) 'face))))))
15247 (goto-char (point-min)))))
15248 (org-detach-overlay org-tags-overlay)
15249 (if rtn
15250 (mapconcat 'identity current ":")
15251 nil))))
15253 (defun org-get-tags-string ()
15254 "Get the TAGS string in the current headline."
15255 (unless (org-on-heading-p t)
15256 (error "Not on a heading"))
15257 (save-excursion
15258 (beginning-of-line 1)
15259 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15260 (org-match-string-no-properties 1)
15261 "")))
15263 (defun org-get-tags ()
15264 "Get the list of tags specified in the current headline."
15265 (org-split-string (org-get-tags-string) ":"))
15267 (defun org-get-buffer-tags ()
15268 "Get a table of all tags used in the buffer, for completion."
15269 (let (tags)
15270 (save-excursion
15271 (goto-char (point-min))
15272 (while (re-search-forward
15273 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15274 (when (equal (char-after (point-at-bol 0)) ?*)
15275 (mapc (lambda (x) (add-to-list 'tags x))
15276 (org-split-string (org-match-string-no-properties 1) ":")))))
15277 (mapcar 'list tags)))
15280 ;;;; Properties
15282 ;;; Setting and retrieving properties
15284 (defconst org-special-properties
15285 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15286 "TIMESTAMP" "TIMESTAMP_IA")
15287 "The special properties valid in Org-mode.
15289 These are properties that are not defined in the property drawer,
15290 but in some other way.")
15292 (defconst org-default-properties
15293 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15294 "LOCATION" "LOGGING" "COLUMNS")
15295 "Some properties that are used by Org-mode for various purposes.
15296 Being in this list makes sure that they are offered for completion.")
15298 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15299 "Regular expression matching the first line of a property drawer.")
15301 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15302 "Regular expression matching the first line of a property drawer.")
15304 (defun org-property-action ()
15305 "Do an action on properties."
15306 (interactive)
15307 (let (c)
15308 (org-at-property-p)
15309 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15310 (setq c (read-char-exclusive))
15311 (cond
15312 ((equal c ?s)
15313 (call-interactively 'org-set-property))
15314 ((equal c ?d)
15315 (call-interactively 'org-delete-property))
15316 ((equal c ?D)
15317 (call-interactively 'org-delete-property-globally))
15318 ((equal c ?c)
15319 (call-interactively 'org-compute-property-at-point))
15320 (t (error "No such property action %c" c)))))
15322 (defun org-at-property-p ()
15323 "Is the cursor in a property line?"
15324 ;; FIXME: Does not check if we are actually in the drawer.
15325 ;; FIXME: also returns true on any drawers.....
15326 ;; This is used by C-c C-c for property action.
15327 (save-excursion
15328 (beginning-of-line 1)
15329 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15331 (defmacro org-with-point-at (pom &rest body)
15332 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15333 (declare (indent 1) (debug t))
15334 `(save-excursion
15335 (if (markerp pom) (set-buffer (marker-buffer pom)))
15336 (save-excursion
15337 (goto-char (or pom (point)))
15338 ,@body)))
15340 (defun org-get-property-block (&optional beg end force)
15341 "Return the (beg . end) range of the body of the property drawer.
15342 BEG and END can be beginning and end of subtree, if not given
15343 they will be found.
15344 If the drawer does not exist and FORCE is non-nil, create the drawer."
15345 (catch 'exit
15346 (save-excursion
15347 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15348 (end (or end (progn (outline-next-heading) (point)))))
15349 (goto-char beg)
15350 (if (re-search-forward org-property-start-re end t)
15351 (setq beg (1+ (match-end 0)))
15352 (if force
15353 (save-excursion
15354 (org-insert-property-drawer)
15355 (setq end (progn (outline-next-heading) (point))))
15356 (throw 'exit nil))
15357 (goto-char beg)
15358 (if (re-search-forward org-property-start-re end t)
15359 (setq beg (1+ (match-end 0)))))
15360 (if (re-search-forward org-property-end-re end t)
15361 (setq end (match-beginning 0))
15362 (or force (throw 'exit nil))
15363 (goto-char beg)
15364 (setq end beg)
15365 (org-indent-line-function)
15366 (insert ":END:\n"))
15367 (cons beg end)))))
15369 (defun org-entry-properties (&optional pom which)
15370 "Get all properties of the entry at point-or-marker POM.
15371 This includes the TODO keyword, the tags, time strings for deadline,
15372 scheduled, and clocking, and any additional properties defined in the
15373 entry. The return value is an alist, keys may occur multiple times
15374 if the property key was used several times.
15375 POM may also be nil, in which case the current entry is used.
15376 If WHICH is nil or `all', get all properties. If WHICH is
15377 `special' or `standard', only get that subclass."
15378 (setq which (or which 'all))
15379 (org-with-point-at pom
15380 (let ((clockstr (substring org-clock-string 0 -1))
15381 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15382 beg end range props sum-props key value string)
15383 (save-excursion
15384 (when (condition-case nil (org-back-to-heading t) (error nil))
15385 (setq beg (point))
15386 (setq sum-props (get-text-property (point) 'org-summaries))
15387 (outline-next-heading)
15388 (setq end (point))
15389 (when (memq which '(all special))
15390 ;; Get the special properties, like TODO and tags
15391 (goto-char beg)
15392 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15393 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15394 (when (looking-at org-priority-regexp)
15395 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15396 (when (and (setq value (org-get-tags-string))
15397 (string-match "\\S-" value))
15398 (push (cons "TAGS" value) props))
15399 (when (setq value (org-get-tags-at))
15400 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15401 props))
15402 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15403 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15404 string (if (equal key clockstr)
15405 (org-no-properties
15406 (org-trim
15407 (buffer-substring
15408 (match-beginning 3) (goto-char (point-at-eol)))))
15409 (substring (org-match-string-no-properties 3) 1 -1)))
15410 (unless key
15411 (if (= (char-after (match-beginning 3)) ?\[)
15412 (setq key "TIMESTAMP_IA")
15413 (setq key "TIMESTAMP")))
15414 (when (or (equal key clockstr) (not (assoc key props)))
15415 (push (cons key string) props)))
15419 (when (memq which '(all standard))
15420 ;; Get the standard properties, like :PORP: ...
15421 (setq range (org-get-property-block beg end))
15422 (when range
15423 (goto-char (car range))
15424 (while (re-search-forward
15425 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15426 (cdr range) t)
15427 (setq key (org-match-string-no-properties 1)
15428 value (org-trim (or (org-match-string-no-properties 2) "")))
15429 (unless (member key excluded)
15430 (push (cons key (or value "")) props)))))
15431 (append sum-props (nreverse props)))))))
15433 (defun org-entry-get (pom property &optional inherit)
15434 "Get value of PROPERTY for entry at point-or-marker POM.
15435 If INHERIT is non-nil and the entry does not have the property,
15436 then also check higher levels of the hierarchy.
15437 If the property is present but empty, the return value is the empty string.
15438 If the property is not present at all, nil is returned."
15439 (org-with-point-at pom
15440 (if inherit
15441 (org-entry-get-with-inheritance property)
15442 (if (member property org-special-properties)
15443 ;; We need a special property. Use brute force, get all properties.
15444 (cdr (assoc property (org-entry-properties nil 'special)))
15445 (let ((range (org-get-property-block)))
15446 (if (and range
15447 (goto-char (car range))
15448 (re-search-forward
15449 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15450 (cdr range) t))
15451 ;; Found the property, return it.
15452 (if (match-end 1)
15453 (org-match-string-no-properties 1)
15454 "")))))))
15456 (defun org-entry-delete (pom property)
15457 "Delete the property PROPERTY from entry at point-or-marker POM."
15458 (org-with-point-at pom
15459 (if (member property org-special-properties)
15460 nil ; cannot delete these properties.
15461 (let ((range (org-get-property-block)))
15462 (if (and range
15463 (goto-char (car range))
15464 (re-search-forward
15465 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15466 (cdr range) t))
15467 (progn
15468 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15470 nil)))))
15472 ;; Multi-values properties are properties that contain multiple values
15473 ;; These values are assumed to be single words, separated by whitespace.
15474 (defun org-entry-add-to-multivalued-property (pom property value)
15475 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15476 (let* ((old (org-entry-get pom property))
15477 (values (and old (org-split-string old "[ \t]"))))
15478 (unless (member value values)
15479 (setq values (cons value values))
15480 (org-entry-put pom property
15481 (mapconcat 'identity values " ")))))
15483 (defun org-entry-remove-from-multivalued-property (pom property value)
15484 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15485 (let* ((old (org-entry-get pom property))
15486 (values (and old (org-split-string old "[ \t]"))))
15487 (when (member value values)
15488 (setq values (delete value values))
15489 (org-entry-put pom property
15490 (mapconcat 'identity values " ")))))
15492 (defun org-entry-member-in-multivalued-property (pom property value)
15493 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15494 (let* ((old (org-entry-get pom property))
15495 (values (and old (org-split-string old "[ \t]"))))
15496 (member value values)))
15498 (defvar org-entry-property-inherited-from (make-marker))
15500 (defun org-entry-get-with-inheritance (property)
15501 "Get entry property, and search higher levels if not present."
15502 (let (tmp)
15503 (save-excursion
15504 (save-restriction
15505 (widen)
15506 (catch 'ex
15507 (while t
15508 (when (setq tmp (org-entry-get nil property))
15509 (org-back-to-heading t)
15510 (move-marker org-entry-property-inherited-from (point))
15511 (throw 'ex tmp))
15512 (or (org-up-heading-safe) (throw 'ex nil)))))
15513 (or tmp (cdr (assoc property org-local-properties))
15514 (cdr (assoc property org-global-properties))))))
15516 (defun org-entry-put (pom property value)
15517 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15518 (org-with-point-at pom
15519 (org-back-to-heading t)
15520 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15521 range)
15522 (cond
15523 ((equal property "TODO")
15524 (when (and (stringp value) (string-match "\\S-" value)
15525 (not (member value org-todo-keywords-1)))
15526 (error "\"%s\" is not a valid TODO state" value))
15527 (if (or (not value)
15528 (not (string-match "\\S-" value)))
15529 (setq value 'none))
15530 (org-todo value)
15531 (org-set-tags nil 'align))
15532 ((equal property "PRIORITY")
15533 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15534 (string-to-char value) ?\ ))
15535 (org-set-tags nil 'align))
15536 ((equal property "SCHEDULED")
15537 (if (re-search-forward org-scheduled-time-regexp end t)
15538 (cond
15539 ((eq value 'earlier) (org-timestamp-change -1 'day))
15540 ((eq value 'later) (org-timestamp-change 1 'day))
15541 (t (call-interactively 'org-schedule)))
15542 (call-interactively 'org-schedule)))
15543 ((equal property "DEADLINE")
15544 (if (re-search-forward org-deadline-time-regexp end t)
15545 (cond
15546 ((eq value 'earlier) (org-timestamp-change -1 'day))
15547 ((eq value 'later) (org-timestamp-change 1 'day))
15548 (t (call-interactively 'org-deadline)))
15549 (call-interactively 'org-deadline)))
15550 ((member property org-special-properties)
15551 (error "The %s property can not yet be set with `org-entry-put'"
15552 property))
15553 (t ; a non-special property
15554 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15555 (setq range (org-get-property-block beg end 'force))
15556 (goto-char (car range))
15557 (if (re-search-forward
15558 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15559 (progn
15560 (delete-region (match-beginning 1) (match-end 1))
15561 (goto-char (match-beginning 1)))
15562 (goto-char (cdr range))
15563 (insert "\n")
15564 (backward-char 1)
15565 (org-indent-line-function)
15566 (insert ":" property ":"))
15567 (and value (insert " " value))
15568 (org-indent-line-function)))))))
15570 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15571 "Get all property keys in the current buffer.
15572 With INCLUDE-SPECIALS, also list the special properties that relect things
15573 like tags and TODO state.
15574 With INCLUDE-DEFAULTS, also include properties that has special meaning
15575 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15576 (let (rtn range)
15577 (save-excursion
15578 (save-restriction
15579 (widen)
15580 (goto-char (point-min))
15581 (while (re-search-forward org-property-start-re nil t)
15582 (setq range (org-get-property-block))
15583 (goto-char (car range))
15584 (while (re-search-forward
15585 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15586 (cdr range) t)
15587 (add-to-list 'rtn (org-match-string-no-properties 1)))
15588 (outline-next-heading))))
15590 (when include-specials
15591 (setq rtn (append org-special-properties rtn)))
15593 (when include-defaults
15594 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15596 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15598 (defun org-property-values (key)
15599 "Return a list of all values of property KEY."
15600 (save-excursion
15601 (save-restriction
15602 (widen)
15603 (goto-char (point-min))
15604 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15605 values)
15606 (while (re-search-forward re nil t)
15607 (add-to-list 'values (org-trim (match-string 1))))
15608 (delete "" values)))))
15610 (defun org-insert-property-drawer ()
15611 "Insert a property drawer into the current entry."
15612 (interactive)
15613 (org-back-to-heading t)
15614 (looking-at outline-regexp)
15615 (let ((indent (- (match-end 0)(match-beginning 0)))
15616 (beg (point))
15617 (re (concat "^[ \t]*" org-keyword-time-regexp))
15618 end hiddenp)
15619 (outline-next-heading)
15620 (setq end (point))
15621 (goto-char beg)
15622 (while (re-search-forward re end t))
15623 (setq hiddenp (org-invisible-p))
15624 (end-of-line 1)
15625 (and (equal (char-after) ?\n) (forward-char 1))
15626 (org-skip-over-state-notes)
15627 (skip-chars-backward " \t\n\r")
15628 (if (eq (char-before) ?*) (forward-char 1))
15629 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15630 (beginning-of-line 0)
15631 (indent-to-column indent)
15632 (beginning-of-line 2)
15633 (indent-to-column indent)
15634 (beginning-of-line 0)
15635 (if hiddenp
15636 (save-excursion
15637 (org-back-to-heading t)
15638 (hide-entry))
15639 (org-flag-drawer t))))
15641 (defun org-set-property (property value)
15642 "In the current entry, set PROPERTY to VALUE.
15643 When called interactively, this will prompt for a property name, offering
15644 completion on existing and default properties. And then it will prompt
15645 for a value, offering competion either on allowed values (via an inherited
15646 xxx_ALL property) or on existing values in other instances of this property
15647 in the current file."
15648 (interactive
15649 (let* ((prop (completing-read
15650 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15651 (cur (org-entry-get nil prop))
15652 (allowed (org-property-get-allowed-values nil prop 'table))
15653 (existing (mapcar 'list (org-property-values prop)))
15654 (val (if allowed
15655 (completing-read "Value: " allowed nil 'req-match)
15656 (completing-read
15657 (concat "Value" (if (and cur (string-match "\\S-" cur))
15658 (concat "[" cur "]") "")
15659 ": ")
15660 existing nil nil "" nil cur))))
15661 (list prop (if (equal val "") cur val))))
15662 (unless (equal (org-entry-get nil property) value)
15663 (org-entry-put nil property value)))
15665 (defun org-delete-property (property)
15666 "In the current entry, delete PROPERTY."
15667 (interactive
15668 (let* ((prop (completing-read
15669 "Property: " (org-entry-properties nil 'standard))))
15670 (list prop)))
15671 (message (concat "Property " property
15672 (if (org-entry-delete nil property)
15673 " deleted"
15674 " was not present in the entry"))))
15676 (defun org-delete-property-globally (property)
15677 "Remove PROPERTY globally, from all entries."
15678 (interactive
15679 (let* ((prop (completing-read
15680 "Globally remove property: "
15681 (mapcar 'list (org-buffer-property-keys)))))
15682 (list prop)))
15683 (save-excursion
15684 (save-restriction
15685 (widen)
15686 (goto-char (point-min))
15687 (let ((cnt 0))
15688 (while (re-search-forward
15689 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15690 nil t)
15691 (setq cnt (1+ cnt))
15692 (replace-match ""))
15693 (message "Property \"%s\" removed from %d entries" property cnt)))))
15695 (defvar org-columns-current-fmt-compiled) ; defined below
15697 (defun org-compute-property-at-point ()
15698 "Compute the property at point.
15699 This looks for an enclosing column format, extracts the operator and
15700 then applies it to the proerty in the column format's scope."
15701 (interactive)
15702 (unless (org-at-property-p)
15703 (error "Not at a property"))
15704 (let ((prop (org-match-string-no-properties 2)))
15705 (org-columns-get-format-and-top-level)
15706 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15707 (error "No operator defined for property %s" prop))
15708 (org-columns-compute prop)))
15710 (defun org-property-get-allowed-values (pom property &optional table)
15711 "Get allowed values for the property PROPERTY.
15712 When TABLE is non-nil, return an alist that can directly be used for
15713 completion."
15714 (let (vals)
15715 (cond
15716 ((equal property "TODO")
15717 (setq vals (org-with-point-at pom
15718 (append org-todo-keywords-1 '("")))))
15719 ((equal property "PRIORITY")
15720 (let ((n org-lowest-priority))
15721 (while (>= n org-highest-priority)
15722 (push (char-to-string n) vals)
15723 (setq n (1- n)))))
15724 ((member property org-special-properties))
15726 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15728 (when (and vals (string-match "\\S-" vals))
15729 (setq vals (car (read-from-string (concat "(" vals ")"))))
15730 (setq vals (mapcar (lambda (x)
15731 (cond ((stringp x) x)
15732 ((numberp x) (number-to-string x))
15733 ((symbolp x) (symbol-name x))
15734 (t "???")))
15735 vals)))))
15736 (if table (mapcar 'list vals) vals)))
15738 (defun org-property-previous-allowed-value (&optional previous)
15739 "Switch to the next allowed value for this property."
15740 (interactive)
15741 (org-property-next-allowed-value t))
15743 (defun org-property-next-allowed-value (&optional previous)
15744 "Switch to the next allowed value for this property."
15745 (interactive)
15746 (unless (org-at-property-p)
15747 (error "Not at a property"))
15748 (let* ((key (match-string 2))
15749 (value (match-string 3))
15750 (allowed (or (org-property-get-allowed-values (point) key)
15751 (and (member value '("[ ]" "[-]" "[X]"))
15752 '("[ ]" "[X]"))))
15753 nval)
15754 (unless allowed
15755 (error "Allowed values for this property have not been defined"))
15756 (if previous (setq allowed (reverse allowed)))
15757 (if (member value allowed)
15758 (setq nval (car (cdr (member value allowed)))))
15759 (setq nval (or nval (car allowed)))
15760 (if (equal nval value)
15761 (error "Only one allowed value for this property"))
15762 (org-at-property-p)
15763 (replace-match (concat " :" key ": " nval) t t)
15764 (org-indent-line-function)
15765 (beginning-of-line 1)
15766 (skip-chars-forward " \t")))
15768 (defun org-find-entry-with-id (ident)
15769 "Locate the entry that contains the ID property with exact value IDENT.
15770 IDENT can be a string, a symbol or a number, this function will search for
15771 the string representation of it.
15772 Return the position where this entry starts, or nil if there is no such entry."
15773 (let ((id (cond
15774 ((stringp ident) ident)
15775 ((symbol-name ident) (symbol-name ident))
15776 ((numberp ident) (number-to-string ident))
15777 (t (error "IDENT %s must be a string, symbol or number" ident))))
15778 (case-fold-search nil))
15779 (save-excursion
15780 (save-restriction
15781 (goto-char (point-min))
15782 (when (re-search-forward
15783 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15784 nil t)
15785 (org-back-to-heading)
15786 (point))))))
15788 ;;; Column View
15790 (defvar org-columns-overlays nil
15791 "Holds the list of current column overlays.")
15793 (defvar org-columns-current-fmt nil
15794 "Local variable, holds the currently active column format.")
15795 (defvar org-columns-current-fmt-compiled nil
15796 "Local variable, holds the currently active column format.
15797 This is the compiled version of the format.")
15798 (defvar org-columns-current-widths nil
15799 "Loval variable, holds the currently widths of fields.")
15800 (defvar org-columns-current-maxwidths nil
15801 "Loval variable, holds the currently active maximum column widths.")
15802 (defvar org-columns-begin-marker (make-marker)
15803 "Points to the position where last a column creation command was called.")
15804 (defvar org-columns-top-level-marker (make-marker)
15805 "Points to the position where current columns region starts.")
15807 (defvar org-columns-map (make-sparse-keymap)
15808 "The keymap valid in column display.")
15810 (defun org-columns-content ()
15811 "Switch to contents view while in columns view."
15812 (interactive)
15813 (org-overview)
15814 (org-content))
15816 (org-defkey org-columns-map "c" 'org-columns-content)
15817 (org-defkey org-columns-map "o" 'org-overview)
15818 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15819 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15820 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15821 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15822 (org-defkey org-columns-map "v" 'org-columns-show-value)
15823 (org-defkey org-columns-map "q" 'org-columns-quit)
15824 (org-defkey org-columns-map "r" 'org-columns-redo)
15825 (org-defkey org-columns-map [left] 'backward-char)
15826 (org-defkey org-columns-map "\M-b" 'backward-char)
15827 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15828 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15829 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15830 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15831 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15832 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15833 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15834 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15835 (org-defkey org-columns-map "<" 'org-columns-narrow)
15836 (org-defkey org-columns-map ">" 'org-columns-widen)
15837 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15838 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15839 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15840 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15842 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15843 '("Column"
15844 ["Edit property" org-columns-edit-value t]
15845 ["Next allowed value" org-columns-next-allowed-value t]
15846 ["Previous allowed value" org-columns-previous-allowed-value t]
15847 ["Show full value" org-columns-show-value t]
15848 ["Edit allowed values" org-columns-edit-allowed t]
15849 "--"
15850 ["Edit column attributes" org-columns-edit-attributes t]
15851 ["Increase column width" org-columns-widen t]
15852 ["Decrease column width" org-columns-narrow t]
15853 "--"
15854 ["Move column right" org-columns-move-right t]
15855 ["Move column left" org-columns-move-left t]
15856 ["Add column" org-columns-new t]
15857 ["Delete column" org-columns-delete t]
15858 "--"
15859 ["CONTENTS" org-columns-content t]
15860 ["OVERVIEW" org-overview t]
15861 ["Refresh columns display" org-columns-redo t]
15862 "--"
15863 ["Open link" org-columns-open-link t]
15864 "--"
15865 ["Quit" org-columns-quit t]))
15867 (defun org-columns-new-overlay (beg end &optional string face)
15868 "Create a new column overlay and add it to the list."
15869 (let ((ov (org-make-overlay beg end)))
15870 (org-overlay-put ov 'face (or face 'secondary-selection))
15871 (org-overlay-display ov string face)
15872 (push ov org-columns-overlays)
15873 ov))
15875 (defun org-columns-display-here (&optional props)
15876 "Overlay the current line with column display."
15877 (interactive)
15878 (let* ((fmt org-columns-current-fmt-compiled)
15879 (beg (point-at-bol))
15880 (level-face (save-excursion
15881 (beginning-of-line 1)
15882 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15883 (org-get-level-face 2))))
15884 (color (list :foreground
15885 (face-attribute (or level-face 'default) :foreground)))
15886 props pom property ass width f string ov column val modval)
15887 ;; Check if the entry is in another buffer.
15888 (unless props
15889 (if (eq major-mode 'org-agenda-mode)
15890 (setq pom (or (get-text-property (point) 'org-hd-marker)
15891 (get-text-property (point) 'org-marker))
15892 props (if pom (org-entry-properties pom) nil))
15893 (setq props (org-entry-properties nil))))
15894 ;; Walk the format
15895 (while (setq column (pop fmt))
15896 (setq property (car column)
15897 ass (if (equal property "ITEM")
15898 (cons "ITEM"
15899 (save-match-data
15900 (org-no-properties
15901 (org-remove-tabs
15902 (buffer-substring-no-properties
15903 (point-at-bol) (point-at-eol))))))
15904 (assoc property props))
15905 width (or (cdr (assoc property org-columns-current-maxwidths))
15906 (nth 2 column)
15907 (length property))
15908 f (format "%%-%d.%ds | " width width)
15909 val (or (cdr ass) "")
15910 modval (if (equal property "ITEM")
15911 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15912 string (format f (or modval val)))
15913 ;; Create the overlay
15914 (org-unmodified
15915 (setq ov (org-columns-new-overlay
15916 beg (setq beg (1+ beg)) string
15917 (list color 'org-column)))
15918 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15919 (org-overlay-put ov 'keymap org-columns-map)
15920 (org-overlay-put ov 'org-columns-key property)
15921 (org-overlay-put ov 'org-columns-value (cdr ass))
15922 (org-overlay-put ov 'org-columns-value-modified modval)
15923 (org-overlay-put ov 'org-columns-pom pom)
15924 (org-overlay-put ov 'org-columns-format f))
15925 (if (or (not (char-after beg))
15926 (equal (char-after beg) ?\n))
15927 (let ((inhibit-read-only t))
15928 (save-excursion
15929 (goto-char beg)
15930 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15931 ;; Make the rest of the line disappear.
15932 (org-unmodified
15933 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15934 (org-overlay-put ov 'invisible t)
15935 (org-overlay-put ov 'keymap org-columns-map)
15936 (org-overlay-put ov 'intangible t)
15937 (push ov org-columns-overlays)
15938 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15939 (org-overlay-put ov 'keymap org-columns-map)
15940 (push ov org-columns-overlays)
15941 (let ((inhibit-read-only t))
15942 (put-text-property (max (point-min) (1- (point-at-bol)))
15943 (min (point-max) (1+ (point-at-eol)))
15944 'read-only "Type `e' to edit property")))))
15946 (defvar org-previous-header-line-format nil
15947 "The header line format before column view was turned on.")
15948 (defvar org-columns-inhibit-recalculation nil
15949 "Inhibit recomputing of columns on column view startup.")
15952 (defvar header-line-format)
15953 (defun org-columns-display-here-title ()
15954 "Overlay the newline before the current line with the table title."
15955 (interactive)
15956 (let ((fmt org-columns-current-fmt-compiled)
15957 string (title "")
15958 property width f column str widths)
15959 (while (setq column (pop fmt))
15960 (setq property (car column)
15961 str (or (nth 1 column) property)
15962 width (or (cdr (assoc property org-columns-current-maxwidths))
15963 (nth 2 column)
15964 (length str))
15965 widths (push width widths)
15966 f (format "%%-%d.%ds | " width width)
15967 string (format f str)
15968 title (concat title string)))
15969 (setq title (concat
15970 (org-add-props " " nil 'display '(space :align-to 0))
15971 (org-add-props title nil 'face '(:weight bold :underline t))))
15972 (org-set-local 'org-previous-header-line-format header-line-format)
15973 (org-set-local 'org-columns-current-widths (nreverse widths))
15974 (setq header-line-format title)))
15976 (defun org-columns-remove-overlays ()
15977 "Remove all currently active column overlays."
15978 (interactive)
15979 (when (marker-buffer org-columns-begin-marker)
15980 (with-current-buffer (marker-buffer org-columns-begin-marker)
15981 (when (local-variable-p 'org-previous-header-line-format)
15982 (setq header-line-format org-previous-header-line-format)
15983 (kill-local-variable 'org-previous-header-line-format))
15984 (move-marker org-columns-begin-marker nil)
15985 (move-marker org-columns-top-level-marker nil)
15986 (org-unmodified
15987 (mapc 'org-delete-overlay org-columns-overlays)
15988 (setq org-columns-overlays nil)
15989 (let ((inhibit-read-only t))
15990 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15992 (defun org-columns-cleanup-item (item fmt)
15993 "Remove from ITEM what is a column in the format FMT."
15994 (if (not org-complex-heading-regexp)
15995 item
15996 (when (string-match org-complex-heading-regexp item)
15997 (concat
15998 (org-add-props (concat (match-string 1 item) " ") nil
15999 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16000 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16001 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16002 " " (match-string 4 item)
16003 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16005 (defun org-columns-show-value ()
16006 "Show the full value of the property."
16007 (interactive)
16008 (let ((value (get-char-property (point) 'org-columns-value)))
16009 (message "Value is: %s" (or value ""))))
16011 (defun org-columns-quit ()
16012 "Remove the column overlays and in this way exit column editing."
16013 (interactive)
16014 (org-unmodified
16015 (org-columns-remove-overlays)
16016 (let ((inhibit-read-only t))
16017 (remove-text-properties (point-min) (point-max) '(read-only t))))
16018 (when (eq major-mode 'org-agenda-mode)
16019 (message
16020 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16022 (defun org-columns-check-computed ()
16023 "Check if this column value is computed.
16024 If yes, throw an error indicating that changing it does not make sense."
16025 (let ((val (get-char-property (point) 'org-columns-value)))
16026 (when (and (stringp val)
16027 (get-char-property 0 'org-computed val))
16028 (error "This value is computed from the entry's children"))))
16030 (defun org-columns-todo (&optional arg)
16031 "Change the TODO state during column view."
16032 (interactive "P")
16033 (org-columns-edit-value "TODO"))
16035 (defun org-columns-set-tags-or-toggle (&optional arg)
16036 "Toggle checkbox at point, or set tags for current headline."
16037 (interactive "P")
16038 (if (string-match "\\`\\[[ xX-]\\]\\'"
16039 (get-char-property (point) 'org-columns-value))
16040 (org-columns-next-allowed-value)
16041 (org-columns-edit-value "TAGS")))
16043 (defun org-columns-edit-value (&optional key)
16044 "Edit the value of the property at point in column view.
16045 Where possible, use the standard interface for changing this line."
16046 (interactive)
16047 (org-columns-check-computed)
16048 (let* ((external-key key)
16049 (col (current-column))
16050 (key (or key (get-char-property (point) 'org-columns-key)))
16051 (value (get-char-property (point) 'org-columns-value))
16052 (bol (point-at-bol)) (eol (point-at-eol))
16053 (pom (or (get-text-property bol 'org-hd-marker)
16054 (point))) ; keep despite of compiler waring
16055 (line-overlays
16056 (delq nil (mapcar (lambda (x)
16057 (and (eq (overlay-buffer x) (current-buffer))
16058 (>= (overlay-start x) bol)
16059 (<= (overlay-start x) eol)
16061 org-columns-overlays)))
16062 nval eval allowed)
16063 (cond
16064 ((equal key "ITEM")
16065 (setq eval '(org-with-point-at pom
16066 (org-edit-headline))))
16067 ((equal key "TODO")
16068 (setq eval '(org-with-point-at pom
16069 (let ((current-prefix-arg
16070 (if external-key current-prefix-arg '(4))))
16071 (call-interactively 'org-todo)))))
16072 ((equal key "PRIORITY")
16073 (setq eval '(org-with-point-at pom
16074 (call-interactively 'org-priority))))
16075 ((equal key "TAGS")
16076 (setq eval '(org-with-point-at pom
16077 (let ((org-fast-tag-selection-single-key
16078 (if (eq org-fast-tag-selection-single-key 'expert)
16079 t org-fast-tag-selection-single-key)))
16080 (call-interactively 'org-set-tags)))))
16081 ((equal key "DEADLINE")
16082 (setq eval '(org-with-point-at pom
16083 (call-interactively 'org-deadline))))
16084 ((equal key "SCHEDULED")
16085 (setq eval '(org-with-point-at pom
16086 (call-interactively 'org-schedule))))
16088 (setq allowed (org-property-get-allowed-values pom key 'table))
16089 (if allowed
16090 (setq nval (completing-read "Value: " allowed nil t))
16091 (setq nval (read-string "Edit: " value)))
16092 (setq nval (org-trim nval))
16093 (when (not (equal nval value))
16094 (setq eval '(org-entry-put pom key nval)))))
16095 (when eval
16096 (let ((inhibit-read-only t))
16097 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16098 (unwind-protect
16099 (progn
16100 (setq org-columns-overlays
16101 (org-delete-all line-overlays org-columns-overlays))
16102 (mapc 'org-delete-overlay line-overlays)
16103 (org-columns-eval eval))
16104 (org-columns-display-here))))
16105 (move-to-column col)
16106 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16107 (org-columns-update key))))
16109 (defun org-edit-headline () ; FIXME: this is not columns specific
16110 "Edit the current headline, the part without TODO keyword, TAGS."
16111 (org-back-to-heading)
16112 (when (looking-at org-todo-line-regexp)
16113 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16114 (txt (match-string 3))
16115 (post "")
16116 txt2)
16117 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16118 (setq post (match-string 0 txt)
16119 txt (substring txt 0 (match-beginning 0))))
16120 (setq txt2 (read-string "Edit: " txt))
16121 (when (not (equal txt txt2))
16122 (beginning-of-line 1)
16123 (insert pre txt2 post)
16124 (delete-region (point) (point-at-eol))
16125 (org-set-tags nil t)))))
16127 (defun org-columns-edit-allowed ()
16128 "Edit the list of allowed values for the current property."
16129 (interactive)
16130 (let* ((key (get-char-property (point) 'org-columns-key))
16131 (key1 (concat key "_ALL"))
16132 (allowed (org-entry-get (point) key1 t))
16133 nval)
16134 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16135 (setq nval (read-string "Allowed: " allowed))
16136 (org-entry-put
16137 (cond ((marker-position org-entry-property-inherited-from)
16138 org-entry-property-inherited-from)
16139 ((marker-position org-columns-top-level-marker)
16140 org-columns-top-level-marker))
16141 key1 nval)))
16143 (defmacro org-no-warnings (&rest body)
16144 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16146 (defun org-columns-eval (form)
16147 (let (hidep)
16148 (save-excursion
16149 (beginning-of-line 1)
16150 ;; `next-line' is needed here, because it skips invisible line.
16151 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16152 (setq hidep (org-on-heading-p 1)))
16153 (eval form)
16154 (and hidep (hide-entry))))
16156 (defun org-columns-previous-allowed-value ()
16157 "Switch to the previous allowed value for this column."
16158 (interactive)
16159 (org-columns-next-allowed-value t))
16161 (defun org-columns-next-allowed-value (&optional previous)
16162 "Switch to the next allowed value for this column."
16163 (interactive)
16164 (org-columns-check-computed)
16165 (let* ((col (current-column))
16166 (key (get-char-property (point) 'org-columns-key))
16167 (value (get-char-property (point) 'org-columns-value))
16168 (bol (point-at-bol)) (eol (point-at-eol))
16169 (pom (or (get-text-property bol 'org-hd-marker)
16170 (point))) ; keep despite of compiler waring
16171 (line-overlays
16172 (delq nil (mapcar (lambda (x)
16173 (and (eq (overlay-buffer x) (current-buffer))
16174 (>= (overlay-start x) bol)
16175 (<= (overlay-start x) eol)
16177 org-columns-overlays)))
16178 (allowed (or (org-property-get-allowed-values pom key)
16179 (and (equal
16180 (nth 4 (assoc key org-columns-current-fmt-compiled))
16181 'checkbox) '("[ ]" "[X]"))))
16182 nval)
16183 (when (equal key "ITEM")
16184 (error "Cannot edit item headline from here"))
16185 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16186 (error "Allowed values for this property have not been defined"))
16187 (if (member key '("SCHEDULED" "DEADLINE"))
16188 (setq nval (if previous 'earlier 'later))
16189 (if previous (setq allowed (reverse allowed)))
16190 (if (member value allowed)
16191 (setq nval (car (cdr (member value allowed)))))
16192 (setq nval (or nval (car allowed)))
16193 (if (equal nval value)
16194 (error "Only one allowed value for this property")))
16195 (let ((inhibit-read-only t))
16196 (remove-text-properties (1- bol) eol '(read-only t))
16197 (unwind-protect
16198 (progn
16199 (setq org-columns-overlays
16200 (org-delete-all line-overlays org-columns-overlays))
16201 (mapc 'org-delete-overlay line-overlays)
16202 (org-columns-eval '(org-entry-put pom key nval)))
16203 (org-columns-display-here)))
16204 (move-to-column col)
16205 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16206 (org-columns-update key))))
16208 (defun org-verify-version (task)
16209 (cond
16210 ((eq task 'columns)
16211 (if (or (featurep 'xemacs)
16212 (< emacs-major-version 22))
16213 (error "Emacs 22 is required for the columns feature")))))
16215 (defun org-columns-open-link (&optional arg)
16216 (interactive "P")
16217 (let ((key (get-char-property (point) 'org-columns-key))
16218 (value (get-char-property (point) 'org-columns-value)))
16219 (org-open-link-from-string arg)))
16221 (defun org-open-link-from-string (s &optional arg)
16222 "Open a link in the string S, as if it was in Org-mode."
16223 (interactive)
16224 (with-temp-buffer
16225 (let ((org-inhibit-startup t))
16226 (org-mode)
16227 (insert s)
16228 (goto-char (point-min))
16229 (org-open-at-point arg))))
16231 (defun org-columns-get-format-and-top-level ()
16232 (let (fmt)
16233 (when (condition-case nil (org-back-to-heading) (error nil))
16234 (move-marker org-entry-property-inherited-from nil)
16235 (setq fmt (org-entry-get nil "COLUMNS" t)))
16236 (setq fmt (or fmt org-columns-default-format))
16237 (org-set-local 'org-columns-current-fmt fmt)
16238 (org-columns-compile-format fmt)
16239 (if (marker-position org-entry-property-inherited-from)
16240 (move-marker org-columns-top-level-marker
16241 org-entry-property-inherited-from)
16242 (move-marker org-columns-top-level-marker (point)))
16243 fmt))
16245 (defun org-columns ()
16246 "Turn on column view on an org-mode file."
16247 (interactive)
16248 (org-verify-version 'columns)
16249 (org-columns-remove-overlays)
16250 (move-marker org-columns-begin-marker (point))
16251 (let (beg end fmt cache maxwidths)
16252 (setq fmt (org-columns-get-format-and-top-level))
16253 (save-excursion
16254 (goto-char org-columns-top-level-marker)
16255 (setq beg (point))
16256 (unless org-columns-inhibit-recalculation
16257 (org-columns-compute-all))
16258 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16259 (point-max)))
16260 (goto-char beg)
16261 ;; Get and cache the properties
16262 (while (re-search-forward (concat "^" outline-regexp) end t)
16263 (push (cons (org-current-line) (org-entry-properties)) cache))
16264 (when cache
16265 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16266 (org-set-local 'org-columns-current-maxwidths maxwidths)
16267 (org-columns-display-here-title)
16268 (mapc (lambda (x)
16269 (goto-line (car x))
16270 (org-columns-display-here (cdr x)))
16271 cache)))))
16273 (defun org-columns-new (&optional prop title width op fmt)
16274 "Insert a new column, to the leeft o the current column."
16275 (interactive)
16276 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16277 cell)
16278 (setq prop (completing-read
16279 "Property: " (mapcar 'list (org-buffer-property-keys t))
16280 nil nil prop))
16281 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16282 (setq width (read-string "Column width: " (if width (number-to-string width))))
16283 (if (string-match "\\S-" width)
16284 (setq width (string-to-number width))
16285 (setq width nil))
16286 (setq fmt (completing-read "Summary [none]: "
16287 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16288 nil t))
16289 (if (string-match "\\S-" fmt)
16290 (setq fmt (intern fmt))
16291 (setq fmt nil))
16292 (if (eq fmt 'none) (setq fmt nil))
16293 (if editp
16294 (progn
16295 (setcar editp prop)
16296 (setcdr editp (list title width nil fmt)))
16297 (setq cell (nthcdr (1- (current-column))
16298 org-columns-current-fmt-compiled))
16299 (setcdr cell (cons (list prop title width nil fmt)
16300 (cdr cell))))
16301 (org-columns-store-format)
16302 (org-columns-redo)))
16304 (defun org-columns-delete ()
16305 "Delete the column at point from columns view."
16306 (interactive)
16307 (let* ((n (current-column))
16308 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16309 (when (y-or-n-p
16310 (format "Are you sure you want to remove column \"%s\"? " title))
16311 (setq org-columns-current-fmt-compiled
16312 (delq (nth n org-columns-current-fmt-compiled)
16313 org-columns-current-fmt-compiled))
16314 (org-columns-store-format)
16315 (org-columns-redo)
16316 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16317 (backward-char 1)))))
16319 (defun org-columns-edit-attributes ()
16320 "Edit the attributes of the current column."
16321 (interactive)
16322 (let* ((n (current-column))
16323 (info (nth n org-columns-current-fmt-compiled)))
16324 (apply 'org-columns-new info)))
16326 (defun org-columns-widen (arg)
16327 "Make the column wider by ARG characters."
16328 (interactive "p")
16329 (let* ((n (current-column))
16330 (entry (nth n org-columns-current-fmt-compiled))
16331 (width (or (nth 2 entry)
16332 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16333 (setq width (max 1 (+ width arg)))
16334 (setcar (nthcdr 2 entry) width)
16335 (org-columns-store-format)
16336 (org-columns-redo)))
16338 (defun org-columns-narrow (arg)
16339 "Make the column nrrower by ARG characters."
16340 (interactive "p")
16341 (org-columns-widen (- arg)))
16343 (defun org-columns-move-right ()
16344 "Swap this column with the one to the right."
16345 (interactive)
16346 (let* ((n (current-column))
16347 (cell (nthcdr n org-columns-current-fmt-compiled))
16349 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16350 (error "Cannot shift this column further to the right"))
16351 (setq e (car cell))
16352 (setcar cell (car (cdr cell)))
16353 (setcdr cell (cons e (cdr (cdr cell))))
16354 (org-columns-store-format)
16355 (org-columns-redo)
16356 (forward-char 1)))
16358 (defun org-columns-move-left ()
16359 "Swap this column with the one to the left."
16360 (interactive)
16361 (let* ((n (current-column)))
16362 (when (= n 0)
16363 (error "Cannot shift this column further to the left"))
16364 (backward-char 1)
16365 (org-columns-move-right)
16366 (backward-char 1)))
16368 (defun org-columns-store-format ()
16369 "Store the text version of the current columns format in appropriate place.
16370 This is either in the COLUMNS property of the node starting the current column
16371 display, or in the #+COLUMNS line of the current buffer."
16372 (let (fmt (cnt 0))
16373 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16374 (org-set-local 'org-columns-current-fmt fmt)
16375 (if (marker-position org-columns-top-level-marker)
16376 (save-excursion
16377 (goto-char org-columns-top-level-marker)
16378 (if (and (org-at-heading-p)
16379 (org-entry-get nil "COLUMNS"))
16380 (org-entry-put nil "COLUMNS" fmt)
16381 (goto-char (point-min))
16382 ;; Overwrite all #+COLUMNS lines....
16383 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16384 (setq cnt (1+ cnt))
16385 (replace-match (concat "#+COLUMNS: " fmt) t t))
16386 (unless (> cnt 0)
16387 (goto-char (point-min))
16388 (or (org-on-heading-p t) (outline-next-heading))
16389 (let ((inhibit-read-only t))
16390 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16391 (org-set-local 'org-columns-default-format fmt))))))
16393 (defvar org-overriding-columns-format nil
16394 "When set, overrides any other definition.")
16395 (defvar org-agenda-view-columns-initially nil
16396 "When set, switch to columns view immediately after creating the agenda.")
16398 (defun org-agenda-columns ()
16399 "Turn on column view in the agenda."
16400 (interactive)
16401 (org-verify-version 'columns)
16402 (org-columns-remove-overlays)
16403 (move-marker org-columns-begin-marker (point))
16404 (let (fmt cache maxwidths m)
16405 (cond
16406 ((and (local-variable-p 'org-overriding-columns-format)
16407 org-overriding-columns-format)
16408 (setq fmt org-overriding-columns-format))
16409 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16410 (setq fmt (org-entry-get m "COLUMNS" t)))
16411 ((and (boundp 'org-columns-current-fmt)
16412 (local-variable-p 'org-columns-current-fmt)
16413 org-columns-current-fmt)
16414 (setq fmt org-columns-current-fmt))
16415 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16416 (setq m (get-text-property m 'org-hd-marker))
16417 (setq fmt (org-entry-get m "COLUMNS" t))))
16418 (setq fmt (or fmt org-columns-default-format))
16419 (org-set-local 'org-columns-current-fmt fmt)
16420 (org-columns-compile-format fmt)
16421 (save-excursion
16422 ;; Get and cache the properties
16423 (goto-char (point-min))
16424 (while (not (eobp))
16425 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16426 (get-text-property (point) 'org-marker)))
16427 (push (cons (org-current-line) (org-entry-properties m)) cache))
16428 (beginning-of-line 2))
16429 (when cache
16430 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16431 (org-set-local 'org-columns-current-maxwidths maxwidths)
16432 (org-columns-display-here-title)
16433 (mapc (lambda (x)
16434 (goto-line (car x))
16435 (org-columns-display-here (cdr x)))
16436 cache)))))
16438 (defun org-columns-get-autowidth-alist (s cache)
16439 "Derive the maximum column widths from the format and the cache."
16440 (let ((start 0) rtn)
16441 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16442 (push (cons (match-string 1 s) 1) rtn)
16443 (setq start (match-end 0)))
16444 (mapc (lambda (x)
16445 (setcdr x (apply 'max
16446 (mapcar
16447 (lambda (y)
16448 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16449 cache))))
16450 rtn)
16451 rtn))
16453 (defun org-columns-compute-all ()
16454 "Compute all columns that have operators defined."
16455 (org-unmodified
16456 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16457 (let ((columns org-columns-current-fmt-compiled) col)
16458 (while (setq col (pop columns))
16459 (when (nth 3 col)
16460 (save-excursion
16461 (org-columns-compute (car col)))))))
16463 (defun org-columns-update (property)
16464 "Recompute PROPERTY, and update the columns display for it."
16465 (org-columns-compute property)
16466 (let (fmt val pos)
16467 (save-excursion
16468 (mapc (lambda (ov)
16469 (when (equal (org-overlay-get ov 'org-columns-key) property)
16470 (setq pos (org-overlay-start ov))
16471 (goto-char pos)
16472 (when (setq val (cdr (assoc property
16473 (get-text-property
16474 (point-at-bol) 'org-summaries))))
16475 (setq fmt (org-overlay-get ov 'org-columns-format))
16476 (org-overlay-put ov 'org-columns-value val)
16477 (org-overlay-put ov 'display (format fmt val)))))
16478 org-columns-overlays))))
16480 (defun org-columns-compute (property)
16481 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16482 (interactive)
16483 (let* ((re (concat "^" outline-regexp))
16484 (lmax 30) ; Does anyone use deeper levels???
16485 (lsum (make-vector lmax 0))
16486 (lflag (make-vector lmax nil))
16487 (level 0)
16488 (ass (assoc property org-columns-current-fmt-compiled))
16489 (format (nth 4 ass))
16490 (printf (nth 5 ass))
16491 (beg org-columns-top-level-marker)
16492 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16493 (save-excursion
16494 ;; Find the region to compute
16495 (goto-char beg)
16496 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16497 (goto-char end)
16498 ;; Walk the tree from the back and do the computations
16499 (while (re-search-backward re beg t)
16500 (setq sumpos (match-beginning 0)
16501 last-level level
16502 level (org-outline-level)
16503 val (org-entry-get nil property)
16504 valflag (and val (string-match "\\S-" val)))
16505 (cond
16506 ((< level last-level)
16507 ;; put the sum of lower levels here as a property
16508 (setq sum (aref lsum last-level) ; current sum
16509 flag (aref lflag last-level) ; any valid entries from children?
16510 str (org-column-number-to-string sum format printf)
16511 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16512 useval (if flag str1 (if valflag val ""))
16513 sum-alist (get-text-property sumpos 'org-summaries))
16514 (if (assoc property sum-alist)
16515 (setcdr (assoc property sum-alist) useval)
16516 (push (cons property useval) sum-alist)
16517 (org-unmodified
16518 (add-text-properties sumpos (1+ sumpos)
16519 (list 'org-summaries sum-alist))))
16520 (when val
16521 (org-entry-put nil property (if flag str val)))
16522 ;; add current to current level accumulator
16523 (when (or flag valflag)
16524 (aset lsum level (+ (aref lsum level)
16525 (if flag sum (org-column-string-to-number
16526 (if flag str val) format))))
16527 (aset lflag level t))
16528 ;; clear accumulators for deeper levels
16529 (loop for l from (1+ level) to (1- lmax) do
16530 (aset lsum l 0)
16531 (aset lflag l nil)))
16532 ((>= level last-level)
16533 ;; add what we have here to the accumulator for this level
16534 (aset lsum level (+ (aref lsum level)
16535 (org-column-string-to-number (or val "0") format)))
16536 (and valflag (aset lflag level t)))
16537 (t (error "This should not happen")))))))
16539 (defun org-columns-redo ()
16540 "Construct the column display again."
16541 (interactive)
16542 (message "Recomputing columns...")
16543 (save-excursion
16544 (if (marker-position org-columns-begin-marker)
16545 (goto-char org-columns-begin-marker))
16546 (org-columns-remove-overlays)
16547 (if (org-mode-p)
16548 (call-interactively 'org-columns)
16549 (call-interactively 'org-agenda-columns)))
16550 (message "Recomputing columns...done"))
16552 (defun org-columns-not-in-agenda ()
16553 (if (eq major-mode 'org-agenda-mode)
16554 (error "This command is only allowed in Org-mode buffers")))
16557 (defun org-string-to-number (s)
16558 "Convert string to number, and interpret hh:mm:ss."
16559 (if (not (string-match ":" s))
16560 (string-to-number s)
16561 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16562 (while l
16563 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16564 sum)))
16566 (defun org-column-number-to-string (n fmt printf)
16567 "Convert a computed column number to a string value, according to FMT."
16568 (cond
16569 ((eq fmt 'add_times)
16570 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16571 (format "%d:%02d" h m)))
16572 ((eq fmt 'checkbox)
16573 (cond ((= n (floor n)) "[X]")
16574 ((> n 1.) "[-]")
16575 (t "[ ]")))
16576 (printf (format printf n))
16577 ((eq fmt 'currency)
16578 (format "%.2f" n))
16579 (t (number-to-string n))))
16581 (defun org-column-string-to-number (s fmt)
16582 "Convert a column value to a number that can be used for column computing."
16583 (cond
16584 ((string-match ":" s)
16585 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16586 (while l
16587 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16588 sum))
16589 ((eq fmt 'checkbox)
16590 (if (equal s "[X]") 1. 0.000001))
16591 (t (string-to-number s))))
16593 (defun org-columns-uncompile-format (cfmt)
16594 "Turn the compiled columns format back into a string representation."
16595 (let ((rtn "") e s prop title op width fmt printf)
16596 (while (setq e (pop cfmt))
16597 (setq prop (car e)
16598 title (nth 1 e)
16599 width (nth 2 e)
16600 op (nth 3 e)
16601 fmt (nth 4 e)
16602 printf (nth 5 e))
16603 (cond
16604 ((eq fmt 'add_times) (setq op ":"))
16605 ((eq fmt 'checkbox) (setq op "X"))
16606 ((eq fmt 'add_numbers) (setq op "+"))
16607 ((eq fmt 'currency) (setq op "$")))
16608 (if (and op printf) (setq op (concat op ";" printf)))
16609 (if (equal title prop) (setq title nil))
16610 (setq s (concat "%" (if width (number-to-string width))
16611 prop
16612 (if title (concat "(" title ")"))
16613 (if op (concat "{" op "}"))))
16614 (setq rtn (concat rtn " " s)))
16615 (org-trim rtn)))
16617 (defun org-columns-compile-format (fmt)
16618 "Turn a column format string into an alist of specifications.
16619 The alist has one entry for each column in the format. The elements of
16620 that list are:
16621 property the property
16622 title the title field for the columns
16623 width the column width in characters, can be nil for automatic
16624 operator the operator if any
16625 format the output format for computed results, derived from operator
16626 printf a printf format for computed values"
16627 (let ((start 0) width prop title op f printf)
16628 (setq org-columns-current-fmt-compiled nil)
16629 (while (string-match
16630 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16631 fmt start)
16632 (setq start (match-end 0)
16633 width (match-string 1 fmt)
16634 prop (match-string 2 fmt)
16635 title (or (match-string 3 fmt) prop)
16636 op (match-string 4 fmt)
16637 f nil
16638 printf nil)
16639 (if width (setq width (string-to-number width)))
16640 (when (and op (string-match ";" op))
16641 (setq printf (substring op (match-end 0))
16642 op (substring op 0 (match-beginning 0))))
16643 (cond
16644 ((equal op "+") (setq f 'add_numbers))
16645 ((equal op "$") (setq f 'currency))
16646 ((equal op ":") (setq f 'add_times))
16647 ((equal op "X") (setq f 'checkbox)))
16648 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16649 (setq org-columns-current-fmt-compiled
16650 (nreverse org-columns-current-fmt-compiled))))
16653 ;;; Dynamic block for Column view
16655 (defun org-columns-capture-view ()
16656 "Get the column view of the current buffer and return it as a list.
16657 The list will contains the title row and all other rows. Each row is
16658 a list of fields."
16659 (save-excursion
16660 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16661 (n (length title)) row tbl)
16662 (goto-char (point-min))
16663 (while (re-search-forward "^\\*+ " nil t)
16664 (when (get-char-property (match-beginning 0) 'org-columns-key)
16665 (setq row nil)
16666 (loop for i from 0 to (1- n) do
16667 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16668 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16670 row))
16671 (setq row (nreverse row))
16672 (push row tbl)))
16673 (append (list title 'hline) (nreverse tbl)))))
16675 (defun org-dblock-write:columnview (params)
16676 "Write the column view table.
16677 PARAMS is a property list of parameters:
16679 :width enforce same column widths with <N> specifiers.
16680 :id the :ID: property of the entry where the columns view
16681 should be built, as a string. When `local', call locally.
16682 When `global' call column view with the cursor at the beginning
16683 of the buffer (usually this means that the whole buffer switches
16684 to column view).
16685 :hlines When t, insert a hline before each item. When a number, insert
16686 a hline before each level <= that number.
16687 :vlines When t, make each column a colgroup to enforce vertical lines."
16688 (let ((pos (move-marker (make-marker) (point)))
16689 (hlines (plist-get params :hlines))
16690 (vlines (plist-get params :vlines))
16691 tbl id idpos nfields tmp)
16692 (save-excursion
16693 (save-restriction
16694 (when (setq id (plist-get params :id))
16695 (cond ((not id) nil)
16696 ((eq id 'global) (goto-char (point-min)))
16697 ((eq id 'local) nil)
16698 ((setq idpos (org-find-entry-with-id id))
16699 (goto-char idpos))
16700 (t (error "Cannot find entry with :ID: %s" id))))
16701 (org-columns)
16702 (setq tbl (org-columns-capture-view))
16703 (setq nfields (length (car tbl)))
16704 (org-columns-quit)))
16705 (goto-char pos)
16706 (move-marker pos nil)
16707 (when tbl
16708 (when (plist-get params :hlines)
16709 (setq tmp nil)
16710 (while tbl
16711 (if (eq (car tbl) 'hline)
16712 (push (pop tbl) tmp)
16713 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16714 (if (and (not (eq (car tmp) 'hline))
16715 (or (eq hlines t)
16716 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16717 (push 'hline tmp)))
16718 (push (pop tbl) tmp)))
16719 (setq tbl (nreverse tmp)))
16720 (when vlines
16721 (setq tbl (mapcar (lambda (x)
16722 (if (eq 'hline x) x (cons "" x)))
16723 tbl))
16724 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16725 (setq pos (point))
16726 (insert (org-listtable-to-string tbl))
16727 (when (plist-get params :width)
16728 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16729 org-columns-current-widths "|")))
16730 (goto-char pos)
16731 (org-table-align))))
16733 (defun org-listtable-to-string (tbl)
16734 "Convert a listtable TBL to a string that contains the Org-mode table.
16735 The table still need to be alligned. The resulting string has no leading
16736 and tailing newline characters."
16737 (mapconcat
16738 (lambda (x)
16739 (cond
16740 ((listp x)
16741 (concat "|" (mapconcat 'identity x "|") "|"))
16742 ((eq x 'hline) "|-|")
16743 (t (error "Garbage in listtable: %s" x))))
16744 tbl "\n"))
16746 (defun org-insert-columns-dblock ()
16747 "Create a dynamic block capturing a column view table."
16748 (interactive)
16749 (let ((defaults '(:name "columnview" :hlines 1))
16750 (id (completing-read
16751 "Capture columns (local, global, entry with :ID: property) [local]: "
16752 (append '(("global") ("local"))
16753 (mapcar 'list (org-property-values "ID"))))))
16754 (if (equal id "") (setq id 'local))
16755 (if (equal id "global") (setq id 'global))
16756 (setq defaults (append defaults (list :id id)))
16757 (org-create-dblock defaults)
16758 (org-update-dblock)))
16760 ;;;; Timestamps
16762 (defvar org-last-changed-timestamp nil)
16763 (defvar org-time-was-given) ; dynamically scoped parameter
16764 (defvar org-end-time-was-given) ; dynamically scoped parameter
16765 (defvar org-ts-what) ; dynamically scoped parameter
16767 (defun org-time-stamp (arg)
16768 "Prompt for a date/time and insert a time stamp.
16769 If the user specifies a time like HH:MM, or if this command is called
16770 with a prefix argument, the time stamp will contain date and time.
16771 Otherwise, only the date will be included. All parts of a date not
16772 specified by the user will be filled in from the current date/time.
16773 So if you press just return without typing anything, the time stamp
16774 will represent the current date/time. If there is already a timestamp
16775 at the cursor, it will be modified."
16776 (interactive "P")
16777 (let* ((ts nil)
16778 (default-time
16779 ;; Default time is either today, or, when entering a range,
16780 ;; the range start.
16781 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16782 (save-excursion
16783 (re-search-backward
16784 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16785 (- (point) 20) t)))
16786 (apply 'encode-time (org-parse-time-string (match-string 1)))
16787 (current-time)))
16788 (default-input (and ts (org-get-compact-tod ts)))
16789 org-time-was-given org-end-time-was-given time)
16790 (cond
16791 ((and (org-at-timestamp-p)
16792 (eq last-command 'org-time-stamp)
16793 (eq this-command 'org-time-stamp))
16794 (insert "--")
16795 (setq time (let ((this-command this-command))
16796 (org-read-date arg 'totime nil nil default-time default-input)))
16797 (org-insert-time-stamp time (or org-time-was-given arg)))
16798 ((org-at-timestamp-p)
16799 (setq time (let ((this-command this-command))
16800 (org-read-date arg 'totime nil nil default-time default-input)))
16801 (when (org-at-timestamp-p) ; just to get the match data
16802 (replace-match "")
16803 (setq org-last-changed-timestamp
16804 (org-insert-time-stamp
16805 time (or org-time-was-given arg)
16806 nil nil nil (list org-end-time-was-given))))
16807 (message "Timestamp updated"))
16809 (setq time (let ((this-command this-command))
16810 (org-read-date arg 'totime nil nil default-time default-input)))
16811 (org-insert-time-stamp time (or org-time-was-given arg)
16812 nil nil nil (list org-end-time-was-given))))))
16814 ;; FIXME: can we use this for something else????
16815 ;; like computing time differences?????
16816 (defun org-get-compact-tod (s)
16817 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16818 (let* ((t1 (match-string 1 s))
16819 (h1 (string-to-number (match-string 2 s)))
16820 (m1 (string-to-number (match-string 3 s)))
16821 (t2 (and (match-end 4) (match-string 5 s)))
16822 (h2 (and t2 (string-to-number (match-string 6 s))))
16823 (m2 (and t2 (string-to-number (match-string 7 s))))
16824 dh dm)
16825 (if (not t2)
16827 (setq dh (- h2 h1) dm (- m2 m1))
16828 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16829 (concat t1 "+" (number-to-string dh)
16830 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16832 (defun org-time-stamp-inactive (&optional arg)
16833 "Insert an inactive time stamp.
16834 An inactive time stamp is enclosed in square brackets instead of angle
16835 brackets. It is inactive in the sense that it does not trigger agenda entries,
16836 does not link to the calendar and cannot be changed with the S-cursor keys.
16837 So these are more for recording a certain time/date."
16838 (interactive "P")
16839 (let (org-time-was-given org-end-time-was-given time)
16840 (setq time (org-read-date arg 'totime))
16841 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16842 nil nil (list org-end-time-was-given))))
16844 (defvar org-date-ovl (org-make-overlay 1 1))
16845 (org-overlay-put org-date-ovl 'face 'org-warning)
16846 (org-detach-overlay org-date-ovl)
16848 (defvar org-ans1) ; dynamically scoped parameter
16849 (defvar org-ans2) ; dynamically scoped parameter
16851 (defvar org-plain-time-of-day-regexp) ; defined below
16853 (defvar org-read-date-overlay nil)
16854 (defvar org-dcst nil) ; dynamically scoped
16856 (defun org-read-date (&optional with-time to-time from-string prompt
16857 default-time default-input)
16858 "Read a date, possibly a time, and make things smooth for the user.
16859 The prompt will suggest to enter an ISO date, but you can also enter anything
16860 which will at least partially be understood by `parse-time-string'.
16861 Unrecognized parts of the date will default to the current day, month, year,
16862 hour and minute. If this command is called to replace a timestamp at point,
16863 of to enter the second timestamp of a range, the default time is taken from the
16864 existing stamp. For example,
16865 3-2-5 --> 2003-02-05
16866 feb 15 --> currentyear-02-15
16867 sep 12 9 --> 2009-09-12
16868 12:45 --> today 12:45
16869 22 sept 0:34 --> currentyear-09-22 0:34
16870 12 --> currentyear-currentmonth-12
16871 Fri --> nearest Friday (today or later)
16872 etc.
16874 Furthermore you can specify a relative date by giving, as the *first* thing
16875 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16876 change in days weeks, months, years.
16877 With a single plus or minus, the date is relative to today. With a double
16878 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16879 +4d --> four days from today
16880 +4 --> same as above
16881 +2w --> two weeks from today
16882 ++5 --> five days from default date
16884 The function understands only English month and weekday abbreviations,
16885 but this can be configured with the variables `parse-time-months' and
16886 `parse-time-weekdays'.
16888 While prompting, a calendar is popped up - you can also select the
16889 date with the mouse (button 1). The calendar shows a period of three
16890 months. To scroll it to other months, use the keys `>' and `<'.
16891 If you don't like the calendar, turn it off with
16892 \(setq org-read-date-popup-calendar nil)
16894 With optional argument TO-TIME, the date will immediately be converted
16895 to an internal time.
16896 With an optional argument WITH-TIME, the prompt will suggest to also
16897 insert a time. Note that when WITH-TIME is not set, you can still
16898 enter a time, and this function will inform the calling routine about
16899 this change. The calling routine may then choose to change the format
16900 used to insert the time stamp into the buffer to include the time.
16901 With optional argument FROM-STRING, read from this string instead from
16902 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16903 the time/date that is used for everything that is not specified by the
16904 user."
16905 (require 'parse-time)
16906 (let* ((org-time-stamp-rounding-minutes
16907 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16908 (org-dcst org-display-custom-times)
16909 (ct (org-current-time))
16910 (def (or default-time ct))
16911 (defdecode (decode-time def))
16912 (dummy (progn
16913 (when (< (nth 2 defdecode) org-extend-today-until)
16914 (setcar (nthcdr 2 defdecode) -1)
16915 (setcar (nthcdr 1 defdecode) 59)
16916 (setq def (apply 'encode-time defdecode)
16917 defdecode (decode-time def)))))
16918 (calendar-move-hook nil)
16919 (view-diary-entries-initially nil)
16920 (view-calendar-holidays-initially nil)
16921 (timestr (format-time-string
16922 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16923 (prompt (concat (if prompt (concat prompt " ") "")
16924 (format "Date+time [%s]: " timestr)))
16925 ans (org-ans0 "") org-ans1 org-ans2 final)
16927 (cond
16928 (from-string (setq ans from-string))
16929 (org-read-date-popup-calendar
16930 (save-excursion
16931 (save-window-excursion
16932 (calendar)
16933 (calendar-forward-day (- (time-to-days def)
16934 (calendar-absolute-from-gregorian
16935 (calendar-current-date))))
16936 (org-eval-in-calendar nil t)
16937 (let* ((old-map (current-local-map))
16938 (map (copy-keymap calendar-mode-map))
16939 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16940 (org-defkey map (kbd "RET") 'org-calendar-select)
16941 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16942 'org-calendar-select-mouse)
16943 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16944 'org-calendar-select-mouse)
16945 (org-defkey minibuffer-local-map [(meta shift left)]
16946 (lambda () (interactive)
16947 (org-eval-in-calendar '(calendar-backward-month 1))))
16948 (org-defkey minibuffer-local-map [(meta shift right)]
16949 (lambda () (interactive)
16950 (org-eval-in-calendar '(calendar-forward-month 1))))
16951 (org-defkey minibuffer-local-map [(meta shift up)]
16952 (lambda () (interactive)
16953 (org-eval-in-calendar '(calendar-backward-year 1))))
16954 (org-defkey minibuffer-local-map [(meta shift down)]
16955 (lambda () (interactive)
16956 (org-eval-in-calendar '(calendar-forward-year 1))))
16957 (org-defkey minibuffer-local-map [(shift up)]
16958 (lambda () (interactive)
16959 (org-eval-in-calendar '(calendar-backward-week 1))))
16960 (org-defkey minibuffer-local-map [(shift down)]
16961 (lambda () (interactive)
16962 (org-eval-in-calendar '(calendar-forward-week 1))))
16963 (org-defkey minibuffer-local-map [(shift left)]
16964 (lambda () (interactive)
16965 (org-eval-in-calendar '(calendar-backward-day 1))))
16966 (org-defkey minibuffer-local-map [(shift right)]
16967 (lambda () (interactive)
16968 (org-eval-in-calendar '(calendar-forward-day 1))))
16969 (org-defkey minibuffer-local-map ">"
16970 (lambda () (interactive)
16971 (org-eval-in-calendar '(scroll-calendar-left 1))))
16972 (org-defkey minibuffer-local-map "<"
16973 (lambda () (interactive)
16974 (org-eval-in-calendar '(scroll-calendar-right 1))))
16975 (unwind-protect
16976 (progn
16977 (use-local-map map)
16978 (add-hook 'post-command-hook 'org-read-date-display)
16979 (setq org-ans0 (read-string prompt default-input nil nil))
16980 ;; org-ans0: from prompt
16981 ;; org-ans1: from mouse click
16982 ;; org-ans2: from calendar motion
16983 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16984 (remove-hook 'post-command-hook 'org-read-date-display)
16985 (use-local-map old-map)
16986 (when org-read-date-overlay
16987 (org-delete-overlay org-read-date-overlay)
16988 (setq org-read-date-overlay nil)))))))
16990 (t ; Naked prompt only
16991 (unwind-protect
16992 (setq ans (read-string prompt default-input nil timestr))
16993 (when org-read-date-overlay
16994 (org-delete-overlay org-read-date-overlay)
16995 (setq org-read-date-overlay nil)))))
16997 (setq final (org-read-date-analyze ans def defdecode))
16999 (if to-time
17000 (apply 'encode-time final)
17001 (if (and (boundp 'org-time-was-given) org-time-was-given)
17002 (format "%04d-%02d-%02d %02d:%02d"
17003 (nth 5 final) (nth 4 final) (nth 3 final)
17004 (nth 2 final) (nth 1 final))
17005 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17006 (defvar def)
17007 (defvar defdecode)
17008 (defvar with-time)
17009 (defun org-read-date-display ()
17010 "Display the currrent date prompt interpretation in the minibuffer."
17011 (when org-read-date-display-live
17012 (when org-read-date-overlay
17013 (org-delete-overlay org-read-date-overlay))
17014 (let ((p (point)))
17015 (end-of-line 1)
17016 (while (not (equal (buffer-substring
17017 (max (point-min) (- (point) 4)) (point))
17018 " "))
17019 (insert " "))
17020 (goto-char p))
17021 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17022 " " (or org-ans1 org-ans2)))
17023 (org-end-time-was-given nil)
17024 (f (org-read-date-analyze ans def defdecode))
17025 (fmts (if org-dcst
17026 org-time-stamp-custom-formats
17027 org-time-stamp-formats))
17028 (fmt (if (or with-time
17029 (and (boundp 'org-time-was-given) org-time-was-given))
17030 (cdr fmts)
17031 (car fmts)))
17032 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17033 (when (and org-end-time-was-given
17034 (string-match org-plain-time-of-day-regexp txt))
17035 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17036 org-end-time-was-given
17037 (substring txt (match-end 0)))))
17038 (setq org-read-date-overlay
17039 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17040 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17042 (defun org-read-date-analyze (ans def defdecode)
17043 "Analyze the combined answer of the date prompt."
17044 ;; FIXME: cleanup and comment
17045 (let (delta deltan deltaw deltadef year month day
17046 hour minute second wday pm h2 m2 tl wday1)
17048 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17049 (setq ans (replace-match "" t t ans)
17050 deltan (car delta)
17051 deltaw (nth 1 delta)
17052 deltadef (nth 2 delta)))
17054 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17055 (when (string-match
17056 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17057 (setq year (if (match-end 2)
17058 (string-to-number (match-string 2 ans))
17059 (string-to-number (format-time-string "%Y")))
17060 month (string-to-number (match-string 3 ans))
17061 day (string-to-number (match-string 4 ans)))
17062 (if (< year 100) (setq year (+ 2000 year)))
17063 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17064 t nil ans)))
17065 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17066 ;; If there is a time with am/pm, and *no* time without it, we convert
17067 ;; so that matching will be successful.
17068 (loop for i from 1 to 2 do ; twice, for end time as well
17069 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17070 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17071 (setq hour (string-to-number (match-string 1 ans))
17072 minute (if (match-end 3)
17073 (string-to-number (match-string 3 ans))
17075 pm (equal ?p
17076 (string-to-char (downcase (match-string 4 ans)))))
17077 (if (and (= hour 12) (not pm))
17078 (setq hour 0)
17079 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17080 (setq ans (replace-match (format "%02d:%02d" hour minute)
17081 t t ans))))
17083 ;; Check if a time range is given as a duration
17084 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17085 (setq hour (string-to-number (match-string 1 ans))
17086 h2 (+ hour (string-to-number (match-string 3 ans)))
17087 minute (string-to-number (match-string 2 ans))
17088 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17089 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17090 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17092 ;; Check if there is a time range
17093 (when (boundp 'org-end-time-was-given)
17094 (setq org-time-was-given nil)
17095 (when (and (string-match org-plain-time-of-day-regexp ans)
17096 (match-end 8))
17097 (setq org-end-time-was-given (match-string 8 ans))
17098 (setq ans (concat (substring ans 0 (match-beginning 7))
17099 (substring ans (match-end 7))))))
17101 (setq tl (parse-time-string ans)
17102 day (or (nth 3 tl) (nth 3 defdecode))
17103 month (or (nth 4 tl)
17104 (if (and org-read-date-prefer-future
17105 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17106 (1+ (nth 4 defdecode))
17107 (nth 4 defdecode)))
17108 year (or (nth 5 tl)
17109 (if (and org-read-date-prefer-future
17110 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17111 (1+ (nth 5 defdecode))
17112 (nth 5 defdecode)))
17113 hour (or (nth 2 tl) (nth 2 defdecode))
17114 minute (or (nth 1 tl) (nth 1 defdecode))
17115 second (or (nth 0 tl) 0)
17116 wday (nth 6 tl))
17117 (when deltan
17118 (unless deltadef
17119 (let ((now (decode-time (current-time))))
17120 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17121 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17122 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17123 ((equal deltaw "m") (setq month (+ month deltan)))
17124 ((equal deltaw "y") (setq year (+ year deltan)))))
17125 (when (and wday (not (nth 3 tl)))
17126 ;; Weekday was given, but no day, so pick that day in the week
17127 ;; on or after the derived date.
17128 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17129 (unless (equal wday wday1)
17130 (setq day (+ day (% (- wday wday1 -7) 7)))))
17131 (if (and (boundp 'org-time-was-given)
17132 (nth 2 tl))
17133 (setq org-time-was-given t))
17134 (if (< year 100) (setq year (+ 2000 year)))
17135 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17136 (list second minute hour day month year)))
17138 (defvar parse-time-weekdays)
17140 (defun org-read-date-get-relative (s today default)
17141 "Check string S for special relative date string.
17142 TODAY and DEFAULT are internal times, for today and for a default.
17143 Return shift list (N what def-flag)
17144 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
17145 N is the number if WHATs to shift
17146 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17147 the DEFAULT date rather than TODAY."
17148 (when (string-match
17149 (concat
17150 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17151 "\\([0-9]+\\)?"
17152 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17153 "\\([ \t]\\|$\\)") s)
17154 (let* ((dir (if (match-end 1)
17155 (string-to-char (substring (match-string 1 s) -1))
17156 ?+))
17157 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17158 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17159 (what (if (match-end 3) (match-string 3 s) "d"))
17160 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17161 (date (if rel default today))
17162 (wday (nth 6 (decode-time date)))
17163 delta)
17164 (if wday1
17165 (progn
17166 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17167 (if (= dir ?-) (setq delta (- delta 7)))
17168 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17169 (list delta "d" rel))
17170 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17172 (defun org-eval-in-calendar (form &optional keepdate)
17173 "Eval FORM in the calendar window and return to current window.
17174 Also, store the cursor date in variable org-ans2."
17175 (let ((sw (selected-window)))
17176 (select-window (get-buffer-window "*Calendar*"))
17177 (eval form)
17178 (when (and (not keepdate) (calendar-cursor-to-date))
17179 (let* ((date (calendar-cursor-to-date))
17180 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17181 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17182 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17183 (select-window sw)))
17185 ; ;; Update the prompt to show new default date
17186 ; (save-excursion
17187 ; (goto-char (point-min))
17188 ; (when (and org-ans2
17189 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17190 ; (get-text-property (match-end 0) 'field))
17191 ; (let ((inhibit-read-only t))
17192 ; (replace-match (concat "[" org-ans2 "]") t t)
17193 ; (add-text-properties (point-min) (1+ (match-end 0))
17194 ; (text-properties-at (1+ (point-min)))))))))
17196 (defun org-calendar-select ()
17197 "Return to `org-read-date' with the date currently selected.
17198 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17199 (interactive)
17200 (when (calendar-cursor-to-date)
17201 (let* ((date (calendar-cursor-to-date))
17202 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17203 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17204 (if (active-minibuffer-window) (exit-minibuffer))))
17206 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17207 "Insert a date stamp for the date given by the internal TIME.
17208 WITH-HM means, use the stamp format that includes the time of the day.
17209 INACTIVE means use square brackets instead of angular ones, so that the
17210 stamp will not contribute to the agenda.
17211 PRE and POST are optional strings to be inserted before and after the
17212 stamp.
17213 The command returns the inserted time stamp."
17214 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17215 stamp)
17216 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17217 (insert-before-markers (or pre ""))
17218 (insert-before-markers (setq stamp (format-time-string fmt time)))
17219 (when (listp extra)
17220 (setq extra (car extra))
17221 (if (and (stringp extra)
17222 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17223 (setq extra (format "-%02d:%02d"
17224 (string-to-number (match-string 1 extra))
17225 (string-to-number (match-string 2 extra))))
17226 (setq extra nil)))
17227 (when extra
17228 (backward-char 1)
17229 (insert-before-markers extra)
17230 (forward-char 1))
17231 (insert-before-markers (or post ""))
17232 stamp))
17234 (defun org-toggle-time-stamp-overlays ()
17235 "Toggle the use of custom time stamp formats."
17236 (interactive)
17237 (setq org-display-custom-times (not org-display-custom-times))
17238 (unless org-display-custom-times
17239 (let ((p (point-min)) (bmp (buffer-modified-p)))
17240 (while (setq p (next-single-property-change p 'display))
17241 (if (and (get-text-property p 'display)
17242 (eq (get-text-property p 'face) 'org-date))
17243 (remove-text-properties
17244 p (setq p (next-single-property-change p 'display))
17245 '(display t))))
17246 (set-buffer-modified-p bmp)))
17247 (if (featurep 'xemacs)
17248 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17249 (org-restart-font-lock)
17250 (setq org-table-may-need-update t)
17251 (if org-display-custom-times
17252 (message "Time stamps are overlayed with custom format")
17253 (message "Time stamp overlays removed")))
17255 (defun org-display-custom-time (beg end)
17256 "Overlay modified time stamp format over timestamp between BED and END."
17257 (let* ((ts (buffer-substring beg end))
17258 t1 w1 with-hm tf time str w2 (off 0))
17259 (save-match-data
17260 (setq t1 (org-parse-time-string ts t))
17261 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17262 (setq off (- (match-end 0) (match-beginning 0)))))
17263 (setq end (- end off))
17264 (setq w1 (- end beg)
17265 with-hm (and (nth 1 t1) (nth 2 t1))
17266 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17267 time (org-fix-decoded-time t1)
17268 str (org-add-props
17269 (format-time-string
17270 (substring tf 1 -1) (apply 'encode-time time))
17271 nil 'mouse-face 'highlight)
17272 w2 (length str))
17273 (if (not (= w2 w1))
17274 (add-text-properties (1+ beg) (+ 2 beg)
17275 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17276 (if (featurep 'xemacs)
17277 (progn
17278 (put-text-property beg end 'invisible t)
17279 (put-text-property beg end 'end-glyph (make-glyph str)))
17280 (put-text-property beg end 'display str))))
17282 (defun org-translate-time (string)
17283 "Translate all timestamps in STRING to custom format.
17284 But do this only if the variable `org-display-custom-times' is set."
17285 (when org-display-custom-times
17286 (save-match-data
17287 (let* ((start 0)
17288 (re org-ts-regexp-both)
17289 t1 with-hm inactive tf time str beg end)
17290 (while (setq start (string-match re string start))
17291 (setq beg (match-beginning 0)
17292 end (match-end 0)
17293 t1 (save-match-data
17294 (org-parse-time-string (substring string beg end) t))
17295 with-hm (and (nth 1 t1) (nth 2 t1))
17296 inactive (equal (substring string beg (1+ beg)) "[")
17297 tf (funcall (if with-hm 'cdr 'car)
17298 org-time-stamp-custom-formats)
17299 time (org-fix-decoded-time t1)
17300 str (format-time-string
17301 (concat
17302 (if inactive "[" "<") (substring tf 1 -1)
17303 (if inactive "]" ">"))
17304 (apply 'encode-time time))
17305 string (replace-match str t t string)
17306 start (+ start (length str)))))))
17307 string)
17309 (defun org-fix-decoded-time (time)
17310 "Set 0 instead of nil for the first 6 elements of time.
17311 Don't touch the rest."
17312 (let ((n 0))
17313 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17315 (defun org-days-to-time (timestamp-string)
17316 "Difference between TIMESTAMP-STRING and now in days."
17317 (- (time-to-days (org-time-string-to-time timestamp-string))
17318 (time-to-days (current-time))))
17320 (defun org-deadline-close (timestamp-string &optional ndays)
17321 "Is the time in TIMESTAMP-STRING close to the current date?"
17322 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17323 (and (< (org-days-to-time timestamp-string) ndays)
17324 (not (org-entry-is-done-p))))
17326 (defun org-get-wdays (ts)
17327 "Get the deadline lead time appropriate for timestring TS."
17328 (cond
17329 ((<= org-deadline-warning-days 0)
17330 ;; 0 or negative, enforce this value no matter what
17331 (- org-deadline-warning-days))
17332 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17333 ;; lead time is specified.
17334 (floor (* (string-to-number (match-string 1 ts))
17335 (cdr (assoc (match-string 2 ts)
17336 '(("d" . 1) ("w" . 7)
17337 ("m" . 30.4) ("y" . 365.25)))))))
17338 ;; go for the default.
17339 (t org-deadline-warning-days)))
17341 (defun org-calendar-select-mouse (ev)
17342 "Return to `org-read-date' with the date currently selected.
17343 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17344 (interactive "e")
17345 (mouse-set-point ev)
17346 (when (calendar-cursor-to-date)
17347 (let* ((date (calendar-cursor-to-date))
17348 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17349 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17350 (if (active-minibuffer-window) (exit-minibuffer))))
17352 (defun org-check-deadlines (ndays)
17353 "Check if there are any deadlines due or past due.
17354 A deadline is considered due if it happens within `org-deadline-warning-days'
17355 days from today's date. If the deadline appears in an entry marked DONE,
17356 it is not shown. The prefix arg NDAYS can be used to test that many
17357 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17358 (interactive "P")
17359 (let* ((org-warn-days
17360 (cond
17361 ((equal ndays '(4)) 100000)
17362 (ndays (prefix-numeric-value ndays))
17363 (t (abs org-deadline-warning-days))))
17364 (case-fold-search nil)
17365 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17366 (callback
17367 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17369 (message "%d deadlines past-due or due within %d days"
17370 (org-occur regexp nil callback)
17371 org-warn-days)))
17373 (defun org-evaluate-time-range (&optional to-buffer)
17374 "Evaluate a time range by computing the difference between start and end.
17375 Normally the result is just printed in the echo area, but with prefix arg
17376 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17377 If the time range is actually in a table, the result is inserted into the
17378 next column.
17379 For time difference computation, a year is assumed to be exactly 365
17380 days in order to avoid rounding problems."
17381 (interactive "P")
17383 (org-clock-update-time-maybe)
17384 (save-excursion
17385 (unless (org-at-date-range-p t)
17386 (goto-char (point-at-bol))
17387 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17388 (if (not (org-at-date-range-p t))
17389 (error "Not at a time-stamp range, and none found in current line")))
17390 (let* ((ts1 (match-string 1))
17391 (ts2 (match-string 2))
17392 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17393 (match-end (match-end 0))
17394 (time1 (org-time-string-to-time ts1))
17395 (time2 (org-time-string-to-time ts2))
17396 (t1 (time-to-seconds time1))
17397 (t2 (time-to-seconds time2))
17398 (diff (abs (- t2 t1)))
17399 (negative (< (- t2 t1) 0))
17400 ;; (ys (floor (* 365 24 60 60)))
17401 (ds (* 24 60 60))
17402 (hs (* 60 60))
17403 (fy "%dy %dd %02d:%02d")
17404 (fy1 "%dy %dd")
17405 (fd "%dd %02d:%02d")
17406 (fd1 "%dd")
17407 (fh "%02d:%02d")
17408 y d h m align)
17409 (if havetime
17410 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17412 d (floor (/ diff ds)) diff (mod diff ds)
17413 h (floor (/ diff hs)) diff (mod diff hs)
17414 m (floor (/ diff 60)))
17415 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17417 d (floor (+ (/ diff ds) 0.5))
17418 h 0 m 0))
17419 (if (not to-buffer)
17420 (message (org-make-tdiff-string y d h m))
17421 (if (org-at-table-p)
17422 (progn
17423 (goto-char match-end)
17424 (setq align t)
17425 (and (looking-at " *|") (goto-char (match-end 0))))
17426 (goto-char match-end))
17427 (if (looking-at
17428 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17429 (replace-match ""))
17430 (if negative (insert " -"))
17431 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17432 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17433 (insert " " (format fh h m))))
17434 (if align (org-table-align))
17435 (message "Time difference inserted")))))
17437 (defun org-make-tdiff-string (y d h m)
17438 (let ((fmt "")
17439 (l nil))
17440 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17441 l (push y l)))
17442 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17443 l (push d l)))
17444 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17445 l (push h l)))
17446 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17447 l (push m l)))
17448 (apply 'format fmt (nreverse l))))
17450 (defun org-time-string-to-time (s)
17451 (apply 'encode-time (org-parse-time-string s)))
17453 (defun org-time-string-to-absolute (s &optional daynr)
17454 "Convert a time stamp to an absolute day number.
17455 If there is a specifyer for a cyclic time stamp, get the closest date to
17456 DAYNR."
17457 (cond
17458 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17459 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17460 daynr
17461 (+ daynr 1000)))
17462 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17463 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17464 (time-to-days (current-time))) (match-string 0 s)))
17465 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17467 (defun org-time-from-absolute (d)
17468 "Return the time corresponding to date D.
17469 D may be an absolute day number, or a calendar-type list (month day year)."
17470 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17471 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17473 (defun org-calendar-holiday ()
17474 "List of holidays, for Diary display in Org-mode."
17475 (require 'holidays)
17476 (let ((hl (funcall
17477 (if (fboundp 'calendar-check-holidays)
17478 'calendar-check-holidays 'check-calendar-holidays) date)))
17479 (if hl (mapconcat 'identity hl "; "))))
17481 (defun org-diary-sexp-entry (sexp entry date)
17482 "Process a SEXP diary ENTRY for DATE."
17483 (require 'diary-lib)
17484 (let ((result (if calendar-debug-sexp
17485 (let ((stack-trace-on-error t))
17486 (eval (car (read-from-string sexp))))
17487 (condition-case nil
17488 (eval (car (read-from-string sexp)))
17489 (error
17490 (beep)
17491 (message "Bad sexp at line %d in %s: %s"
17492 (org-current-line)
17493 (buffer-file-name) sexp)
17494 (sleep-for 2))))))
17495 (cond ((stringp result) result)
17496 ((and (consp result)
17497 (stringp (cdr result))) (cdr result))
17498 (result entry)
17499 (t nil))))
17501 (defun org-diary-to-ical-string (frombuf)
17502 "Get iCalendar entries from diary entries in buffer FROMBUF.
17503 This uses the icalendar.el library."
17504 (let* ((tmpdir (if (featurep 'xemacs)
17505 (temp-directory)
17506 temporary-file-directory))
17507 (tmpfile (make-temp-name
17508 (expand-file-name "orgics" tmpdir)))
17509 buf rtn b e)
17510 (save-excursion
17511 (set-buffer frombuf)
17512 (icalendar-export-region (point-min) (point-max) tmpfile)
17513 (setq buf (find-buffer-visiting tmpfile))
17514 (set-buffer buf)
17515 (goto-char (point-min))
17516 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17517 (setq b (match-beginning 0)))
17518 (goto-char (point-max))
17519 (if (re-search-backward "^END:VEVENT" nil t)
17520 (setq e (match-end 0)))
17521 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17522 (kill-buffer buf)
17523 (kill-buffer frombuf)
17524 (delete-file tmpfile)
17525 rtn))
17527 (defun org-closest-date (start current change)
17528 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17529 ;; Make the proper lists from the dates
17530 (catch 'exit
17531 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17532 dn dw sday cday n1 n2
17533 d m y y1 y2 date1 date2 nmonths nm ny m2)
17535 (setq start (org-date-to-gregorian start)
17536 current (org-date-to-gregorian
17537 (if org-agenda-repeating-timestamp-show-all
17538 current
17539 (time-to-days (current-time))))
17540 sday (calendar-absolute-from-gregorian start)
17541 cday (calendar-absolute-from-gregorian current))
17543 (if (<= cday sday) (throw 'exit sday))
17545 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17546 (setq dn (string-to-number (match-string 1 change))
17547 dw (cdr (assoc (match-string 2 change) a1)))
17548 (error "Invalid change specifyer: %s" change))
17549 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17550 (cond
17551 ((eq dw 'day)
17552 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17553 n2 (+ n1 dn)))
17554 ((eq dw 'year)
17555 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17556 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17557 (setq date1 (list m d y1)
17558 n1 (calendar-absolute-from-gregorian date1)
17559 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17560 n2 (calendar-absolute-from-gregorian date2)))
17561 ((eq dw 'month)
17562 ;; approx number of month between the tow dates
17563 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17564 ;; How often does dn fit in there?
17565 (setq d (nth 1 start) m (car start) y (nth 2 start)
17566 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17567 m (+ m nm)
17568 ny (floor (/ m 12))
17569 y (+ y ny)
17570 m (- m (* ny 12)))
17571 (while (> m 12) (setq m (- m 12) y (1+ y)))
17572 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17573 (setq m2 (+ m dn) y2 y)
17574 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17575 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17576 (while (< n2 cday)
17577 (setq n1 n2 m m2 y y2)
17578 (setq m2 (+ m dn) y2 y)
17579 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17580 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17582 (if org-agenda-repeating-timestamp-show-all
17583 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17584 (if (= cday n1) n1 n2)))))
17586 (defun org-date-to-gregorian (date)
17587 "Turn any specification of DATE into a gregorian date for the calendar."
17588 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17589 ((and (listp date) (= (length date) 3)) date)
17590 ((stringp date)
17591 (setq date (org-parse-time-string date))
17592 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17593 ((listp date)
17594 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17596 (defun org-parse-time-string (s &optional nodefault)
17597 "Parse the standard Org-mode time string.
17598 This should be a lot faster than the normal `parse-time-string'.
17599 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17600 hour and minute fields will be nil if not given."
17601 (if (string-match org-ts-regexp0 s)
17602 (list 0
17603 (if (or (match-beginning 8) (not nodefault))
17604 (string-to-number (or (match-string 8 s) "0")))
17605 (if (or (match-beginning 7) (not nodefault))
17606 (string-to-number (or (match-string 7 s) "0")))
17607 (string-to-number (match-string 4 s))
17608 (string-to-number (match-string 3 s))
17609 (string-to-number (match-string 2 s))
17610 nil nil nil)
17611 (make-list 9 0)))
17613 (defun org-timestamp-up (&optional arg)
17614 "Increase the date item at the cursor by one.
17615 If the cursor is on the year, change the year. If it is on the month or
17616 the day, change that.
17617 With prefix ARG, change by that many units."
17618 (interactive "p")
17619 (org-timestamp-change (prefix-numeric-value arg)))
17621 (defun org-timestamp-down (&optional arg)
17622 "Decrease the date item at the cursor by one.
17623 If the cursor is on the year, change the year. If it is on the month or
17624 the day, change that.
17625 With prefix ARG, change by that many units."
17626 (interactive "p")
17627 (org-timestamp-change (- (prefix-numeric-value arg))))
17629 (defun org-timestamp-up-day (&optional arg)
17630 "Increase the date in the time stamp by one day.
17631 With prefix ARG, change that many days."
17632 (interactive "p")
17633 (if (and (not (org-at-timestamp-p t))
17634 (org-on-heading-p))
17635 (org-todo 'up)
17636 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17638 (defun org-timestamp-down-day (&optional arg)
17639 "Decrease the date in the time stamp by one day.
17640 With prefix ARG, change that many days."
17641 (interactive "p")
17642 (if (and (not (org-at-timestamp-p t))
17643 (org-on-heading-p))
17644 (org-todo 'down)
17645 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17647 (defsubst org-pos-in-match-range (pos n)
17648 (and (match-beginning n)
17649 (<= (match-beginning n) pos)
17650 (>= (match-end n) pos)))
17652 (defun org-at-timestamp-p (&optional inactive-ok)
17653 "Determine if the cursor is in or at a timestamp."
17654 (interactive)
17655 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17656 (pos (point))
17657 (ans (or (looking-at tsr)
17658 (save-excursion
17659 (skip-chars-backward "^[<\n\r\t")
17660 (if (> (point) (point-min)) (backward-char 1))
17661 (and (looking-at tsr)
17662 (> (- (match-end 0) pos) -1))))))
17663 (and ans
17664 (boundp 'org-ts-what)
17665 (setq org-ts-what
17666 (cond
17667 ((= pos (match-beginning 0)) 'bracket)
17668 ((= pos (1- (match-end 0))) 'bracket)
17669 ((org-pos-in-match-range pos 2) 'year)
17670 ((org-pos-in-match-range pos 3) 'month)
17671 ((org-pos-in-match-range pos 7) 'hour)
17672 ((org-pos-in-match-range pos 8) 'minute)
17673 ((or (org-pos-in-match-range pos 4)
17674 (org-pos-in-match-range pos 5)) 'day)
17675 ((and (> pos (or (match-end 8) (match-end 5)))
17676 (< pos (match-end 0)))
17677 (- pos (or (match-end 8) (match-end 5))))
17678 (t 'day))))
17679 ans))
17681 (defun org-toggle-timestamp-type ()
17683 (interactive)
17684 (when (org-at-timestamp-p t)
17685 (save-excursion
17686 (goto-char (match-beginning 0))
17687 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17688 (goto-char (1- (match-end 0)))
17689 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17690 (message "Timestamp is now %sactive"
17691 (if (equal (char-before) ?>) "in" ""))))
17693 (defun org-timestamp-change (n &optional what)
17694 "Change the date in the time stamp at point.
17695 The date will be changed by N times WHAT. WHAT can be `day', `month',
17696 `year', `minute', `second'. If WHAT is not given, the cursor position
17697 in the timestamp determines what will be changed."
17698 (let ((pos (point))
17699 with-hm inactive
17700 org-ts-what
17701 extra
17702 ts time time0)
17703 (if (not (org-at-timestamp-p t))
17704 (error "Not at a timestamp"))
17705 (if (and (not what) (eq org-ts-what 'bracket))
17706 (org-toggle-timestamp-type)
17707 (if (and (not what) (not (eq org-ts-what 'day))
17708 org-display-custom-times
17709 (get-text-property (point) 'display)
17710 (not (get-text-property (1- (point)) 'display)))
17711 (setq org-ts-what 'day))
17712 (setq org-ts-what (or what org-ts-what)
17713 inactive (= (char-after (match-beginning 0)) ?\[)
17714 ts (match-string 0))
17715 (replace-match "")
17716 (if (string-match
17717 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17719 (setq extra (match-string 1 ts)))
17720 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17721 (setq with-hm t))
17722 (setq time0 (org-parse-time-string ts))
17723 (setq time
17724 (encode-time (or (car time0) 0)
17725 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17726 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17727 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17728 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17729 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17730 (nthcdr 6 time0)))
17731 (when (integerp org-ts-what)
17732 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17733 (if (eq what 'calendar)
17734 (let ((cal-date (org-get-date-from-calendar)))
17735 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17736 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17737 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17738 (setcar time0 (or (car time0) 0))
17739 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17740 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17741 (setq time (apply 'encode-time time0))))
17742 (setq org-last-changed-timestamp
17743 (org-insert-time-stamp time with-hm inactive nil nil extra))
17744 (org-clock-update-time-maybe)
17745 (goto-char pos)
17746 ;; Try to recenter the calendar window, if any
17747 (if (and org-calendar-follow-timestamp-change
17748 (get-buffer-window "*Calendar*" t)
17749 (memq org-ts-what '(day month year)))
17750 (org-recenter-calendar (time-to-days time))))))
17752 ;; FIXME: does not yet work for lead times
17753 (defun org-modify-ts-extra (s pos n)
17754 "Change the different parts of the lead-time and repeat fields in timestamp."
17755 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17756 ng h m new)
17757 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17758 (cond
17759 ((or (org-pos-in-match-range pos 2)
17760 (org-pos-in-match-range pos 3))
17761 (setq m (string-to-number (match-string 3 s))
17762 h (string-to-number (match-string 2 s)))
17763 (if (org-pos-in-match-range pos 2)
17764 (setq h (+ h n))
17765 (setq m (+ m n)))
17766 (if (< m 0) (setq m (+ m 60) h (1- h)))
17767 (if (> m 59) (setq m (- m 60) h (1+ h)))
17768 (setq h (min 24 (max 0 h)))
17769 (setq ng 1 new (format "-%02d:%02d" h m)))
17770 ((org-pos-in-match-range pos 6)
17771 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17772 ((org-pos-in-match-range pos 5)
17773 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17775 (when ng
17776 (setq s (concat
17777 (substring s 0 (match-beginning ng))
17779 (substring s (match-end ng))))))
17782 (defun org-recenter-calendar (date)
17783 "If the calendar is visible, recenter it to DATE."
17784 (let* ((win (selected-window))
17785 (cwin (get-buffer-window "*Calendar*" t))
17786 (calendar-move-hook nil))
17787 (when cwin
17788 (select-window cwin)
17789 (calendar-goto-date (if (listp date) date
17790 (calendar-gregorian-from-absolute date)))
17791 (select-window win))))
17793 (defun org-goto-calendar (&optional arg)
17794 "Go to the Emacs calendar at the current date.
17795 If there is a time stamp in the current line, go to that date.
17796 A prefix ARG can be used to force the current date."
17797 (interactive "P")
17798 (let ((tsr org-ts-regexp) diff
17799 (calendar-move-hook nil)
17800 (view-calendar-holidays-initially nil)
17801 (view-diary-entries-initially nil))
17802 (if (or (org-at-timestamp-p)
17803 (save-excursion
17804 (beginning-of-line 1)
17805 (looking-at (concat ".*" tsr))))
17806 (let ((d1 (time-to-days (current-time)))
17807 (d2 (time-to-days
17808 (org-time-string-to-time (match-string 1)))))
17809 (setq diff (- d2 d1))))
17810 (calendar)
17811 (calendar-goto-today)
17812 (if (and diff (not arg)) (calendar-forward-day diff))))
17814 (defun org-get-date-from-calendar ()
17815 "Return a list (month day year) of date at point in calendar."
17816 (with-current-buffer "*Calendar*"
17817 (save-match-data
17818 (calendar-cursor-to-date))))
17820 (defun org-date-from-calendar ()
17821 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17822 If there is already a time stamp at the cursor position, update it."
17823 (interactive)
17824 (if (org-at-timestamp-p t)
17825 (org-timestamp-change 0 'calendar)
17826 (let ((cal-date (org-get-date-from-calendar)))
17827 (org-insert-time-stamp
17828 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17830 ;; Make appt aware of appointments from the agenda
17831 ;;;###autoload
17832 (defun org-agenda-to-appt (&optional filter)
17833 "Activate appointments found in `org-agenda-files'.
17834 When prefixed, prompt for a regular expression and use it as a
17835 filter: only add entries if they match this regular expression.
17837 FILTER can be a string. In this case, use this string as a
17838 regular expression to filter results.
17840 FILTER can also be an alist, with the car of each cell being
17841 either 'headline or 'category. For example:
17843 '((headline \"IMPORTANT\")
17844 (category \"Work\"))
17846 will only add headlines containing IMPORTANT or headlines
17847 belonging to the category \"Work\"."
17848 (interactive "P")
17849 (require 'calendar)
17850 (if (equal filter '(4))
17851 (setq filter (read-from-minibuffer "Regexp filter: ")))
17852 (let* ((cnt 0) ; count added events
17853 (org-agenda-new-buffers nil)
17854 (today (org-date-to-gregorian
17855 (time-to-days (current-time))))
17856 (files (org-agenda-files)) entries file)
17857 ;; Get all entries which may contain an appt
17858 (while (setq file (pop files))
17859 (setq entries
17860 (append entries
17861 (org-agenda-get-day-entries
17862 file today
17863 :timestamp :scheduled :deadline))))
17864 (setq entries (delq nil entries))
17865 ;; Map thru entries and find if they pass thru the filter
17866 (mapc
17867 (lambda(x)
17868 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17869 (cat (get-text-property 1 'org-category x))
17870 (tod (get-text-property 1 'time-of-day x))
17871 (ok (or (null filter)
17872 (and (stringp filter) (string-match filter evt))
17873 (and (listp filter)
17874 (or (string-match
17875 (cadr (assoc 'category filter)) cat)
17876 (string-match
17877 (cadr (assoc 'headline filter)) evt))))))
17878 ;; FIXME: Shall we remove text-properties for the appt text?
17879 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17880 (when (and ok tod)
17881 (setq tod (number-to-string tod)
17882 tod (when (string-match
17883 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17884 (concat (match-string 1 tod) ":"
17885 (match-string 2 tod))))
17886 (appt-add tod evt)
17887 (setq cnt (1+ cnt))))) entries)
17888 (org-release-buffers org-agenda-new-buffers)
17889 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17891 ;;; The clock for measuring work time.
17893 (defvar org-mode-line-string "")
17894 (put 'org-mode-line-string 'risky-local-variable t)
17896 (defvar org-mode-line-timer nil)
17897 (defvar org-clock-heading "")
17898 (defvar org-clock-start-time "")
17900 (defun org-update-mode-line ()
17901 (let* ((delta (- (time-to-seconds (current-time))
17902 (time-to-seconds org-clock-start-time)))
17903 (h (floor delta 3600))
17904 (m (floor (- delta (* 3600 h)) 60)))
17905 (setq org-mode-line-string
17906 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17907 'help-echo "Org-mode clock is running"))
17908 (force-mode-line-update)))
17910 (defvar org-clock-marker (make-marker)
17911 "Marker recording the last clock-in.")
17912 (defvar org-clock-mode-line-entry nil
17913 "Information for the modeline about the running clock.")
17915 (defun org-clock-in ()
17916 "Start the clock on the current item.
17917 If necessary, clock-out of the currently active clock."
17918 (interactive)
17919 (org-clock-out t)
17920 (let (ts)
17921 (save-excursion
17922 (org-back-to-heading t)
17923 (if (and org-clock-heading-function
17924 (functionp org-clock-heading-function))
17925 (setq org-clock-heading (funcall org-clock-heading-function))
17926 (if (looking-at org-complex-heading-regexp)
17927 (setq org-clock-heading (match-string 4))
17928 (setq org-clock-heading "???")))
17929 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17930 (org-clock-find-position)
17932 (insert "\n") (backward-char 1)
17933 (indent-relative)
17934 (insert org-clock-string " ")
17935 (setq org-clock-start-time (current-time))
17936 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17937 (move-marker org-clock-marker (point) (buffer-base-buffer))
17938 (or global-mode-string (setq global-mode-string '("")))
17939 (or (memq 'org-mode-line-string global-mode-string)
17940 (setq global-mode-string
17941 (append global-mode-string '(org-mode-line-string))))
17942 (org-update-mode-line)
17943 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17944 (message "Clock started at %s" ts))))
17946 (defun org-clock-find-position ()
17947 "Find the location where the next clock line should be inserted."
17948 (org-back-to-heading t)
17949 (catch 'exit
17950 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17951 (re (concat "^[ \t]*" org-clock-string))
17952 (cnt 0)
17953 first last)
17954 (goto-char beg)
17955 (when (eobp) (newline) (setq end (max (point) end)))
17956 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17957 ;; we seem to have a CLOCK drawer, so go there.
17958 (beginning-of-line 2)
17959 (throw 'exit t))
17960 ;; Lets count the CLOCK lines
17961 (goto-char beg)
17962 (while (re-search-forward re end t)
17963 (setq first (or first (match-beginning 0))
17964 last (match-beginning 0)
17965 cnt (1+ cnt)))
17966 (when (and (integerp org-clock-into-drawer)
17967 (>= (1+ cnt) org-clock-into-drawer))
17968 ;; Wrap current entries into a new drawer
17969 (goto-char last)
17970 (beginning-of-line 2)
17971 (if (org-at-item-p) (org-end-of-item))
17972 (insert ":END:\n")
17973 (beginning-of-line 0)
17974 (org-indent-line-function)
17975 (goto-char first)
17976 (insert ":CLOCK:\n")
17977 (beginning-of-line 0)
17978 (org-indent-line-function)
17979 (org-flag-drawer t)
17980 (beginning-of-line 2)
17981 (throw 'exit nil))
17983 (goto-char beg)
17984 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17985 (not (equal (match-string 1) org-clock-string)))
17986 ;; Planning info, skip to after it
17987 (beginning-of-line 2)
17988 (or (bolp) (newline)))
17989 (when (eq t org-clock-into-drawer)
17990 (insert ":CLOCK:\n:END:\n")
17991 (beginning-of-line -1)
17992 (org-indent-line-function)
17993 (org-flag-drawer t)
17994 (beginning-of-line 2)
17995 (org-indent-line-function)))))
17997 (defun org-clock-out (&optional fail-quietly)
17998 "Stop the currently running clock.
17999 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18000 (interactive)
18001 (catch 'exit
18002 (if (not (marker-buffer org-clock-marker))
18003 (if fail-quietly (throw 'exit t) (error "No active clock")))
18004 (let (ts te s h m)
18005 (save-excursion
18006 (set-buffer (marker-buffer org-clock-marker))
18007 (goto-char org-clock-marker)
18008 (beginning-of-line 1)
18009 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18010 (equal (match-string 1) org-clock-string))
18011 (setq ts (match-string 2))
18012 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18013 (goto-char (match-end 0))
18014 (delete-region (point) (point-at-eol))
18015 (insert "--")
18016 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18017 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18018 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18019 h (floor (/ s 3600))
18020 s (- s (* 3600 h))
18021 m (floor (/ s 60))
18022 s (- s (* 60 s)))
18023 (insert " => " (format "%2d:%02d" h m))
18024 (move-marker org-clock-marker nil)
18025 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18026 (org-log-done (org-parse-local-options logging 'org-log-done))
18027 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18028 (org-add-log-maybe 'clock-out))
18029 (when org-mode-line-timer
18030 (cancel-timer org-mode-line-timer)
18031 (setq org-mode-line-timer nil))
18032 (setq global-mode-string
18033 (delq 'org-mode-line-string global-mode-string))
18034 (force-mode-line-update)
18035 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18037 (defun org-clock-cancel ()
18038 "Cancel the running clock be removing the start timestamp."
18039 (interactive)
18040 (if (not (marker-buffer org-clock-marker))
18041 (error "No active clock"))
18042 (save-excursion
18043 (set-buffer (marker-buffer org-clock-marker))
18044 (goto-char org-clock-marker)
18045 (delete-region (1- (point-at-bol)) (point-at-eol)))
18046 (setq global-mode-string
18047 (delq 'org-mode-line-string global-mode-string))
18048 (force-mode-line-update)
18049 (message "Clock canceled"))
18051 (defun org-clock-goto (&optional delete-windows)
18052 "Go to the currently clocked-in entry."
18053 (interactive "P")
18054 (if (not (marker-buffer org-clock-marker))
18055 (error "No active clock"))
18056 (switch-to-buffer-other-window
18057 (marker-buffer org-clock-marker))
18058 (if delete-windows (delete-other-windows))
18059 (goto-char org-clock-marker)
18060 (org-show-entry)
18061 (org-back-to-heading)
18062 (recenter))
18064 (defvar org-clock-file-total-minutes nil
18065 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18066 (make-variable-buffer-local 'org-clock-file-total-minutes)
18068 (defun org-clock-sum (&optional tstart tend)
18069 "Sum the times for each subtree.
18070 Puts the resulting times in minutes as a text property on each headline."
18071 (interactive)
18072 (let* ((bmp (buffer-modified-p))
18073 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18074 org-clock-string
18075 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18076 (lmax 30)
18077 (ltimes (make-vector lmax 0))
18078 (t1 0)
18079 (level 0)
18080 ts te dt
18081 time)
18082 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18083 (save-excursion
18084 (goto-char (point-max))
18085 (while (re-search-backward re nil t)
18086 (cond
18087 ((match-end 2)
18088 ;; Two time stamps
18089 (setq ts (match-string 2)
18090 te (match-string 3)
18091 ts (time-to-seconds
18092 (apply 'encode-time (org-parse-time-string ts)))
18093 te (time-to-seconds
18094 (apply 'encode-time (org-parse-time-string te)))
18095 ts (if tstart (max ts tstart) ts)
18096 te (if tend (min te tend) te)
18097 dt (- te ts)
18098 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18099 ((match-end 4)
18100 ;; A naket time
18101 (setq t1 (+ t1 (string-to-number (match-string 5))
18102 (* 60 (string-to-number (match-string 4))))))
18103 (t ;; A headline
18104 (setq level (- (match-end 1) (match-beginning 1)))
18105 (when (or (> t1 0) (> (aref ltimes level) 0))
18106 (loop for l from 0 to level do
18107 (aset ltimes l (+ (aref ltimes l) t1)))
18108 (setq t1 0 time (aref ltimes level))
18109 (loop for l from level to (1- lmax) do
18110 (aset ltimes l 0))
18111 (goto-char (match-beginning 0))
18112 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18113 (setq org-clock-file-total-minutes (aref ltimes 0)))
18114 (set-buffer-modified-p bmp)))
18116 (defun org-clock-display (&optional total-only)
18117 "Show subtree times in the entire buffer.
18118 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18119 in the echo area."
18120 (interactive)
18121 (org-remove-clock-overlays)
18122 (let (time h m p)
18123 (org-clock-sum)
18124 (unless total-only
18125 (save-excursion
18126 (goto-char (point-min))
18127 (while (or (and (equal (setq p (point)) (point-min))
18128 (get-text-property p :org-clock-minutes))
18129 (setq p (next-single-property-change
18130 (point) :org-clock-minutes)))
18131 (goto-char p)
18132 (when (setq time (get-text-property p :org-clock-minutes))
18133 (org-put-clock-overlay time (funcall outline-level))))
18134 (setq h (/ org-clock-file-total-minutes 60)
18135 m (- org-clock-file-total-minutes (* 60 h)))
18136 ;; Arrange to remove the overlays upon next change.
18137 (when org-remove-highlights-with-change
18138 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18139 nil 'local))))
18140 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18142 (defvar org-clock-overlays nil)
18143 (make-variable-buffer-local 'org-clock-overlays)
18145 (defun org-put-clock-overlay (time &optional level)
18146 "Put an overlays on the current line, displaying TIME.
18147 If LEVEL is given, prefix time with a corresponding number of stars.
18148 This creates a new overlay and stores it in `org-clock-overlays', so that it
18149 will be easy to remove."
18150 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18151 (l (if level (org-get-legal-level level 0) 0))
18152 (off 0)
18153 ov tx)
18154 (move-to-column c)
18155 (unless (eolp) (skip-chars-backward "^ \t"))
18156 (skip-chars-backward " \t")
18157 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18158 tx (concat (buffer-substring (1- (point)) (point))
18159 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18160 (org-add-props (format "%s %2d:%02d%s"
18161 (make-string l ?*) h m
18162 (make-string (- 10 l) ?\ ))
18163 '(face secondary-selection))
18164 ""))
18165 (if (not (featurep 'xemacs))
18166 (org-overlay-put ov 'display tx)
18167 (org-overlay-put ov 'invisible t)
18168 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18169 (push ov org-clock-overlays)))
18171 (defun org-remove-clock-overlays (&optional beg end noremove)
18172 "Remove the occur highlights from the buffer.
18173 BEG and END are ignored. If NOREMOVE is nil, remove this function
18174 from the `before-change-functions' in the current buffer."
18175 (interactive)
18176 (unless org-inhibit-highlight-removal
18177 (mapc 'org-delete-overlay org-clock-overlays)
18178 (setq org-clock-overlays nil)
18179 (unless noremove
18180 (remove-hook 'before-change-functions
18181 'org-remove-clock-overlays 'local))))
18183 (defun org-clock-out-if-current ()
18184 "Clock out if the current entry contains the running clock.
18185 This is used to stop the clock after a TODO entry is marked DONE,
18186 and is only done if the variable `org-clock-out-when-done' is not nil."
18187 (when (and org-clock-out-when-done
18188 (member state org-done-keywords)
18189 (equal (marker-buffer org-clock-marker) (current-buffer))
18190 (< (point) org-clock-marker)
18191 (> (save-excursion (outline-next-heading) (point))
18192 org-clock-marker))
18193 ;; Clock out, but don't accept a logging message for this.
18194 (let ((org-log-done (if (and (listp org-log-done)
18195 (member 'clock-out org-log-done))
18196 '(done)
18197 org-log-done)))
18198 (org-clock-out))))
18200 (add-hook 'org-after-todo-state-change-hook
18201 'org-clock-out-if-current)
18203 (defun org-check-running-clock ()
18204 "Check if the current buffer contains the running clock.
18205 If yes, offer to stop it and to save the buffer with the changes."
18206 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18207 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18208 (buffer-name))))
18209 (org-clock-out)
18210 (when (y-or-n-p "Save changed buffer?")
18211 (save-buffer))))
18213 (defun org-clock-report (&optional arg)
18214 "Create a table containing a report about clocked time.
18215 If the cursor is inside an existing clocktable block, then the table
18216 will be updated. If not, a new clocktable will be inserted.
18217 When called with a prefix argument, move to the first clock table in the
18218 buffer and update it."
18219 (interactive "P")
18220 (org-remove-clock-overlays)
18221 (when arg (org-find-dblock "clocktable"))
18222 (if (org-in-clocktable-p)
18223 (goto-char (org-in-clocktable-p))
18224 (org-create-dblock (list :name "clocktable"
18225 :maxlevel 2 :scope 'file)))
18226 (org-update-dblock))
18228 (defun org-in-clocktable-p ()
18229 "Check if the cursor is in a clocktable."
18230 (let ((pos (point)) start)
18231 (save-excursion
18232 (end-of-line 1)
18233 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18234 (setq start (match-beginning 0))
18235 (re-search-forward "^#\\+END:.*" nil t)
18236 (>= (match-end 0) pos)
18237 start))))
18239 (defun org-clock-update-time-maybe ()
18240 "If this is a CLOCK line, update it and return t.
18241 Otherwise, return nil."
18242 (interactive)
18243 (save-excursion
18244 (beginning-of-line 1)
18245 (skip-chars-forward " \t")
18246 (when (looking-at org-clock-string)
18247 (let ((re (concat "[ \t]*" org-clock-string
18248 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18249 "\\([ \t]*=>.*\\)?"))
18250 ts te h m s)
18251 (if (not (looking-at re))
18253 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18254 (end-of-line 1)
18255 (setq ts (match-string 1)
18256 te (match-string 2))
18257 (setq s (- (time-to-seconds
18258 (apply 'encode-time (org-parse-time-string te)))
18259 (time-to-seconds
18260 (apply 'encode-time (org-parse-time-string ts))))
18261 h (floor (/ s 3600))
18262 s (- s (* 3600 h))
18263 m (floor (/ s 60))
18264 s (- s (* 60 s)))
18265 (insert " => " (format "%2d:%02d" h m))
18266 t)))))
18268 (defun org-clock-special-range (key &optional time as-strings)
18269 "Return two times bordering a special time range.
18270 Key is a symbol specifying the range and can be one of `today', `yesterday',
18271 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18272 A week starts Monday 0:00 and ends Sunday 24:00.
18273 The range is determined relative to TIME. TIME defaults to the current time.
18274 The return value is a cons cell with two internal times like the ones
18275 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18276 the returned times will be formatted strings."
18277 (let* ((tm (decode-time (or time (current-time))))
18278 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18279 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18280 (dow (nth 6 tm))
18281 s1 m1 h1 d1 month1 y1 diff ts te fm)
18282 (cond
18283 ((eq key 'today)
18284 (setq h 0 m 0 h1 24 m1 0))
18285 ((eq key 'yesterday)
18286 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18287 ((eq key 'thisweek)
18288 (setq diff (if (= dow 0) 6 (1- dow))
18289 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18290 ((eq key 'lastweek)
18291 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18292 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18293 ((eq key 'thismonth)
18294 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18295 ((eq key 'lastmonth)
18296 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18297 ((eq key 'thisyear)
18298 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18299 ((eq key 'lastyear)
18300 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18301 (t (error "No such time block %s" key)))
18302 (setq ts (encode-time s m h d month y)
18303 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18304 (or d1 d) (or month1 month) (or y1 y)))
18305 (setq fm (cdr org-time-stamp-formats))
18306 (if as-strings
18307 (cons (format-time-string fm ts) (format-time-string fm te))
18308 (cons ts te))))
18310 (defun org-dblock-write:clocktable (params)
18311 "Write the standard clocktable."
18312 (let ((hlchars '((1 . "*") (2 . "/")))
18313 (emph nil)
18314 (ins (make-marker))
18315 (total-time nil)
18316 ipos time h m p level hlc hdl maxlevel
18317 ts te cc block beg end pos scope tbl tostring multifile)
18318 (setq scope (plist-get params :scope)
18319 tostring (plist-get params :tostring)
18320 multifile (plist-get params :multifile)
18321 maxlevel (or (plist-get params :maxlevel) 3)
18322 emph (plist-get params :emphasize)
18323 ts (plist-get params :tstart)
18324 te (plist-get params :tend)
18325 block (plist-get params :block))
18326 (when block
18327 (setq cc (org-clock-special-range block nil t)
18328 ts (car cc) te (cdr cc)))
18329 (if ts (setq ts (time-to-seconds
18330 (apply 'encode-time (org-parse-time-string ts)))))
18331 (if te (setq te (time-to-seconds
18332 (apply 'encode-time (org-parse-time-string te)))))
18333 (move-marker ins (point))
18334 (setq ipos (point))
18336 ;; Get the right scope
18337 (setq pos (point))
18338 (save-restriction
18339 (cond
18340 ((not scope))
18341 ((eq scope 'file) (widen))
18342 ((eq scope 'subtree) (org-narrow-to-subtree))
18343 ((eq scope 'tree)
18344 (while (org-up-heading-safe))
18345 (org-narrow-to-subtree))
18346 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18347 (symbol-name scope)))
18348 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18349 (catch 'exit
18350 (while (org-up-heading-safe)
18351 (looking-at outline-regexp)
18352 (if (<= (org-reduced-level (funcall outline-level)) level)
18353 (throw 'exit nil))))
18354 (org-narrow-to-subtree))
18355 ((or (listp scope) (eq scope 'agenda))
18356 (let* ((files (if (listp scope) scope (org-agenda-files)))
18357 (scope 'agenda)
18358 (p1 (copy-sequence params))
18359 file)
18360 (plist-put p1 :tostring t)
18361 (plist-put p1 :multifile t)
18362 (plist-put p1 :scope 'file)
18363 (org-prepare-agenda-buffers files)
18364 (while (setq file (pop files))
18365 (with-current-buffer (find-buffer-visiting file)
18366 (push (org-clocktable-add-file
18367 file (org-dblock-write:clocktable p1)) tbl)
18368 (setq total-time (+ (or total-time 0)
18369 org-clock-file-total-minutes)))))))
18370 (goto-char pos)
18372 (unless (eq scope 'agenda)
18373 (org-clock-sum ts te)
18374 (goto-char (point-min))
18375 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18376 (goto-char p)
18377 (when (setq time (get-text-property p :org-clock-minutes))
18378 (save-excursion
18379 (beginning-of-line 1)
18380 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18381 (setq level (org-reduced-level
18382 (- (match-end 1) (match-beginning 1))))
18383 (<= level maxlevel))
18384 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18385 hdl (match-string 2)
18386 h (/ time 60)
18387 m (- time (* 60 h)))
18388 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18389 (push (concat
18390 "| " (int-to-string level) "|" hlc hdl hlc " |"
18391 (make-string (1- level) ?|)
18392 hlc (format "%d:%02d" h m) hlc
18393 " |") tbl))))))
18394 (setq tbl (nreverse tbl))
18395 (if tostring
18396 (if tbl (mapconcat 'identity tbl "\n") nil)
18397 (goto-char ins)
18398 (insert-before-markers
18399 "Clock summary at ["
18400 (substring
18401 (format-time-string (cdr org-time-stamp-formats))
18402 1 -1)
18403 "]."
18404 (if block
18405 (format " Considered range is /%s/." block)
18407 "\n\n"
18408 (if (eq scope 'agenda) "|File" "")
18409 "|L|Headline|Time|\n")
18410 (setq total-time (or total-time org-clock-file-total-minutes)
18411 h (/ total-time 60)
18412 m (- total-time (* 60 h)))
18413 (insert-before-markers
18414 "|-\n|"
18415 (if (eq scope 'agenda) "|" "")
18417 "*Total time*| "
18418 (format "*%d:%02d*" h m)
18419 "|\n|-\n")
18420 (setq tbl (delq nil tbl))
18421 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18422 (equal (substring (car tbl) 0 2) "|-"))
18423 (pop tbl))
18424 (insert-before-markers (mapconcat
18425 'identity (delq nil tbl)
18426 (if (eq scope 'agenda) "\n|-\n" "\n")))
18427 (backward-delete-char 1)
18428 (goto-char ipos)
18429 (skip-chars-forward "^|")
18430 (org-table-align)))))
18432 (defun org-clocktable-add-file (file table)
18433 (if table
18434 (let ((lines (org-split-string table "\n"))
18435 (ff (file-name-nondirectory file)))
18436 (mapconcat 'identity
18437 (mapcar (lambda (x)
18438 (if (string-match org-table-dataline-regexp x)
18439 (concat "|" ff x)
18441 lines)
18442 "\n"))))
18444 ;; FIXME: I don't think anybody uses this, ask David
18445 (defun org-collect-clock-time-entries ()
18446 "Return an internal list with clocking information.
18447 This list has one entry for each CLOCK interval.
18448 FIXME: describe the elements."
18449 (interactive)
18450 (let ((re (concat "^[ \t]*" org-clock-string
18451 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18452 rtn beg end next cont level title total closedp leafp
18453 clockpos titlepos h m donep)
18454 (save-excursion
18455 (org-clock-sum)
18456 (goto-char (point-min))
18457 (while (re-search-forward re nil t)
18458 (setq clockpos (match-beginning 0)
18459 beg (match-string 1) end (match-string 2)
18460 cont (match-end 0))
18461 (setq beg (apply 'encode-time (org-parse-time-string beg))
18462 end (apply 'encode-time (org-parse-time-string end)))
18463 (org-back-to-heading t)
18464 (setq donep (org-entry-is-done-p))
18465 (setq titlepos (point)
18466 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18467 h (/ total 60) m (- total (* 60 h))
18468 total (cons h m))
18469 (looking-at "\\(\\*+\\) +\\(.*\\)")
18470 (setq level (- (match-end 1) (match-beginning 1))
18471 title (org-match-string-no-properties 2))
18472 (save-excursion (outline-next-heading) (setq next (point)))
18473 (setq closedp (re-search-forward org-closed-time-regexp next t))
18474 (goto-char next)
18475 (setq leafp (and (looking-at "^\\*+ ")
18476 (<= (- (match-end 0) (point)) level)))
18477 (push (list beg end clockpos closedp donep
18478 total title titlepos level leafp)
18479 rtn)
18480 (goto-char cont)))
18481 (nreverse rtn)))
18483 ;;;; Agenda, and Diary Integration
18485 ;;; Define the Org-agenda-mode
18487 (defvar org-agenda-mode-map (make-sparse-keymap)
18488 "Keymap for `org-agenda-mode'.")
18490 (defvar org-agenda-menu) ; defined later in this file.
18491 (defvar org-agenda-follow-mode nil)
18492 (defvar org-agenda-show-log nil)
18493 (defvar org-agenda-redo-command nil)
18494 (defvar org-agenda-mode-hook nil)
18495 (defvar org-agenda-type nil)
18496 (defvar org-agenda-force-single-file nil)
18498 (defun org-agenda-mode ()
18499 "Mode for time-sorted view on action items in Org-mode files.
18501 The following commands are available:
18503 \\{org-agenda-mode-map}"
18504 (interactive)
18505 (kill-all-local-variables)
18506 (setq org-agenda-undo-list nil
18507 org-agenda-pending-undo-list nil)
18508 (setq major-mode 'org-agenda-mode)
18509 ;; Keep global-font-lock-mode from turning on font-lock-mode
18510 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18511 (setq mode-name "Org-Agenda")
18512 (use-local-map org-agenda-mode-map)
18513 (easy-menu-add org-agenda-menu)
18514 (if org-startup-truncated (setq truncate-lines t))
18515 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18516 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18517 ;; Make sure properties are removed when copying text
18518 (when (boundp 'buffer-substring-filters)
18519 (org-set-local 'buffer-substring-filters
18520 (cons (lambda (x)
18521 (set-text-properties 0 (length x) nil x) x)
18522 buffer-substring-filters)))
18523 (unless org-agenda-keep-modes
18524 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18525 org-agenda-show-log nil))
18526 (easy-menu-change
18527 '("Agenda") "Agenda Files"
18528 (append
18529 (list
18530 (vector
18531 (if (get 'org-agenda-files 'org-restrict)
18532 "Restricted to single file"
18533 "Edit File List")
18534 '(org-edit-agenda-file-list)
18535 (not (get 'org-agenda-files 'org-restrict)))
18536 "--")
18537 (mapcar 'org-file-menu-entry (org-agenda-files))))
18538 (org-agenda-set-mode-name)
18539 (apply
18540 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18541 (list 'org-agenda-mode-hook)))
18543 (substitute-key-definition 'undo 'org-agenda-undo
18544 org-agenda-mode-map global-map)
18545 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18546 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18547 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18548 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18549 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18550 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18551 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18552 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18553 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18554 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18555 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18556 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18557 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18558 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18559 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18560 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18561 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18562 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18563 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18564 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18565 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18566 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18567 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18568 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18569 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18570 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18571 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18572 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18573 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18575 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18576 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18577 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18578 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18579 (while l (org-defkey org-agenda-mode-map
18580 (int-to-string (pop l)) 'digit-argument)))
18582 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18583 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18584 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18585 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18586 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18587 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18588 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18589 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18590 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18591 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18592 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18593 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18594 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18595 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18596 (org-defkey org-agenda-mode-map "n" 'next-line)
18597 (org-defkey org-agenda-mode-map "p" 'previous-line)
18598 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18599 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18600 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18601 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18602 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18603 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18604 (eval-after-load "calendar"
18605 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18606 'org-calendar-goto-agenda))
18607 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18608 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18609 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18610 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18611 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18612 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18613 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18614 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18615 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18616 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18617 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18618 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18619 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18620 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18621 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18622 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18623 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18624 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18625 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18626 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18627 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18628 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18630 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18631 "Local keymap for agenda entries from Org-mode.")
18633 (org-defkey org-agenda-keymap
18634 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18635 (org-defkey org-agenda-keymap
18636 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18637 (when org-agenda-mouse-1-follows-link
18638 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18639 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18640 '("Agenda"
18641 ("Agenda Files")
18642 "--"
18643 ["Show" org-agenda-show t]
18644 ["Go To (other window)" org-agenda-goto t]
18645 ["Go To (this window)" org-agenda-switch-to t]
18646 ["Follow Mode" org-agenda-follow-mode
18647 :style toggle :selected org-agenda-follow-mode :active t]
18648 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18649 "--"
18650 ["Cycle TODO" org-agenda-todo t]
18651 ["Archive subtree" org-agenda-archive t]
18652 ["Delete subtree" org-agenda-kill t]
18653 "--"
18654 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18655 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18656 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18657 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18658 "--"
18659 ("Tags and Properties"
18660 ["Show all Tags" org-agenda-show-tags t]
18661 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18662 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18663 "--"
18664 ["Column View" org-columns t])
18665 ("Date/Schedule"
18666 ["Schedule" org-agenda-schedule t]
18667 ["Set Deadline" org-agenda-deadline t]
18668 "--"
18669 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18670 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18671 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18672 ("Clock"
18673 ["Clock in" org-agenda-clock-in t]
18674 ["Clock out" org-agenda-clock-out t]
18675 ["Clock cancel" org-agenda-clock-cancel t]
18676 ["Goto running clock" org-clock-goto t])
18677 ("Priority"
18678 ["Set Priority" org-agenda-priority t]
18679 ["Increase Priority" org-agenda-priority-up t]
18680 ["Decrease Priority" org-agenda-priority-down t]
18681 ["Show Priority" org-agenda-show-priority t])
18682 ("Calendar/Diary"
18683 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18684 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18685 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18686 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18687 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18688 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18689 "--"
18690 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18691 "--"
18692 ("View"
18693 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18694 :style radio :selected (equal org-agenda-ndays 1)]
18695 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18696 :style radio :selected (equal org-agenda-ndays 7)]
18697 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18698 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18699 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18700 :style radio :selected (member org-agenda-ndays '(365 366))]
18701 "--"
18702 ["Show Logbook entries" org-agenda-log-mode
18703 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18704 ["Include Diary" org-agenda-toggle-diary
18705 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18706 ["Use Time Grid" org-agenda-toggle-time-grid
18707 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18708 ["Write view to file" org-write-agenda t]
18709 ["Rebuild buffer" org-agenda-redo t]
18710 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18711 "--"
18712 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18713 "--"
18714 ["Quit" org-agenda-quit t]
18715 ["Exit and Release Buffers" org-agenda-exit t]
18718 ;;; Agenda undo
18720 (defvar org-agenda-allow-remote-undo t
18721 "Non-nil means, allow remote undo from the agenda buffer.")
18722 (defvar org-agenda-undo-list nil
18723 "List of undoable operations in the agenda since last refresh.")
18724 (defvar org-agenda-undo-has-started-in nil
18725 "Buffers that have already seen `undo-start' in the current undo sequence.")
18726 (defvar org-agenda-pending-undo-list nil
18727 "In a series of undo commands, this is the list of remaning undo items.")
18729 (defmacro org-if-unprotected (&rest body)
18730 "Execute BODY if there is no `org-protected' text property at point."
18731 (declare (debug t))
18732 `(unless (get-text-property (point) 'org-protected)
18733 ,@body))
18735 (defmacro org-with-remote-undo (_buffer &rest _body)
18736 "Execute BODY while recording undo information in two buffers."
18737 (declare (indent 1) (debug t))
18738 `(let ((_cline (org-current-line))
18739 (_cmd this-command)
18740 (_buf1 (current-buffer))
18741 (_buf2 ,_buffer)
18742 (_undo1 buffer-undo-list)
18743 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18744 _c1 _c2)
18745 ,@_body
18746 (when org-agenda-allow-remote-undo
18747 (setq _c1 (org-verify-change-for-undo
18748 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18749 _c2 (org-verify-change-for-undo
18750 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18751 (when (or _c1 _c2)
18752 ;; make sure there are undo boundaries
18753 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18754 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18755 ;; remember which buffer to undo
18756 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18757 org-agenda-undo-list)))))
18759 (defun org-agenda-undo ()
18760 "Undo a remote editing step in the agenda.
18761 This undoes changes both in the agenda buffer and in the remote buffer
18762 that have been changed along."
18763 (interactive)
18764 (or org-agenda-allow-remote-undo
18765 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18766 (if (not (eq this-command last-command))
18767 (setq org-agenda-undo-has-started-in nil
18768 org-agenda-pending-undo-list org-agenda-undo-list))
18769 (if (not org-agenda-pending-undo-list)
18770 (error "No further undo information"))
18771 (let* ((entry (pop org-agenda-pending-undo-list))
18772 buf line cmd rembuf)
18773 (setq cmd (pop entry) line (pop entry))
18774 (setq rembuf (nth 2 entry))
18775 (org-with-remote-undo rembuf
18776 (while (bufferp (setq buf (pop entry)))
18777 (if (pop entry)
18778 (with-current-buffer buf
18779 (let ((last-undo-buffer buf)
18780 (inhibit-read-only t))
18781 (unless (memq buf org-agenda-undo-has-started-in)
18782 (push buf org-agenda-undo-has-started-in)
18783 (make-local-variable 'pending-undo-list)
18784 (undo-start))
18785 (while (and pending-undo-list
18786 (listp pending-undo-list)
18787 (not (car pending-undo-list)))
18788 (pop pending-undo-list))
18789 (undo-more 1))))))
18790 (goto-line line)
18791 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18793 (defun org-verify-change-for-undo (l1 l2)
18794 "Verify that a real change occurred between the undo lists L1 and L2."
18795 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18796 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18797 (not (eq l1 l2)))
18799 ;;; Agenda dispatch
18801 (defvar org-agenda-restrict nil)
18802 (defvar org-agenda-restrict-begin (make-marker))
18803 (defvar org-agenda-restrict-end (make-marker))
18804 (defvar org-agenda-last-dispatch-buffer nil)
18805 (defvar org-agenda-overriding-restriction nil)
18807 ;;;###autoload
18808 (defun org-agenda (arg &optional keys restriction)
18809 "Dispatch agenda commands to collect entries to the agenda buffer.
18810 Prompts for a command to execute. Any prefix arg will be passed
18811 on to the selected command. The default selections are:
18813 a Call `org-agenda-list' to display the agenda for current day or week.
18814 t Call `org-todo-list' to display the global todo list.
18815 T Call `org-todo-list' to display the global todo list, select only
18816 entries with a specific TODO keyword (the user gets a prompt).
18817 m Call `org-tags-view' to display headlines with tags matching
18818 a condition (the user is prompted for the condition).
18819 M Like `m', but select only TODO entries, no ordinary headlines.
18820 L Create a timeline for the current buffer.
18821 e Export views to associated files.
18823 More commands can be added by configuring the variable
18824 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18825 searches can be pre-defined in this way.
18827 If the current buffer is in Org-mode and visiting a file, you can also
18828 first press `<' once to indicate that the agenda should be temporarily
18829 \(until the next use of \\[org-agenda]) restricted to the current file.
18830 Pressing `<' twice means to restrict to the current subtree or region
18831 \(if active)."
18832 (interactive "P")
18833 (catch 'exit
18834 (let* ((prefix-descriptions nil)
18835 (org-agenda-custom-commands
18836 ;; normalize different versions
18837 (delq nil
18838 (mapcar
18839 (lambda (x)
18840 (cond ((stringp (cdr x))
18841 (push x prefix-descriptions)
18842 nil)
18843 ((stringp (nth 1 x)) x)
18844 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18845 (t (cons (car x) (cons "" (cdr x))))))
18846 org-agenda-custom-commands)))
18847 (buf (current-buffer))
18848 (bfn (buffer-file-name (buffer-base-buffer)))
18849 entry key type match lprops ans)
18850 ;; Turn off restriction unless there is an overriding one
18851 (unless org-agenda-overriding-restriction
18852 (put 'org-agenda-files 'org-restrict nil)
18853 (setq org-agenda-restrict nil)
18854 (move-marker org-agenda-restrict-begin nil)
18855 (move-marker org-agenda-restrict-end nil))
18856 ;; Delete old local properties
18857 (put 'org-agenda-redo-command 'org-lprops nil)
18858 ;; Remember where this call originated
18859 (setq org-agenda-last-dispatch-buffer (current-buffer))
18860 (unless keys
18861 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18862 keys (car ans)
18863 restriction (cdr ans)))
18864 ;; Estabish the restriction, if any
18865 (when (and (not org-agenda-overriding-restriction) restriction)
18866 (put 'org-agenda-files 'org-restrict (list bfn))
18867 (cond
18868 ((eq restriction 'region)
18869 (setq org-agenda-restrict t)
18870 (move-marker org-agenda-restrict-begin (region-beginning))
18871 (move-marker org-agenda-restrict-end (region-end)))
18872 ((eq restriction 'subtree)
18873 (save-excursion
18874 (setq org-agenda-restrict t)
18875 (org-back-to-heading t)
18876 (move-marker org-agenda-restrict-begin (point))
18877 (move-marker org-agenda-restrict-end
18878 (progn (org-end-of-subtree t)))))))
18880 (require 'calendar) ; FIXME: can we avoid this for some commands?
18881 ;; For example the todo list should not need it (but does...)
18882 (cond
18883 ((setq entry (assoc keys org-agenda-custom-commands))
18884 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18885 (progn
18886 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18887 (put 'org-agenda-redo-command 'org-lprops lprops)
18888 (cond
18889 ((eq type 'agenda)
18890 (org-let lprops '(org-agenda-list current-prefix-arg)))
18891 ((eq type 'alltodo)
18892 (org-let lprops '(org-todo-list current-prefix-arg)))
18893 ((eq type 'stuck)
18894 (org-let lprops '(org-agenda-list-stuck-projects
18895 current-prefix-arg)))
18896 ((eq type 'tags)
18897 (org-let lprops '(org-tags-view current-prefix-arg match)))
18898 ((eq type 'tags-todo)
18899 (org-let lprops '(org-tags-view '(4) match)))
18900 ((eq type 'todo)
18901 (org-let lprops '(org-todo-list match)))
18902 ((eq type 'tags-tree)
18903 (org-check-for-org-mode)
18904 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18905 ((eq type 'todo-tree)
18906 (org-check-for-org-mode)
18907 (org-let lprops
18908 '(org-occur (concat "^" outline-regexp "[ \t]*"
18909 (regexp-quote match) "\\>"))))
18910 ((eq type 'occur-tree)
18911 (org-check-for-org-mode)
18912 (org-let lprops '(org-occur match)))
18913 ((functionp type)
18914 (org-let lprops '(funcall type match)))
18915 ((fboundp type)
18916 (org-let lprops '(funcall type match)))
18917 (t (error "Invalid custom agenda command type %s" type))))
18918 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18919 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18920 ((equal keys "a") (call-interactively 'org-agenda-list))
18921 ((equal keys "t") (call-interactively 'org-todo-list))
18922 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18923 ((equal keys "m") (call-interactively 'org-tags-view))
18924 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18925 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18926 ((equal keys "L")
18927 (unless (org-mode-p)
18928 (error "This is not an Org-mode file"))
18929 (unless restriction
18930 (put 'org-agenda-files 'org-restrict (list bfn))
18931 (org-call-with-arg 'org-timeline arg)))
18932 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18933 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18934 ((equal keys "!") (customize-variable 'org-stuck-projects))
18935 (t (error "Invalid agenda key"))))))
18937 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18938 "The user interface for selecting an agenda command."
18939 (catch 'exit
18940 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18941 (restrict-ok (and bfn (org-mode-p)))
18942 (region-p (org-region-active-p))
18943 (custom org-agenda-custom-commands)
18944 (selstring "")
18945 restriction second-time
18946 c entry key type match prefixes rmheader header-end custom1 desc)
18947 (save-window-excursion
18948 (delete-other-windows)
18949 (org-switch-to-buffer-other-window " *Agenda Commands*")
18950 (erase-buffer)
18951 (insert (eval-when-compile
18952 (let ((header
18954 Press key for an agenda command: < Buffer,subtree/region restriction
18955 -------------------------------- > Remove restriction
18956 a Agenda for current week or day e Export agenda views
18957 t List of all TODO entries T Entries with special TODO kwd
18958 m Match a TAGS query M Like m, but only TODO entries
18959 L Timeline for current buffer # List stuck projects (!=configure)
18960 / Multi-occur C Configure custom agenda commands
18962 (start 0))
18963 (while (string-match
18964 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18965 header start)
18966 (setq start (match-end 0))
18967 (add-text-properties (match-beginning 2) (match-end 2)
18968 '(face bold) header))
18969 header)))
18970 (setq header-end (move-marker (make-marker) (point)))
18971 (while t
18972 (setq custom1 custom)
18973 (when (eq rmheader t)
18974 (goto-line 1)
18975 (re-search-forward ":" nil t)
18976 (delete-region (match-end 0) (point-at-eol))
18977 (forward-char 1)
18978 (looking-at "-+")
18979 (delete-region (match-end 0) (point-at-eol))
18980 (move-marker header-end (match-end 0)))
18981 (goto-char header-end)
18982 (delete-region (point) (point-max))
18983 (while (setq entry (pop custom1))
18984 (setq key (car entry) desc (nth 1 entry)
18985 type (nth 2 entry) match (nth 3 entry))
18986 (if (> (length key) 1)
18987 (add-to-list 'prefixes (string-to-char key))
18988 (insert
18989 (format
18990 "\n%-4s%-14s: %s"
18991 (org-add-props (copy-sequence key)
18992 '(face bold))
18993 (cond
18994 ((string-match "\\S-" desc) desc)
18995 ((eq type 'agenda) "Agenda for current week or day")
18996 ((eq type 'alltodo) "List of all TODO entries")
18997 ((eq type 'stuck) "List of stuck projects")
18998 ((eq type 'todo) "TODO keyword")
18999 ((eq type 'tags) "Tags query")
19000 ((eq type 'tags-todo) "Tags (TODO)")
19001 ((eq type 'tags-tree) "Tags tree")
19002 ((eq type 'todo-tree) "TODO kwd tree")
19003 ((eq type 'occur-tree) "Occur tree")
19004 ((functionp type) (if (symbolp type)
19005 (symbol-name type)
19006 "Lambda expression"))
19007 (t "???"))
19008 (cond
19009 ((stringp match)
19010 (org-add-props match nil 'face 'org-warning))
19011 (match
19012 (format "set of %d commands" (length match)))
19013 (t ""))))))
19014 (when prefixes
19015 (mapc (lambda (x)
19016 (insert
19017 (format "\n%s %s"
19018 (org-add-props (char-to-string x)
19019 nil 'face 'bold)
19020 (or (cdr (assoc (concat selstring (char-to-string x))
19021 prefix-descriptions))
19022 "Prefix key"))))
19023 prefixes))
19024 (goto-char (point-min))
19025 (when (fboundp 'fit-window-to-buffer)
19026 (if second-time
19027 (if (not (pos-visible-in-window-p (point-max)))
19028 (fit-window-to-buffer))
19029 (setq second-time t)
19030 (fit-window-to-buffer)))
19031 (message "Press key for agenda command%s:"
19032 (if (or restrict-ok org-agenda-overriding-restriction)
19033 (if org-agenda-overriding-restriction
19034 " (restriction lock active)"
19035 (if restriction
19036 (format " (restricted to %s)" restriction)
19037 " (unrestricted)"))
19038 ""))
19039 (setq c (read-char-exclusive))
19040 (message "")
19041 (cond
19042 ((assoc (char-to-string c) custom)
19043 (setq selstring (concat selstring (char-to-string c)))
19044 (throw 'exit (cons selstring restriction)))
19045 ((memq c prefixes)
19046 (setq selstring (concat selstring (char-to-string c))
19047 prefixes nil
19048 rmheader (or rmheader t)
19049 custom (delq nil (mapcar
19050 (lambda (x)
19051 (if (or (= (length (car x)) 1)
19052 (/= (string-to-char (car x)) c))
19054 (cons (substring (car x) 1) (cdr x))))
19055 custom))))
19056 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19057 (message "Restriction is only possible in Org-mode buffers")
19058 (ding) (sit-for 1))
19059 ((eq c ?1)
19060 (org-agenda-remove-restriction-lock 'noupdate)
19061 (setq restriction 'buffer))
19062 ((eq c ?0)
19063 (org-agenda-remove-restriction-lock 'noupdate)
19064 (setq restriction (if region-p 'region 'subtree)))
19065 ((eq c ?<)
19066 (org-agenda-remove-restriction-lock 'noupdate)
19067 (setq restriction
19068 (cond
19069 ((eq restriction 'buffer)
19070 (if region-p 'region 'subtree))
19071 ((memq restriction '(subtree region))
19072 nil)
19073 (t 'buffer))))
19074 ((eq c ?>)
19075 (org-agenda-remove-restriction-lock 'noupdate)
19076 (setq restriction nil))
19077 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
19078 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19079 ((equal c ?q) (error "Abort"))
19080 (t (error "Invalid key %c" c))))))))
19082 (defun org-run-agenda-series (name series)
19083 (org-prepare-agenda name)
19084 (let* ((org-agenda-multi t)
19085 (redo (list 'org-run-agenda-series name (list 'quote series)))
19086 (cmds (car series))
19087 (gprops (nth 1 series))
19088 match ;; The byte compiler incorrectly complains about this. Keep it!
19089 cmd type lprops)
19090 (while (setq cmd (pop cmds))
19091 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19092 (cond
19093 ((eq type 'agenda)
19094 (org-let2 gprops lprops
19095 '(call-interactively 'org-agenda-list)))
19096 ((eq type 'alltodo)
19097 (org-let2 gprops lprops
19098 '(call-interactively 'org-todo-list)))
19099 ((eq type 'stuck)
19100 (org-let2 gprops lprops
19101 '(call-interactively 'org-agenda-list-stuck-projects)))
19102 ((eq type 'tags)
19103 (org-let2 gprops lprops
19104 '(org-tags-view current-prefix-arg match)))
19105 ((eq type 'tags-todo)
19106 (org-let2 gprops lprops
19107 '(org-tags-view '(4) match)))
19108 ((eq type 'todo)
19109 (org-let2 gprops lprops
19110 '(org-todo-list match)))
19111 ((fboundp type)
19112 (org-let2 gprops lprops
19113 '(funcall type match)))
19114 (t (error "Invalid type in command series"))))
19115 (widen)
19116 (setq org-agenda-redo-command redo)
19117 (goto-char (point-min)))
19118 (org-finalize-agenda))
19120 ;;;###autoload
19121 (defmacro org-batch-agenda (cmd-key &rest parameters)
19122 "Run an agenda command in batch mode and send the result to STDOUT.
19123 If CMD-KEY is a string of length 1, it is used as a key in
19124 `org-agenda-custom-commands' and triggers this command. If it is a
19125 longer string is is used as a tags/todo match string.
19126 Paramters are alternating variable names and values that will be bound
19127 before running the agenda command."
19128 (let (pars)
19129 (while parameters
19130 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19131 (if (> (length cmd-key) 2)
19132 (eval (list 'let (nreverse pars)
19133 (list 'org-tags-view nil cmd-key)))
19134 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19135 (set-buffer org-agenda-buffer-name)
19136 (princ (org-encode-for-stdout (buffer-string)))))
19138 (defun org-encode-for-stdout (string)
19139 (if (fboundp 'encode-coding-string)
19140 (encode-coding-string string buffer-file-coding-system)
19141 string))
19143 (defvar org-agenda-info nil)
19145 ;;;###autoload
19146 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19147 "Run an agenda command in batch mode and send the result to STDOUT.
19148 If CMD-KEY is a string of length 1, it is used as a key in
19149 `org-agenda-custom-commands' and triggers this command. If it is a
19150 longer string is is used as a tags/todo match string.
19151 Paramters are alternating variable names and values that will be bound
19152 before running the agenda command.
19154 The output gives a line for each selected agenda item. Each
19155 item is a list of comma-separated values, like this:
19157 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19159 category The category of the item
19160 head The headline, without TODO kwd, TAGS and PRIORITY
19161 type The type of the agenda entry, can be
19162 todo selected in TODO match
19163 tagsmatch selected in tags match
19164 diary imported from diary
19165 deadline a deadline on given date
19166 scheduled scheduled on given date
19167 timestamp entry has timestamp on given date
19168 closed entry was closed on given date
19169 upcoming-deadline warning about deadline
19170 past-scheduled forwarded scheduled item
19171 block entry has date block including g. date
19172 todo The todo keyword, if any
19173 tags All tags including inherited ones, separated by colons
19174 date The relevant date, like 2007-2-14
19175 time The time, like 15:00-16:50
19176 extra Sting with extra planning info
19177 priority-l The priority letter if any was given
19178 priority-n The computed numerical priority
19179 agenda-day The day in the agenda where this is listed"
19181 (let (pars)
19182 (while parameters
19183 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19184 (push (list 'org-agenda-remove-tags t) pars)
19185 (if (> (length cmd-key) 2)
19186 (eval (list 'let (nreverse pars)
19187 (list 'org-tags-view nil cmd-key)))
19188 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19189 (set-buffer org-agenda-buffer-name)
19190 (let* ((lines (org-split-string (buffer-string) "\n"))
19191 line)
19192 (while (setq line (pop lines))
19193 (catch 'next
19194 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19195 (setq org-agenda-info
19196 (org-fix-agenda-info (text-properties-at 0 line)))
19197 (princ
19198 (org-encode-for-stdout
19199 (mapconcat 'org-agenda-export-csv-mapper
19200 '(org-category txt type todo tags date time-of-day extra
19201 priority-letter priority agenda-day)
19202 ",")))
19203 (princ "\n"))))))
19205 (defun org-fix-agenda-info (props)
19206 "Make sure all properties on an agenda item have a canonical form,
19207 so the the export commands caneasily use it."
19208 (let (tmp re)
19209 (when (setq tmp (plist-get props 'tags))
19210 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19211 (when (setq tmp (plist-get props 'date))
19212 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19213 (let ((calendar-date-display-form '(year "-" month "-" day)))
19214 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19216 (setq tmp (calendar-date-string tmp)))
19217 (setq props (plist-put props 'date tmp)))
19218 (when (setq tmp (plist-get props 'day))
19219 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19220 (let ((calendar-date-display-form '(year "-" month "-" day)))
19221 (setq tmp (calendar-date-string tmp)))
19222 (setq props (plist-put props 'day tmp))
19223 (setq props (plist-put props 'agenda-day tmp)))
19224 (when (setq tmp (plist-get props 'txt))
19225 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19226 (plist-put props 'priority-letter (match-string 1 tmp))
19227 (setq tmp (replace-match "" t t tmp)))
19228 (when (and (setq re (plist-get props 'org-todo-regexp))
19229 (setq re (concat "\\`\\.*" re " ?"))
19230 (string-match re tmp))
19231 (plist-put props 'todo (match-string 1 tmp))
19232 (setq tmp (replace-match "" t t tmp)))
19233 (plist-put props 'txt tmp)))
19234 props)
19236 (defun org-agenda-export-csv-mapper (prop)
19237 (let ((res (plist-get org-agenda-info prop)))
19238 (setq res
19239 (cond
19240 ((not res) "")
19241 ((stringp res) res)
19242 (t (prin1-to-string res))))
19243 (while (string-match "," res)
19244 (setq res (replace-match ";" t t res)))
19245 (org-trim res)))
19248 ;;;###autoload
19249 (defun org-store-agenda-views (&rest parameters)
19250 (interactive)
19251 (eval (list 'org-batch-store-agenda-views)))
19253 ;; FIXME, why is this a macro?????
19254 ;;;###autoload
19255 (defmacro org-batch-store-agenda-views (&rest parameters)
19256 "Run all custom agenda commands that have a file argument."
19257 (let ((cmds org-agenda-custom-commands)
19258 (pop-up-frames nil)
19259 (dir default-directory)
19260 pars cmd thiscmdkey files opts)
19261 (while parameters
19262 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19263 (setq pars (reverse pars))
19264 (save-window-excursion
19265 (while cmds
19266 (setq cmd (pop cmds)
19267 thiscmdkey (car cmd)
19268 opts (nth 3 cmd)
19269 files (nth 4 cmd))
19270 (if (stringp files) (setq files (list files)))
19271 (when files
19272 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19273 (list 'org-agenda nil thiscmdkey)))
19274 (set-buffer org-agenda-buffer-name)
19275 (while files
19276 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19277 (list 'org-write-agenda
19278 (expand-file-name (pop files) dir) t))))
19279 (and (get-buffer org-agenda-buffer-name)
19280 (kill-buffer org-agenda-buffer-name)))))))
19282 (defun org-write-agenda (file &optional nosettings)
19283 "Write the current buffer (an agenda view) as a file.
19284 Depending on the extension of the file name, plain text (.txt),
19285 HTML (.html or .htm) or Postscript (.ps) is produced.
19286 If NOSETTINGS is given, do not scope the settings of
19287 `org-agenda-exporter-settings' into the export commands. This is used when
19288 the settings have already been scoped and we do not wish to overrule other,
19289 higher priority settings."
19290 (interactive "FWrite agenda to file: ")
19291 (if (not (file-writable-p file))
19292 (error "Cannot write agenda to file %s" file))
19293 (cond
19294 ((string-match "\\.html?\\'" file) (require 'htmlize))
19295 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19296 (org-let (if nosettings nil org-agenda-exporter-settings)
19297 '(save-excursion
19298 (save-window-excursion
19299 (cond
19300 ((string-match "\\.html?\\'" file)
19301 (set-buffer (htmlize-buffer (current-buffer)))
19303 (when (and org-agenda-export-html-style
19304 (string-match "<style>" org-agenda-export-html-style))
19305 ;; replace <style> section with org-agenda-export-html-style
19306 (goto-char (point-min))
19307 (kill-region (- (search-forward "<style") 6)
19308 (search-forward "</style>"))
19309 (insert org-agenda-export-html-style))
19310 (write-file file)
19311 (kill-buffer (current-buffer))
19312 (message "HTML written to %s" file))
19313 ((string-match "\\.ps\\'" file)
19314 (ps-print-buffer-with-faces file)
19315 (message "Postscript written to %s" file))
19317 (let ((bs (buffer-string)))
19318 (find-file file)
19319 (insert bs)
19320 (save-buffer 0)
19321 (kill-buffer (current-buffer))
19322 (message "Plain text written to %s" file))))))
19323 (set-buffer org-agenda-buffer-name)))
19325 (defmacro org-no-read-only (&rest body)
19326 "Inhibit read-only for BODY."
19327 `(let ((inhibit-read-only t)) ,@body))
19329 (defun org-check-for-org-mode ()
19330 "Make sure current buffer is in org-mode. Error if not."
19331 (or (org-mode-p)
19332 (error "Cannot execute org-mode agenda command on buffer in %s."
19333 major-mode)))
19335 (defun org-fit-agenda-window ()
19336 "Fit the window to the buffer size."
19337 (and (memq org-agenda-window-setup '(reorganize-frame))
19338 (fboundp 'fit-window-to-buffer)
19339 (fit-window-to-buffer
19341 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19342 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19344 ;;; Agenda file list
19346 (defun org-agenda-files (&optional unrestricted)
19347 "Get the list of agenda files.
19348 Optional UNRESTRICTED means return the full list even if a restriction
19349 is currently in place."
19350 (let ((files
19351 (cond
19352 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19353 ((stringp org-agenda-files) (org-read-agenda-file-list))
19354 ((listp org-agenda-files) org-agenda-files)
19355 (t (error "Invalid value of `org-agenda-files'")))))
19356 (setq files (apply 'append
19357 (mapcar (lambda (f)
19358 (if (file-directory-p f)
19359 (directory-files f t "\\.org\\'")
19360 (list f)))
19361 files)))
19362 (if org-agenda-skip-unavailable-files
19363 (delq nil
19364 (mapcar (function
19365 (lambda (file)
19366 (and (file-readable-p file) file)))
19367 files))
19368 files))) ; `org-check-agenda-file' will remove them from the list
19370 (defun org-edit-agenda-file-list ()
19371 "Edit the list of agenda files.
19372 Depending on setup, this either uses customize to edit the variable
19373 `org-agenda-files', or it visits the file that is holding the list. In the
19374 latter case, the buffer is set up in a way that saving it automatically kills
19375 the buffer and restores the previous window configuration."
19376 (interactive)
19377 (if (stringp org-agenda-files)
19378 (let ((cw (current-window-configuration)))
19379 (find-file org-agenda-files)
19380 (org-set-local 'org-window-configuration cw)
19381 (org-add-hook 'after-save-hook
19382 (lambda ()
19383 (set-window-configuration
19384 (prog1 org-window-configuration
19385 (kill-buffer (current-buffer))))
19386 (org-install-agenda-files-menu)
19387 (message "New agenda file list installed"))
19388 nil 'local)
19389 (message (substitute-command-keys
19390 "Edit list and finish with \\[save-buffer]")))
19391 (customize-variable 'org-agenda-files)))
19393 (defun org-store-new-agenda-file-list (list)
19394 "Set new value for the agenda file list and save it correcly."
19395 (if (stringp org-agenda-files)
19396 (let ((f org-agenda-files) b)
19397 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19398 (with-temp-file f
19399 (insert (mapconcat 'identity list "\n") "\n")))
19400 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19401 (setq org-agenda-files list)
19402 (customize-save-variable 'org-agenda-files org-agenda-files))))
19404 (defun org-read-agenda-file-list ()
19405 "Read the list of agenda files from a file."
19406 (when (stringp org-agenda-files)
19407 (with-temp-buffer
19408 (insert-file-contents org-agenda-files)
19409 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19412 ;;;###autoload
19413 (defun org-cycle-agenda-files ()
19414 "Cycle through the files in `org-agenda-files'.
19415 If the current buffer visits an agenda file, find the next one in the list.
19416 If the current buffer does not, find the first agenda file."
19417 (interactive)
19418 (let* ((fs (org-agenda-files t))
19419 (files (append fs (list (car fs))))
19420 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19421 file)
19422 (unless files (error "No agenda files"))
19423 (catch 'exit
19424 (while (setq file (pop files))
19425 (if (equal (file-truename file) tcf)
19426 (when (car files)
19427 (find-file (car files))
19428 (throw 'exit t))))
19429 (find-file (car fs)))
19430 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19432 (defun org-agenda-file-to-front (&optional to-end)
19433 "Move/add the current file to the top of the agenda file list.
19434 If the file is not present in the list, it is added to the front. If it is
19435 present, it is moved there. With optional argument TO-END, add/move to the
19436 end of the list."
19437 (interactive "P")
19438 (let ((org-agenda-skip-unavailable-files nil)
19439 (file-alist (mapcar (lambda (x)
19440 (cons (file-truename x) x))
19441 (org-agenda-files t)))
19442 (ctf (file-truename buffer-file-name))
19443 x had)
19444 (setq x (assoc ctf file-alist) had x)
19446 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19447 (if to-end
19448 (setq file-alist (append (delq x file-alist) (list x)))
19449 (setq file-alist (cons x (delq x file-alist))))
19450 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19451 (org-install-agenda-files-menu)
19452 (message "File %s to %s of agenda file list"
19453 (if had "moved" "added") (if to-end "end" "front"))))
19455 (defun org-remove-file (&optional file)
19456 "Remove current file from the list of files in variable `org-agenda-files'.
19457 These are the files which are being checked for agenda entries.
19458 Optional argument FILE means, use this file instead of the current."
19459 (interactive)
19460 (let* ((org-agenda-skip-unavailable-files nil)
19461 (file (or file buffer-file-name))
19462 (true-file (file-truename file))
19463 (afile (abbreviate-file-name file))
19464 (files (delq nil (mapcar
19465 (lambda (x)
19466 (if (equal true-file
19467 (file-truename x))
19468 nil x))
19469 (org-agenda-files t)))))
19470 (if (not (= (length files) (length (org-agenda-files t))))
19471 (progn
19472 (org-store-new-agenda-file-list files)
19473 (org-install-agenda-files-menu)
19474 (message "Removed file: %s" afile))
19475 (message "File was not in list: %s" afile))))
19477 (defun org-file-menu-entry (file)
19478 (vector file (list 'find-file file) t))
19480 (defun org-check-agenda-file (file)
19481 "Make sure FILE exists. If not, ask user what to do."
19482 (when (not (file-exists-p file))
19483 (message "non-existent file %s. [R]emove from list or [A]bort?"
19484 (abbreviate-file-name file))
19485 (let ((r (downcase (read-char-exclusive))))
19486 (cond
19487 ((equal r ?r)
19488 (org-remove-file file)
19489 (throw 'nextfile t))
19490 (t (error "Abort"))))))
19492 ;;; Agenda prepare and finalize
19494 (defvar org-agenda-multi nil) ; dynammically scoped
19495 (defvar org-agenda-buffer-name "*Org Agenda*")
19496 (defvar org-pre-agenda-window-conf nil)
19497 (defvar org-agenda-name nil)
19498 (defun org-prepare-agenda (&optional name)
19499 (setq org-todo-keywords-for-agenda nil)
19500 (setq org-done-keywords-for-agenda nil)
19501 (if org-agenda-multi
19502 (progn
19503 (setq buffer-read-only nil)
19504 (goto-char (point-max))
19505 (unless (or (bobp) org-agenda-compact-blocks)
19506 (insert "\n" (make-string (window-width) ?=) "\n"))
19507 (narrow-to-region (point) (point-max)))
19508 (org-agenda-maybe-reset-markers 'force)
19509 (org-prepare-agenda-buffers (org-agenda-files))
19510 (setq org-todo-keywords-for-agenda
19511 (org-uniquify org-todo-keywords-for-agenda))
19512 (setq org-done-keywords-for-agenda
19513 (org-uniquify org-done-keywords-for-agenda))
19514 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19515 (awin (get-buffer-window abuf)))
19516 (cond
19517 ((equal (current-buffer) abuf) nil)
19518 (awin (select-window awin))
19519 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19520 ((equal org-agenda-window-setup 'current-window)
19521 (switch-to-buffer abuf))
19522 ((equal org-agenda-window-setup 'other-window)
19523 (org-switch-to-buffer-other-window abuf))
19524 ((equal org-agenda-window-setup 'other-frame)
19525 (switch-to-buffer-other-frame abuf))
19526 ((equal org-agenda-window-setup 'reorganize-frame)
19527 (delete-other-windows)
19528 (org-switch-to-buffer-other-window abuf))))
19529 (setq buffer-read-only nil)
19530 (erase-buffer)
19531 (org-agenda-mode)
19532 (and name (not org-agenda-name)
19533 (org-set-local 'org-agenda-name name)))
19534 (setq buffer-read-only nil))
19536 (defun org-finalize-agenda ()
19537 "Finishing touch for the agenda buffer, called just before displaying it."
19538 (unless org-agenda-multi
19539 (save-excursion
19540 (let ((inhibit-read-only t))
19541 (goto-char (point-min))
19542 (while (org-activate-bracket-links (point-max))
19543 (add-text-properties (match-beginning 0) (match-end 0)
19544 '(face org-link)))
19545 (org-agenda-align-tags)
19546 (unless org-agenda-with-colors
19547 (remove-text-properties (point-min) (point-max) '(face nil))))
19548 (if (and (boundp 'org-overriding-columns-format)
19549 org-overriding-columns-format)
19550 (org-set-local 'org-overriding-columns-format
19551 org-overriding-columns-format))
19552 (if (and (boundp 'org-agenda-view-columns-initially)
19553 org-agenda-view-columns-initially)
19554 (org-agenda-columns))
19555 (when org-agenda-fontify-priorities
19556 (org-fontify-priorities))
19557 (run-hooks 'org-finalize-agenda-hook))))
19559 (defun org-fontify-priorities ()
19560 "Make highest priority lines bold, and lowest italic."
19561 (interactive)
19562 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19563 (org-delete-overlay o)))
19564 (org-overlays-in (point-min) (point-max)))
19565 (save-excursion
19566 (let ((inhibit-read-only t)
19567 b e p ov h l)
19568 (goto-char (point-min))
19569 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19570 (setq h (or (get-char-property (point) 'org-highest-priority)
19571 org-highest-priority)
19572 l (or (get-char-property (point) 'org-lowest-priority)
19573 org-lowest-priority)
19574 p (string-to-char (match-string 1))
19575 b (match-beginning 0) e (point-at-eol)
19576 ov (org-make-overlay b e))
19577 (org-overlay-put
19578 ov 'face
19579 (cond ((listp org-agenda-fontify-priorities)
19580 (cdr (assoc p org-agenda-fontify-priorities)))
19581 ((equal p l) 'italic)
19582 ((equal p h) 'bold)))
19583 (org-overlay-put ov 'org-type 'org-priority)))))
19585 (defun org-prepare-agenda-buffers (files)
19586 "Create buffers for all agenda files, protect archived trees and comments."
19587 (interactive)
19588 (let ((pa '(:org-archived t))
19589 (pc '(:org-comment t))
19590 (pall '(:org-archived t :org-comment t))
19591 (inhibit-read-only t)
19592 (rea (concat ":" org-archive-tag ":"))
19593 bmp file re)
19594 (save-excursion
19595 (save-restriction
19596 (while (setq file (pop files))
19597 (if (bufferp file)
19598 (set-buffer file)
19599 (org-check-agenda-file file)
19600 (set-buffer (org-get-agenda-file-buffer file)))
19601 (widen)
19602 (setq bmp (buffer-modified-p))
19603 (org-refresh-category-properties)
19604 (setq org-todo-keywords-for-agenda
19605 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19606 (setq org-done-keywords-for-agenda
19607 (append org-done-keywords-for-agenda org-done-keywords))
19608 (save-excursion
19609 (remove-text-properties (point-min) (point-max) pall)
19610 (when org-agenda-skip-archived-trees
19611 (goto-char (point-min))
19612 (while (re-search-forward rea nil t)
19613 (if (org-on-heading-p t)
19614 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19615 (goto-char (point-min))
19616 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19617 (while (re-search-forward re nil t)
19618 (add-text-properties
19619 (match-beginning 0) (org-end-of-subtree t) pc)))
19620 (set-buffer-modified-p bmp))))))
19622 (defvar org-agenda-skip-function nil
19623 "Function to be called at each match during agenda construction.
19624 If this function returns nil, the current match should not be skipped.
19625 Otherwise, the function must return a position from where the search
19626 should be continued.
19627 This may also be a Lisp form, it will be evaluated.
19628 Never set this variable using `setq' or so, because then it will apply
19629 to all future agenda commands. Instead, bind it with `let' to scope
19630 it dynamically into the agenda-constructing command. A good way to set
19631 it is through options in org-agenda-custom-commands.")
19633 (defun org-agenda-skip ()
19634 "Throw to `:skip' in places that should be skipped.
19635 Also moves point to the end of the skipped region, so that search can
19636 continue from there."
19637 (let ((p (point-at-bol)) to fp)
19638 (and org-agenda-skip-archived-trees
19639 (get-text-property p :org-archived)
19640 (org-end-of-subtree t)
19641 (throw :skip t))
19642 (and (get-text-property p :org-comment)
19643 (org-end-of-subtree t)
19644 (throw :skip t))
19645 (if (equal (char-after p) ?#) (throw :skip t))
19646 (when (and (or (setq fp (functionp org-agenda-skip-function))
19647 (consp org-agenda-skip-function))
19648 (setq to (save-excursion
19649 (save-match-data
19650 (if fp
19651 (funcall org-agenda-skip-function)
19652 (eval org-agenda-skip-function))))))
19653 (goto-char to)
19654 (throw :skip t))))
19656 (defvar org-agenda-markers nil
19657 "List of all currently active markers created by `org-agenda'.")
19658 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19659 "Creation time of the last agenda marker.")
19661 (defun org-agenda-new-marker (&optional pos)
19662 "Return a new agenda marker.
19663 Org-mode keeps a list of these markers and resets them when they are
19664 no longer in use."
19665 (let ((m (copy-marker (or pos (point)))))
19666 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19667 (push m org-agenda-markers)
19670 (defun org-agenda-maybe-reset-markers (&optional force)
19671 "Reset markers created by `org-agenda'. But only if they are old enough."
19672 (if (or (and force (not org-agenda-multi))
19673 (> (- (time-to-seconds (current-time))
19674 org-agenda-last-marker-time)
19676 (while org-agenda-markers
19677 (move-marker (pop org-agenda-markers) nil))))
19679 (defun org-get-agenda-file-buffer (file)
19680 "Get a buffer visiting FILE. If the buffer needs to be created, add
19681 it to the list of buffers which might be released later."
19682 (let ((buf (org-find-base-buffer-visiting file)))
19683 (if buf
19684 buf ; just return it
19685 ;; Make a new buffer and remember it
19686 (setq buf (find-file-noselect file))
19687 (if buf (push buf org-agenda-new-buffers))
19688 buf)))
19690 (defun org-release-buffers (blist)
19691 "Release all buffers in list, asking the user for confirmation when needed.
19692 When a buffer is unmodified, it is just killed. When modified, it is saved
19693 \(if the user agrees) and then killed."
19694 (let (buf file)
19695 (while (setq buf (pop blist))
19696 (setq file (buffer-file-name buf))
19697 (when (and (buffer-modified-p buf)
19698 file
19699 (y-or-n-p (format "Save file %s? " file)))
19700 (with-current-buffer buf (save-buffer)))
19701 (kill-buffer buf))))
19703 (defun org-get-category (&optional pos)
19704 "Get the category applying to position POS."
19705 (get-text-property (or pos (point)) 'org-category))
19707 ;;; Agenda timeline
19709 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19711 (defun org-timeline (&optional include-all)
19712 "Show a time-sorted view of the entries in the current org file.
19713 Only entries with a time stamp of today or later will be listed. With
19714 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19715 under the current date.
19716 If the buffer contains an active region, only check the region for
19717 dates."
19718 (interactive "P")
19719 (require 'calendar)
19720 (org-compile-prefix-format 'timeline)
19721 (org-set-sorting-strategy 'timeline)
19722 (let* ((dopast t)
19723 (dotodo include-all)
19724 (doclosed org-agenda-show-log)
19725 (entry buffer-file-name)
19726 (date (calendar-current-date))
19727 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19728 (end (if (org-region-active-p) (region-end) (point-max)))
19729 (day-numbers (org-get-all-dates beg end 'no-ranges
19730 t doclosed ; always include today
19731 org-timeline-show-empty-dates))
19732 (org-deadline-warning-days 0)
19733 (org-agenda-only-exact-dates t)
19734 (today (time-to-days (current-time)))
19735 (past t)
19736 args
19737 s e rtn d emptyp)
19738 (setq org-agenda-redo-command
19739 (list 'progn
19740 (list 'org-switch-to-buffer-other-window (current-buffer))
19741 (list 'org-timeline (list 'quote include-all))))
19742 (if (not dopast)
19743 ;; Remove past dates from the list of dates.
19744 (setq day-numbers (delq nil (mapcar (lambda(x)
19745 (if (>= x today) x nil))
19746 day-numbers))))
19747 (org-prepare-agenda (concat "Timeline "
19748 (file-name-nondirectory buffer-file-name)))
19749 (if doclosed (push :closed args))
19750 (push :timestamp args)
19751 (push :deadline args)
19752 (push :scheduled args)
19753 (push :sexp args)
19754 (if dotodo (push :todo args))
19755 (while (setq d (pop day-numbers))
19756 (if (and (listp d) (eq (car d) :omitted))
19757 (progn
19758 (setq s (point))
19759 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19760 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19761 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19762 (if (and (>= d today)
19763 dopast
19764 past)
19765 (progn
19766 (setq past nil)
19767 (insert (make-string 79 ?-) "\n")))
19768 (setq date (calendar-gregorian-from-absolute d))
19769 (setq s (point))
19770 (setq rtn (and (not emptyp)
19771 (apply 'org-agenda-get-day-entries entry
19772 date args)))
19773 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19774 (progn
19775 (insert
19776 (if (stringp org-agenda-format-date)
19777 (format-time-string org-agenda-format-date
19778 (org-time-from-absolute date))
19779 (funcall org-agenda-format-date date))
19780 "\n")
19781 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19782 (put-text-property s (1- (point)) 'org-date-line t)
19783 (if (equal d today)
19784 (put-text-property s (1- (point)) 'org-today t))
19785 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19786 (put-text-property s (1- (point)) 'day d)))))
19787 (goto-char (point-min))
19788 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19789 (point-min)))
19790 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19791 (org-finalize-agenda)
19792 (setq buffer-read-only t)))
19794 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19795 "Return a list of all relevant day numbers from BEG to END buffer positions.
19796 If NO-RANGES is non-nil, include only the start and end dates of a range,
19797 not every single day in the range. If FORCE-TODAY is non-nil, make
19798 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19799 inactive time stamps (those in square brackets) are included.
19800 When EMPTY is non-nil, also include days without any entries."
19801 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19802 dates dates1 date day day1 day2 ts1 ts2)
19803 (if force-today
19804 (setq dates (list (time-to-days (current-time)))))
19805 (save-excursion
19806 (goto-char beg)
19807 (while (re-search-forward re end t)
19808 (setq day (time-to-days (org-time-string-to-time
19809 (substring (match-string 1) 0 10))))
19810 (or (memq day dates) (push day dates)))
19811 (unless no-ranges
19812 (goto-char beg)
19813 (while (re-search-forward org-tr-regexp end t)
19814 (setq ts1 (substring (match-string 1) 0 10)
19815 ts2 (substring (match-string 2) 0 10)
19816 day1 (time-to-days (org-time-string-to-time ts1))
19817 day2 (time-to-days (org-time-string-to-time ts2)))
19818 (while (< (setq day1 (1+ day1)) day2)
19819 (or (memq day1 dates) (push day1 dates)))))
19820 (setq dates (sort dates '<))
19821 (when empty
19822 (while (setq day (pop dates))
19823 (setq day2 (car dates))
19824 (push day dates1)
19825 (when (and day2 empty)
19826 (if (or (eq empty t)
19827 (and (numberp empty) (<= (- day2 day) empty)))
19828 (while (< (setq day (1+ day)) day2)
19829 (push (list day) dates1))
19830 (push (cons :omitted (- day2 day)) dates1))))
19831 (setq dates (nreverse dates1)))
19832 dates)))
19834 ;;; Agenda Daily/Weekly
19836 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19837 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19838 (defvar org-agenda-last-arguments nil
19839 "The arguments of the previous call to org-agenda")
19840 (defvar org-starting-day nil) ; local variable in the agenda buffer
19841 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19842 (defvar org-include-all-loc nil) ; local variable
19843 (defvar org-agenda-remove-date nil) ; dynamically scoped
19845 ;;;###autoload
19846 (defun org-agenda-list (&optional include-all start-day ndays)
19847 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
19848 The view will be for the current day or week, but from the overview buffer
19849 you will be able to go to other days/weeks.
19851 With one \\[universal-argument] prefix argument INCLUDE-ALL,
19852 all unfinished TODO items will also be shown, before the agenda.
19853 This feature is considered obsolete, please use the TODO list or a block
19854 agenda instead.
19856 With a numeric prefix argument in an interactive call, the agenda will
19857 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
19858 the number of days. NDAYS defaults to `org-agenda-ndays'.
19860 START-DAY defaults to TODAY, or to the most recent match for the weekday
19861 given in `org-agenda-start-on-weekday'."
19862 (interactive "P")
19863 (if (and (integerp include-all) (> include-all 0))
19864 (setq ndays include-all include-all nil))
19865 (setq ndays (or ndays org-agenda-ndays)
19866 start-day (or start-day org-agenda-start-day))
19867 (if org-agenda-overriding-arguments
19868 (setq include-all (car org-agenda-overriding-arguments)
19869 start-day (nth 1 org-agenda-overriding-arguments)
19870 ndays (nth 2 org-agenda-overriding-arguments)))
19871 (if (stringp start-day)
19872 ;; Convert to an absolute day number
19873 (setq start-day (time-to-days (org-read-date nil t start-day))))
19874 (setq org-agenda-last-arguments (list include-all start-day ndays))
19875 (org-compile-prefix-format 'agenda)
19876 (org-set-sorting-strategy 'agenda)
19877 (require 'calendar)
19878 (let* ((org-agenda-start-on-weekday
19879 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19880 org-agenda-start-on-weekday nil))
19881 (thefiles (org-agenda-files))
19882 (files thefiles)
19883 (today (time-to-days
19884 (time-subtract (current-time)
19885 (list 0 (* 3600 org-extend-today-until) 0))))
19886 (sd (or start-day today))
19887 (start (if (or (null org-agenda-start-on-weekday)
19888 (< org-agenda-ndays 7))
19890 (let* ((nt (calendar-day-of-week
19891 (calendar-gregorian-from-absolute sd)))
19892 (n1 org-agenda-start-on-weekday)
19893 (d (- nt n1)))
19894 (- sd (+ (if (< d 0) 7 0) d)))))
19895 (day-numbers (list start))
19896 (day-cnt 0)
19897 (inhibit-redisplay (not debug-on-error))
19898 s e rtn rtnall file date d start-pos end-pos todayp nd)
19899 (setq org-agenda-redo-command
19900 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19901 ;; Make the list of days
19902 (setq ndays (or ndays org-agenda-ndays)
19903 nd ndays)
19904 (while (> ndays 1)
19905 (push (1+ (car day-numbers)) day-numbers)
19906 (setq ndays (1- ndays)))
19907 (setq day-numbers (nreverse day-numbers))
19908 (org-prepare-agenda "Day/Week")
19909 (org-set-local 'org-starting-day (car day-numbers))
19910 (org-set-local 'org-include-all-loc include-all)
19911 (org-set-local 'org-agenda-span
19912 (org-agenda-ndays-to-span nd))
19913 (when (and (or include-all org-agenda-include-all-todo)
19914 (member today day-numbers))
19915 (setq files thefiles
19916 rtnall nil)
19917 (while (setq file (pop files))
19918 (catch 'nextfile
19919 (org-check-agenda-file file)
19920 (setq date (calendar-gregorian-from-absolute today)
19921 rtn (org-agenda-get-day-entries
19922 file date :todo))
19923 (setq rtnall (append rtnall rtn))))
19924 (when rtnall
19925 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19926 (add-text-properties (point-min) (1- (point))
19927 (list 'face 'org-agenda-structure))
19928 (insert (org-finalize-agenda-entries rtnall) "\n")))
19929 (unless org-agenda-compact-blocks
19930 (setq s (point))
19931 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19932 "-agenda:\n")
19933 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19934 'org-date-line t)))
19935 (while (setq d (pop day-numbers))
19936 (setq date (calendar-gregorian-from-absolute d)
19937 s (point))
19938 (if (or (setq todayp (= d today))
19939 (and (not start-pos) (= d sd)))
19940 (setq start-pos (point))
19941 (if (and start-pos (not end-pos))
19942 (setq end-pos (point))))
19943 (setq files thefiles
19944 rtnall nil)
19945 (while (setq file (pop files))
19946 (catch 'nextfile
19947 (org-check-agenda-file file)
19948 (if org-agenda-show-log
19949 (setq rtn (org-agenda-get-day-entries
19950 file date
19951 :deadline :scheduled :timestamp :sexp :closed))
19952 (setq rtn (org-agenda-get-day-entries
19953 file date
19954 :deadline :scheduled :sexp :timestamp)))
19955 (setq rtnall (append rtnall rtn))))
19956 (if org-agenda-include-diary
19957 (progn
19958 (require 'diary-lib)
19959 (setq rtn (org-get-entries-from-diary date))
19960 (setq rtnall (append rtnall rtn))))
19961 (if (or rtnall org-agenda-show-all-dates)
19962 (progn
19963 (setq day-cnt (1+ day-cnt))
19964 (insert
19965 (if (stringp org-agenda-format-date)
19966 (format-time-string org-agenda-format-date
19967 (org-time-from-absolute date))
19968 (funcall org-agenda-format-date date))
19969 "\n")
19970 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19971 (put-text-property s (1- (point)) 'org-date-line t)
19972 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19973 (if todayp (put-text-property s (1- (point)) 'org-today t))
19974 (if rtnall (insert
19975 (org-finalize-agenda-entries
19976 (org-agenda-add-time-grid-maybe
19977 rtnall nd todayp))
19978 "\n"))
19979 (put-text-property s (1- (point)) 'day d)
19980 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19981 (goto-char (point-min))
19982 (org-fit-agenda-window)
19983 (unless (and (pos-visible-in-window-p (point-min))
19984 (pos-visible-in-window-p (point-max)))
19985 (goto-char (1- (point-max)))
19986 (recenter -1)
19987 (if (not (pos-visible-in-window-p (or start-pos 1)))
19988 (progn
19989 (goto-char (or start-pos 1))
19990 (recenter 1))))
19991 (goto-char (or start-pos 1))
19992 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19993 (org-finalize-agenda)
19994 (setq buffer-read-only t)
19995 (message "")))
19997 (defun org-agenda-ndays-to-span (n)
19998 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20000 ;;; Agenda TODO list
20002 (defvar org-select-this-todo-keyword nil)
20003 (defvar org-last-arg nil)
20005 ;;;###autoload
20006 (defun org-todo-list (arg)
20007 "Show all TODO entries from all agenda file in a single list.
20008 The prefix arg can be used to select a specific TODO keyword and limit
20009 the list to these. When using \\[universal-argument], you will be prompted
20010 for a keyword. A numeric prefix directly selects the Nth keyword in
20011 `org-todo-keywords-1'."
20012 (interactive "P")
20013 (require 'calendar)
20014 (org-compile-prefix-format 'todo)
20015 (org-set-sorting-strategy 'todo)
20016 (org-prepare-agenda "TODO")
20017 (let* ((today (time-to-days (current-time)))
20018 (date (calendar-gregorian-from-absolute today))
20019 (kwds org-todo-keywords-for-agenda)
20020 (completion-ignore-case t)
20021 (org-select-this-todo-keyword
20022 (if (stringp arg) arg
20023 (and arg (integerp arg) (> arg 0)
20024 (nth (1- arg) kwds))))
20025 rtn rtnall files file pos)
20026 (when (equal arg '(4))
20027 (setq org-select-this-todo-keyword
20028 (completing-read "Keyword (or KWD1|K2D2|...): "
20029 (mapcar 'list kwds) nil nil)))
20030 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20031 (org-set-local 'org-last-arg arg)
20032 (setq org-agenda-redo-command
20033 '(org-todo-list (or current-prefix-arg org-last-arg)))
20034 (setq files (org-agenda-files)
20035 rtnall nil)
20036 (while (setq file (pop files))
20037 (catch 'nextfile
20038 (org-check-agenda-file file)
20039 (setq rtn (org-agenda-get-day-entries file date :todo))
20040 (setq rtnall (append rtnall rtn))))
20041 (if org-agenda-overriding-header
20042 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20043 nil 'face 'org-agenda-structure) "\n")
20044 (insert "Global list of TODO items of type: ")
20045 (add-text-properties (point-min) (1- (point))
20046 (list 'face 'org-agenda-structure))
20047 (setq pos (point))
20048 (insert (or org-select-this-todo-keyword "ALL") "\n")
20049 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20050 (setq pos (point))
20051 (unless org-agenda-multi
20052 (insert "Available with `N r': (0)ALL")
20053 (let ((n 0) s)
20054 (mapc (lambda (x)
20055 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20056 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20057 (insert "\n "))
20058 (insert " " s))
20059 kwds))
20060 (insert "\n"))
20061 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20062 (when rtnall
20063 (insert (org-finalize-agenda-entries rtnall) "\n"))
20064 (goto-char (point-min))
20065 (org-fit-agenda-window)
20066 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20067 (org-finalize-agenda)
20068 (setq buffer-read-only t)))
20070 ;;; Agenda tags match
20072 ;;;###autoload
20073 (defun org-tags-view (&optional todo-only match)
20074 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20075 The prefix arg TODO-ONLY limits the search to TODO entries."
20076 (interactive "P")
20077 (org-compile-prefix-format 'tags)
20078 (org-set-sorting-strategy 'tags)
20079 (let* ((org-tags-match-list-sublevels
20080 (if todo-only t org-tags-match-list-sublevels))
20081 (completion-ignore-case t)
20082 rtn rtnall files file pos matcher
20083 buffer)
20084 (setq matcher (org-make-tags-matcher match)
20085 match (car matcher) matcher (cdr matcher))
20086 (org-prepare-agenda (concat "TAGS " match))
20087 (setq org-agenda-redo-command
20088 (list 'org-tags-view (list 'quote todo-only)
20089 (list 'if 'current-prefix-arg nil match)))
20090 (setq files (org-agenda-files)
20091 rtnall nil)
20092 (while (setq file (pop files))
20093 (catch 'nextfile
20094 (org-check-agenda-file file)
20095 (setq buffer (if (file-exists-p file)
20096 (org-get-agenda-file-buffer file)
20097 (error "No such file %s" file)))
20098 (if (not buffer)
20099 ;; If file does not exist, merror message to agenda
20100 (setq rtn (list
20101 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20102 rtnall (append rtnall rtn))
20103 (with-current-buffer buffer
20104 (unless (org-mode-p)
20105 (error "Agenda file %s is not in `org-mode'" file))
20106 (save-excursion
20107 (save-restriction
20108 (if org-agenda-restrict
20109 (narrow-to-region org-agenda-restrict-begin
20110 org-agenda-restrict-end)
20111 (widen))
20112 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20113 (setq rtnall (append rtnall rtn))))))))
20114 (if org-agenda-overriding-header
20115 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20116 nil 'face 'org-agenda-structure) "\n")
20117 (insert "Headlines with TAGS match: ")
20118 (add-text-properties (point-min) (1- (point))
20119 (list 'face 'org-agenda-structure))
20120 (setq pos (point))
20121 (insert match "\n")
20122 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20123 (setq pos (point))
20124 (unless org-agenda-multi
20125 (insert "Press `C-u r' to search again with new search string\n"))
20126 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20127 (when rtnall
20128 (insert (org-finalize-agenda-entries rtnall) "\n"))
20129 (goto-char (point-min))
20130 (org-fit-agenda-window)
20131 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20132 (org-finalize-agenda)
20133 (setq buffer-read-only t)))
20135 ;;; Agenda Finding stuck projects
20137 (defvar org-agenda-skip-regexp nil
20138 "Regular expression used in skipping subtrees for the agenda.
20139 This is basically a temporary global variable that can be set and then
20140 used by user-defined selections using `org-agenda-skip-function'.")
20142 (defvar org-agenda-overriding-header nil
20143 "When this is set during todo and tags searches, will replace header.")
20145 (defun org-agenda-skip-subtree-when-regexp-matches ()
20146 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20147 If yes, it returns the end position of this tree, causing agenda commands
20148 to skip this subtree. This is a function that can be put into
20149 `org-agenda-skip-function' for the duration of a command."
20150 (let ((end (save-excursion (org-end-of-subtree t)))
20151 skip)
20152 (save-excursion
20153 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20154 (and skip end)))
20156 (defun org-agenda-skip-entry-if (&rest conditions)
20157 "Skip entry if any of CONDITIONS is true.
20158 See `org-agenda-skip-if for details."
20159 (org-agenda-skip-if nil conditions))
20161 (defun org-agenda-skip-subtree-if (&rest conditions)
20162 "Skip entry if any of CONDITIONS is true.
20163 See `org-agenda-skip-if for details."
20164 (org-agenda-skip-if t conditions))
20166 (defun org-agenda-skip-if (subtree conditions)
20167 "Checks current entity for CONDITIONS.
20168 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20169 the entry, i.e. the text before the next heading is checked.
20171 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20172 from different tests. Valid conditions are:
20174 scheduled Check if there is a scheduled cookie
20175 notscheduled Check if there is no scheduled cookie
20176 deadline Check if there is a deadline
20177 notdeadline Check if there is no deadline
20178 regexp Check if regexp matches
20179 notregexp Check if regexp does not match.
20181 The regexp is taken from the conditions list, it must com right after the
20182 `regexp' of `notregexp' element.
20184 If any of these conditions is met, this function returns the end point of
20185 the entity, causing the search to continue from there. This is a function
20186 that can be put into `org-agenda-skip-function' for the duration of a command."
20187 (let (beg end m)
20188 (org-back-to-heading t)
20189 (setq beg (point)
20190 end (if subtree
20191 (progn (org-end-of-subtree t) (point))
20192 (progn (outline-next-heading) (1- (point)))))
20193 (goto-char beg)
20194 (and
20196 (and (memq 'scheduled conditions)
20197 (re-search-forward org-scheduled-time-regexp end t))
20198 (and (memq 'notscheduled conditions)
20199 (not (re-search-forward org-scheduled-time-regexp end t)))
20200 (and (memq 'deadline conditions)
20201 (re-search-forward org-deadline-time-regexp end t))
20202 (and (memq 'notdeadline conditions)
20203 (not (re-search-forward org-deadline-time-regexp end t)))
20204 (and (setq m (memq 'regexp conditions))
20205 (stringp (nth 1 m))
20206 (re-search-forward (nth 1 m) end t))
20207 (and (setq m (memq 'notregexp conditions))
20208 (stringp (nth 1 m))
20209 (not (re-search-forward (nth 1 m) end t))))
20210 end)))
20212 ;;;###autoload
20213 (defun org-agenda-list-stuck-projects (&rest ignore)
20214 "Create agenda view for projects that are stuck.
20215 Stuck projects are project that have no next actions. For the definitions
20216 of what a project is and how to check if it stuck, customize the variable
20217 `org-stuck-projects'.
20218 MATCH is being ignored."
20219 (interactive)
20220 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20221 ;; FIXME: we could have used org-agenda-skip-if here.
20222 (org-agenda-overriding-header "List of stuck projects: ")
20223 (matcher (nth 0 org-stuck-projects))
20224 (todo (nth 1 org-stuck-projects))
20225 (todo-wds (if (member "*" todo)
20226 (progn
20227 (org-prepare-agenda-buffers (org-agenda-files))
20228 (org-delete-all
20229 org-done-keywords-for-agenda
20230 (copy-sequence org-todo-keywords-for-agenda)))
20231 todo))
20232 (todo-re (concat "^\\*+[ \t]+\\("
20233 (mapconcat 'identity todo-wds "\\|")
20234 "\\)\\>"))
20235 (tags (nth 2 org-stuck-projects))
20236 (tags-re (if (member "*" tags)
20237 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20238 (concat "^\\*+ .*:\\("
20239 (mapconcat 'identity tags "\\|")
20240 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20241 (gen-re (nth 3 org-stuck-projects))
20242 (re-list
20243 (delq nil
20244 (list
20245 (if todo todo-re)
20246 (if tags tags-re)
20247 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20248 gen-re)))))
20249 (setq org-agenda-skip-regexp
20250 (if re-list
20251 (mapconcat 'identity re-list "\\|")
20252 (error "No information how to identify unstuck projects")))
20253 (org-tags-view nil matcher)
20254 (with-current-buffer org-agenda-buffer-name
20255 (setq org-agenda-redo-command
20256 '(org-agenda-list-stuck-projects
20257 (or current-prefix-arg org-last-arg))))))
20259 ;;; Diary integration
20261 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20263 (defun org-get-entries-from-diary (date)
20264 "Get the (Emacs Calendar) diary entries for DATE."
20265 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20266 (diary-display-hook '(fancy-diary-display))
20267 (pop-up-frames nil)
20268 (list-diary-entries-hook
20269 (cons 'org-diary-default-entry list-diary-entries-hook))
20270 (diary-file-name-prefix-function nil) ; turn this feature off
20271 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20272 entries
20273 (org-disable-agenda-to-diary t))
20274 (save-excursion
20275 (save-window-excursion
20276 (funcall (if (fboundp 'diary-list-entries)
20277 'diary-list-entries 'list-diary-entries)
20278 date 1)))
20279 (if (not (get-buffer fancy-diary-buffer))
20280 (setq entries nil)
20281 (with-current-buffer fancy-diary-buffer
20282 (setq buffer-read-only nil)
20283 (if (zerop (buffer-size))
20284 ;; No entries
20285 (setq entries nil)
20286 ;; Omit the date and other unnecessary stuff
20287 (org-agenda-cleanup-fancy-diary)
20288 ;; Add prefix to each line and extend the text properties
20289 (if (zerop (buffer-size))
20290 (setq entries nil)
20291 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20292 (set-buffer-modified-p nil)
20293 (kill-buffer fancy-diary-buffer)))
20294 (when entries
20295 (setq entries (org-split-string entries "\n"))
20296 (setq entries
20297 (mapcar
20298 (lambda (x)
20299 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20300 ;; Extend the text properties to the beginning of the line
20301 (org-add-props x (text-properties-at (1- (length x)) x)
20302 'type "diary" 'date date))
20303 entries)))))
20305 (defun org-agenda-cleanup-fancy-diary ()
20306 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20307 This gets rid of the date, the underline under the date, and
20308 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20309 date. It also removes lines that contain only whitespace."
20310 (goto-char (point-min))
20311 (if (looking-at ".*?:[ \t]*")
20312 (progn
20313 (replace-match "")
20314 (re-search-forward "\n=+$" nil t)
20315 (replace-match "")
20316 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20317 (re-search-forward "\n=+$" nil t)
20318 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20319 (goto-char (point-min))
20320 (while (re-search-forward "^ +\n" nil t)
20321 (replace-match ""))
20322 (goto-char (point-min))
20323 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20324 (replace-match "")))
20326 ;; Make sure entries from the diary have the right text properties.
20327 (eval-after-load "diary-lib"
20328 '(if (boundp 'diary-modify-entry-list-string-function)
20329 ;; We can rely on the hook, nothing to do
20331 ;; Hook not avaiable, must use advice to make this work
20332 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20333 "Make the position visible."
20334 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20335 (stringp string)
20336 buffer-file-name)
20337 (setq string (org-modify-diary-entry-string string))))))
20339 (defun org-modify-diary-entry-string (string)
20340 "Add text properties to string, allowing org-mode to act on it."
20341 (org-add-props string nil
20342 'mouse-face 'highlight
20343 'keymap org-agenda-keymap
20344 'help-echo (if buffer-file-name
20345 (format "mouse-2 or RET jump to diary file %s"
20346 (abbreviate-file-name buffer-file-name))
20348 'org-agenda-diary-link t
20349 'org-marker (org-agenda-new-marker (point-at-bol))))
20351 (defun org-diary-default-entry ()
20352 "Add a dummy entry to the diary.
20353 Needed to avoid empty dates which mess up holiday display."
20354 ;; Catch the error if dealing with the new add-to-diary-alist
20355 (when org-disable-agenda-to-diary
20356 (condition-case nil
20357 (add-to-diary-list original-date "Org-mode dummy" "")
20358 (error
20359 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20361 ;;;###autoload
20362 (defun org-diary (&rest args)
20363 "Return diary information from org-files.
20364 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20365 It accesses org files and extracts information from those files to be
20366 listed in the diary. The function accepts arguments specifying what
20367 items should be listed. The following arguments are allowed:
20369 :timestamp List the headlines of items containing a date stamp or
20370 date range matching the selected date. Deadlines will
20371 also be listed, on the expiration day.
20373 :sexp List entries resulting from diary-like sexps.
20375 :deadline List any deadlines past due, or due within
20376 `org-deadline-warning-days'. The listing occurs only
20377 in the diary for *today*, not at any other date. If
20378 an entry is marked DONE, it is no longer listed.
20380 :scheduled List all items which are scheduled for the given date.
20381 The diary for *today* also contains items which were
20382 scheduled earlier and are not yet marked DONE.
20384 :todo List all TODO items from the org-file. This may be a
20385 long list - so this is not turned on by default.
20386 Like deadlines, these entries only show up in the
20387 diary for *today*, not at any other date.
20389 The call in the diary file should look like this:
20391 &%%(org-diary) ~/path/to/some/orgfile.org
20393 Use a separate line for each org file to check. Or, if you omit the file name,
20394 all files listed in `org-agenda-files' will be checked automatically:
20396 &%%(org-diary)
20398 If you don't give any arguments (as in the example above), the default
20399 arguments (:deadline :scheduled :timestamp :sexp) are used.
20400 So the example above may also be written as
20402 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20404 The function expects the lisp variables `entry' and `date' to be provided
20405 by the caller, because this is how the calendar works. Don't use this
20406 function from a program - use `org-agenda-get-day-entries' instead."
20407 (org-agenda-maybe-reset-markers)
20408 (org-compile-prefix-format 'agenda)
20409 (org-set-sorting-strategy 'agenda)
20410 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20411 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20412 (list entry)
20413 (org-agenda-files t)))
20414 file rtn results)
20415 (org-prepare-agenda-buffers files)
20416 ;; If this is called during org-agenda, don't return any entries to
20417 ;; the calendar. Org Agenda will list these entries itself.
20418 (if org-disable-agenda-to-diary (setq files nil))
20419 (while (setq file (pop files))
20420 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20421 (setq results (append results rtn)))
20422 (if results
20423 (concat (org-finalize-agenda-entries results) "\n"))))
20425 ;;; Agenda entry finders
20427 (defun org-agenda-get-day-entries (file date &rest args)
20428 "Does the work for `org-diary' and `org-agenda'.
20429 FILE is the path to a file to be checked for entries. DATE is date like
20430 the one returned by `calendar-current-date'. ARGS are symbols indicating
20431 which kind of entries should be extracted. For details about these, see
20432 the documentation of `org-diary'."
20433 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20434 (let* ((org-startup-folded nil)
20435 (org-startup-align-all-tables nil)
20436 (buffer (if (file-exists-p file)
20437 (org-get-agenda-file-buffer file)
20438 (error "No such file %s" file)))
20439 arg results rtn)
20440 (if (not buffer)
20441 ;; If file does not exist, make sure an error message ends up in diary
20442 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20443 (with-current-buffer buffer
20444 (unless (org-mode-p)
20445 (error "Agenda file %s is not in `org-mode'" file))
20446 (let ((case-fold-search nil))
20447 (save-excursion
20448 (save-restriction
20449 (if org-agenda-restrict
20450 (narrow-to-region org-agenda-restrict-begin
20451 org-agenda-restrict-end)
20452 (widen))
20453 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20454 (while (setq arg (pop args))
20455 (cond
20456 ((and (eq arg :todo)
20457 (equal date (calendar-current-date)))
20458 (setq rtn (org-agenda-get-todos))
20459 (setq results (append results rtn)))
20460 ((eq arg :timestamp)
20461 (setq rtn (org-agenda-get-blocks))
20462 (setq results (append results rtn))
20463 (setq rtn (org-agenda-get-timestamps))
20464 (setq results (append results rtn)))
20465 ((eq arg :sexp)
20466 (setq rtn (org-agenda-get-sexps))
20467 (setq results (append results rtn)))
20468 ((eq arg :scheduled)
20469 (setq rtn (org-agenda-get-scheduled))
20470 (setq results (append results rtn)))
20471 ((eq arg :closed)
20472 (setq rtn (org-agenda-get-closed))
20473 (setq results (append results rtn)))
20474 ((eq arg :deadline)
20475 (setq rtn (org-agenda-get-deadlines))
20476 (setq results (append results rtn))))))))
20477 results))))
20479 (defun org-entry-is-todo-p ()
20480 (member (org-get-todo-state) org-not-done-keywords))
20482 (defun org-entry-is-done-p ()
20483 (member (org-get-todo-state) org-done-keywords))
20485 (defun org-get-todo-state ()
20486 (save-excursion
20487 (org-back-to-heading t)
20488 (and (looking-at org-todo-line-regexp)
20489 (match-end 2)
20490 (match-string 2))))
20492 (defun org-at-date-range-p (&optional inactive-ok)
20493 "Is the cursor inside a date range?"
20494 (interactive)
20495 (save-excursion
20496 (catch 'exit
20497 (let ((pos (point)))
20498 (skip-chars-backward "^[<\r\n")
20499 (skip-chars-backward "<[")
20500 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20501 (>= (match-end 0) pos)
20502 (throw 'exit t))
20503 (skip-chars-backward "^<[\r\n")
20504 (skip-chars-backward "<[")
20505 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20506 (>= (match-end 0) pos)
20507 (throw 'exit t)))
20508 nil)))
20510 (defun org-agenda-get-todos ()
20511 "Return the TODO information for agenda display."
20512 (let* ((props (list 'face nil
20513 'done-face 'org-done
20514 'org-not-done-regexp org-not-done-regexp
20515 'org-todo-regexp org-todo-regexp
20516 'mouse-face 'highlight
20517 'keymap org-agenda-keymap
20518 'help-echo
20519 (format "mouse-2 or RET jump to org file %s"
20520 (abbreviate-file-name buffer-file-name))))
20521 ;; FIXME: get rid of the \n at some point but watch out
20522 (regexp (concat "^\\*+[ \t]+\\("
20523 (if org-select-this-todo-keyword
20524 (if (equal org-select-this-todo-keyword "*")
20525 org-todo-regexp
20526 (concat "\\<\\("
20527 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20528 "\\)\\>"))
20529 org-not-done-regexp)
20530 "[^\n\r]*\\)"))
20531 marker priority category tags
20532 ee txt beg end)
20533 (goto-char (point-min))
20534 (while (re-search-forward regexp nil t)
20535 (catch :skip
20536 (save-match-data
20537 (beginning-of-line)
20538 (setq beg (point) end (progn (outline-next-heading) (point)))
20539 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20540 (re-search-forward org-ts-regexp end t))
20541 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20542 (re-search-forward org-scheduled-time-regexp end t))
20543 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20544 (re-search-forward org-deadline-time-regexp end t)
20545 (org-deadline-close (match-string 1))))
20546 (goto-char (1+ beg))
20547 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20548 (throw :skip nil)))
20549 (goto-char beg)
20550 (org-agenda-skip)
20551 (goto-char (match-beginning 1))
20552 (setq marker (org-agenda-new-marker (match-beginning 0))
20553 category (org-get-category)
20554 tags (org-get-tags-at (point))
20555 txt (org-format-agenda-item "" (match-string 1) category tags)
20556 priority (1+ (org-get-priority txt)))
20557 (org-add-props txt props
20558 'org-marker marker 'org-hd-marker marker
20559 'priority priority 'org-category category
20560 'type "todo")
20561 (push txt ee)
20562 (if org-agenda-todo-list-sublevels
20563 (goto-char (match-end 1))
20564 (org-end-of-subtree 'invisible))))
20565 (nreverse ee)))
20567 (defconst org-agenda-no-heading-message
20568 "No heading for this item in buffer or region.")
20570 (defun org-agenda-get-timestamps ()
20571 "Return the date stamp information for agenda display."
20572 (let* ((props (list 'face nil
20573 'org-not-done-regexp org-not-done-regexp
20574 'org-todo-regexp org-todo-regexp
20575 'mouse-face 'highlight
20576 'keymap org-agenda-keymap
20577 'help-echo
20578 (format "mouse-2 or RET jump to org file %s"
20579 (abbreviate-file-name buffer-file-name))))
20580 (d1 (calendar-absolute-from-gregorian date))
20581 (remove-re
20582 (concat
20583 (regexp-quote
20584 (format-time-string
20585 "<%Y-%m-%d"
20586 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20587 ".*?>"))
20588 (regexp
20589 (concat
20590 (regexp-quote
20591 (substring
20592 (format-time-string
20593 (car org-time-stamp-formats)
20594 (apply 'encode-time ; DATE bound by calendar
20595 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20596 0 11))
20597 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20598 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20599 marker hdmarker deadlinep scheduledp donep tmp priority category
20600 ee txt timestr tags b0 b3 e3 head)
20601 (goto-char (point-min))
20602 (while (re-search-forward regexp nil t)
20603 (setq b0 (match-beginning 0)
20604 b3 (match-beginning 3) e3 (match-end 3))
20605 (catch :skip
20606 (and (org-at-date-range-p) (throw :skip nil))
20607 (org-agenda-skip)
20608 (if (and (match-end 1)
20609 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20610 (throw :skip nil))
20611 (if (and e3
20612 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20613 (throw :skip nil))
20614 (setq marker (org-agenda-new-marker b0)
20615 category (org-get-category b0)
20616 tmp (buffer-substring (max (point-min)
20617 (- b0 org-ds-keyword-length))
20619 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20620 deadlinep (string-match org-deadline-regexp tmp)
20621 scheduledp (string-match org-scheduled-regexp tmp)
20622 donep (org-entry-is-done-p))
20623 (if (or scheduledp deadlinep) (throw :skip t))
20624 (if (string-match ">" timestr)
20625 ;; substring should only run to end of time stamp
20626 (setq timestr (substring timestr 0 (match-end 0))))
20627 (save-excursion
20628 (if (re-search-backward "^\\*+ " nil t)
20629 (progn
20630 (goto-char (match-beginning 0))
20631 (setq hdmarker (org-agenda-new-marker)
20632 tags (org-get-tags-at))
20633 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20634 (setq head (match-string 1))
20635 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
20636 (setq txt (org-format-agenda-item
20637 nil head category tags timestr nil
20638 remove-re)))
20639 (setq txt org-agenda-no-heading-message))
20640 (setq priority (org-get-priority txt))
20641 (org-add-props txt props
20642 'org-marker marker 'org-hd-marker hdmarker)
20643 (org-add-props txt nil 'priority priority
20644 'org-category category 'date date
20645 'type "timestamp")
20646 (push txt ee))
20647 (outline-next-heading)))
20648 (nreverse ee)))
20650 (defun org-agenda-get-sexps ()
20651 "Return the sexp information for agenda display."
20652 (require 'diary-lib)
20653 (let* ((props (list 'face nil
20654 'mouse-face 'highlight
20655 'keymap org-agenda-keymap
20656 'help-echo
20657 (format "mouse-2 or RET jump to org file %s"
20658 (abbreviate-file-name buffer-file-name))))
20659 (regexp "^&?%%(")
20660 marker category ee txt tags entry result beg b sexp sexp-entry)
20661 (goto-char (point-min))
20662 (while (re-search-forward regexp nil t)
20663 (catch :skip
20664 (org-agenda-skip)
20665 (setq beg (match-beginning 0))
20666 (goto-char (1- (match-end 0)))
20667 (setq b (point))
20668 (forward-sexp 1)
20669 (setq sexp (buffer-substring b (point)))
20670 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20671 (org-trim (match-string 1))
20672 ""))
20673 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20674 (when result
20675 (setq marker (org-agenda-new-marker beg)
20676 category (org-get-category beg))
20678 (if (string-match "\\S-" result)
20679 (setq txt result)
20680 (setq txt "SEXP entry returned empty string"))
20682 (setq txt (org-format-agenda-item
20683 "" txt category tags 'time))
20684 (org-add-props txt props 'org-marker marker)
20685 (org-add-props txt nil
20686 'org-category category 'date date
20687 'type "sexp")
20688 (push txt ee))))
20689 (nreverse ee)))
20691 (defun org-agenda-get-closed ()
20692 "Return the logged TODO entries for agenda display."
20693 (let* ((props (list 'mouse-face 'highlight
20694 'org-not-done-regexp org-not-done-regexp
20695 'org-todo-regexp org-todo-regexp
20696 'keymap org-agenda-keymap
20697 'help-echo
20698 (format "mouse-2 or RET jump to org file %s"
20699 (abbreviate-file-name buffer-file-name))))
20700 (regexp (concat
20701 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20702 (regexp-quote
20703 (substring
20704 (format-time-string
20705 (car org-time-stamp-formats)
20706 (apply 'encode-time ; DATE bound by calendar
20707 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20708 1 11))))
20709 marker hdmarker priority category tags closedp
20710 ee txt timestr)
20711 (goto-char (point-min))
20712 (while (re-search-forward regexp nil t)
20713 (catch :skip
20714 (org-agenda-skip)
20715 (setq marker (org-agenda-new-marker (match-beginning 0))
20716 closedp (equal (match-string 1) org-closed-string)
20717 category (org-get-category (match-beginning 0))
20718 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20719 ;; donep (org-entry-is-done-p)
20721 (if (string-match "\\]" timestr)
20722 ;; substring should only run to end of time stamp
20723 (setq timestr (substring timestr 0 (match-end 0))))
20724 (save-excursion
20725 (if (re-search-backward "^\\*+ " nil t)
20726 (progn
20727 (goto-char (match-beginning 0))
20728 (setq hdmarker (org-agenda-new-marker)
20729 tags (org-get-tags-at))
20730 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20731 (setq txt (org-format-agenda-item
20732 (if closedp "Closed: " "Clocked: ")
20733 (match-string 1) category tags timestr)))
20734 (setq txt org-agenda-no-heading-message))
20735 (setq priority 100000)
20736 (org-add-props txt props
20737 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20738 'priority priority 'org-category category
20739 'type "closed" 'date date
20740 'undone-face 'org-warning 'done-face 'org-done)
20741 (push txt ee))
20742 (outline-next-heading)))
20743 (nreverse ee)))
20745 (defun org-agenda-get-deadlines ()
20746 "Return the deadline information for agenda display."
20747 (let* ((props (list 'mouse-face 'highlight
20748 'org-not-done-regexp org-not-done-regexp
20749 'org-todo-regexp org-todo-regexp
20750 'keymap org-agenda-keymap
20751 'help-echo
20752 (format "mouse-2 or RET jump to org file %s"
20753 (abbreviate-file-name buffer-file-name))))
20754 (regexp org-deadline-time-regexp)
20755 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20756 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20757 d2 diff dfrac wdays pos pos1 category tags
20758 ee txt head face s upcomingp donep timestr)
20759 (goto-char (point-min))
20760 (while (re-search-forward regexp nil t)
20761 (catch :skip
20762 (org-agenda-skip)
20763 (setq s (match-string 1)
20764 pos (1- (match-beginning 1))
20765 d2 (org-time-string-to-absolute (match-string 1) d1)
20766 diff (- d2 d1)
20767 wdays (org-get-wdays s)
20768 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20769 upcomingp (and todayp (> diff 0)))
20770 ;; When to show a deadline in the calendar:
20771 ;; If the expiration is within wdays warning time.
20772 ;; Past-due deadlines are only shown on the current date
20773 (if (or (and (<= diff wdays)
20774 (and todayp (not org-agenda-only-exact-dates)))
20775 (= diff 0))
20776 (save-excursion
20777 (setq category (org-get-category))
20778 (if (re-search-backward "^\\*+[ \t]+" nil t)
20779 (progn
20780 (goto-char (match-end 0))
20781 (setq pos1 (match-beginning 0))
20782 (setq tags (org-get-tags-at pos1))
20783 (setq head (buffer-substring-no-properties
20784 (point)
20785 (progn (skip-chars-forward "^\r\n")
20786 (point))))
20787 (setq donep (string-match org-looking-at-done-regexp head))
20788 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20789 (setq timestr
20790 (concat (substring s (match-beginning 1)) " "))
20791 (setq timestr 'time))
20792 (if (and donep
20793 (or org-agenda-skip-deadline-if-done
20794 (not (= diff 0))))
20795 (setq txt nil)
20796 (setq txt (org-format-agenda-item
20797 (if (= diff 0)
20798 (car org-agenda-deadline-leaders)
20799 (format (nth 1 org-agenda-deadline-leaders)
20800 diff))
20801 head category tags timestr))))
20802 (setq txt org-agenda-no-heading-message))
20803 (when txt
20804 (setq face (org-agenda-deadline-face dfrac))
20805 (org-add-props txt props
20806 'org-marker (org-agenda-new-marker pos)
20807 'org-hd-marker (org-agenda-new-marker pos1)
20808 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20809 (org-get-priority txt))
20810 'org-category category
20811 'type (if upcomingp "upcoming-deadline" "deadline")
20812 'date (if upcomingp date d2)
20813 'face (if donep 'org-done face)
20814 'undone-face face 'done-face 'org-done)
20815 (push txt ee))))))
20816 (nreverse ee)))
20818 (defun org-agenda-deadline-face (fraction)
20819 "Return the face to displaying a deadline item.
20820 FRACTION is what fraction of the head-warning time has passed."
20821 (let ((faces org-agenda-deadline-faces) f)
20822 (catch 'exit
20823 (while (setq f (pop faces))
20824 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20826 (defun org-agenda-get-scheduled ()
20827 "Return the scheduled information for agenda display."
20828 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20829 'org-todo-regexp org-todo-regexp
20830 'done-face 'org-done
20831 'mouse-face 'highlight
20832 'keymap org-agenda-keymap
20833 'help-echo
20834 (format "mouse-2 or RET jump to org file %s"
20835 (abbreviate-file-name buffer-file-name))))
20836 (regexp org-scheduled-time-regexp)
20837 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20838 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20839 d2 diff pos pos1 category tags
20840 ee txt head pastschedp donep face timestr s)
20841 (goto-char (point-min))
20842 (while (re-search-forward regexp nil t)
20843 (catch :skip
20844 (org-agenda-skip)
20845 (setq s (match-string 1)
20846 pos (1- (match-beginning 1))
20847 d2 (org-time-string-to-absolute (match-string 1) d1)
20848 diff (- d2 d1))
20849 (setq pastschedp (and todayp (< diff 0)))
20850 ;; When to show a scheduled item in the calendar:
20851 ;; If it is on or past the date.
20852 (if (or (and (< diff 0)
20853 (and todayp (not org-agenda-only-exact-dates)))
20854 (= diff 0))
20855 (save-excursion
20856 (setq category (org-get-category))
20857 (if (re-search-backward "^\\*+[ \t]+" nil t)
20858 (progn
20859 (goto-char (match-end 0))
20860 (setq pos1 (match-beginning 0))
20861 (setq tags (org-get-tags-at))
20862 (setq head (buffer-substring-no-properties
20863 (point)
20864 (progn (skip-chars-forward "^\r\n") (point))))
20865 (setq donep (string-match org-looking-at-done-regexp head))
20866 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20867 (setq timestr
20868 (concat (substring s (match-beginning 1)) " "))
20869 (setq timestr 'time))
20870 (if (and donep
20871 (or org-agenda-skip-scheduled-if-done
20872 (not (= diff 0))))
20873 (setq txt nil)
20874 (setq txt (org-format-agenda-item
20875 (if (= diff 0)
20876 (car org-agenda-scheduled-leaders)
20877 (format (nth 1 org-agenda-scheduled-leaders)
20878 (- 1 diff)))
20879 head category tags timestr))))
20880 (setq txt org-agenda-no-heading-message))
20881 (when txt
20882 (setq face (if pastschedp
20883 'org-scheduled-previously
20884 'org-scheduled-today))
20885 (org-add-props txt props
20886 'undone-face face
20887 'face (if donep 'org-done face)
20888 'org-marker (org-agenda-new-marker pos)
20889 'org-hd-marker (org-agenda-new-marker pos1)
20890 'type (if pastschedp "past-scheduled" "scheduled")
20891 'date (if pastschedp d2 date)
20892 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20893 'org-category category)
20894 (push txt ee))))))
20895 (nreverse ee)))
20897 (defun org-agenda-get-blocks ()
20898 "Return the date-range information for agenda display."
20899 (let* ((props (list 'face nil
20900 'org-not-done-regexp org-not-done-regexp
20901 'org-todo-regexp org-todo-regexp
20902 'mouse-face 'highlight
20903 'keymap org-agenda-keymap
20904 'help-echo
20905 (format "mouse-2 or RET jump to org file %s"
20906 (abbreviate-file-name buffer-file-name))))
20907 (regexp org-tr-regexp)
20908 (d0 (calendar-absolute-from-gregorian date))
20909 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
20910 donep head)
20911 (goto-char (point-min))
20912 (while (re-search-forward regexp nil t)
20913 (catch :skip
20914 (org-agenda-skip)
20915 (setq pos (point))
20916 (setq timestr (match-string 0)
20917 s1 (match-string 1)
20918 s2 (match-string 2)
20919 d1 (time-to-days (org-time-string-to-time s1))
20920 d2 (time-to-days (org-time-string-to-time s2)))
20921 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20922 ;; Only allow days between the limits, because the normal
20923 ;; date stamps will catch the limits.
20924 (save-excursion
20925 (setq marker (org-agenda-new-marker (point)))
20926 (setq category (org-get-category))
20927 (if (re-search-backward "^\\*+ " nil t)
20928 (progn
20929 (goto-char (match-beginning 0))
20930 (setq hdmarker (org-agenda-new-marker (point)))
20931 (setq tags (org-get-tags-at))
20932 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20933 (setq head (match-string 1))
20934 (and org-agenda-skip-timestamp-if-done
20935 (org-entry-is-done-p)
20936 (throw :skip t))
20937 (setq txt (org-format-agenda-item
20938 (format (if (= d1 d2) "" "(%d/%d): ")
20939 (1+ (- d0 d1)) (1+ (- d2 d1)))
20940 head category tags
20941 (if (= d0 d1) timestr))))
20942 (setq txt org-agenda-no-heading-message))
20943 (org-add-props txt props
20944 'org-marker marker 'org-hd-marker hdmarker
20945 'type "block" 'date date
20946 'priority (org-get-priority txt) 'org-category category)
20947 (push txt ee)))
20948 (goto-char pos)))
20949 ;; Sort the entries by expiration date.
20950 (nreverse ee)))
20952 ;;; Agenda presentation and sorting
20954 (defconst org-plain-time-of-day-regexp
20955 (concat
20956 "\\(\\<[012]?[0-9]"
20957 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20958 "\\(--?"
20959 "\\(\\<[012]?[0-9]"
20960 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20961 "\\)?")
20962 "Regular expression to match a plain time or time range.
20963 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20964 groups carry important information:
20965 0 the full match
20966 1 the first time, range or not
20967 8 the second time, if it is a range.")
20969 (defconst org-plain-time-extension-regexp
20970 (concat
20971 "\\(\\<[012]?[0-9]"
20972 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20973 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20974 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20975 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20976 groups carry important information:
20977 0 the full match
20978 7 hours of duration
20979 9 minutes of duration")
20981 (defconst org-stamp-time-of-day-regexp
20982 (concat
20983 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20984 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20985 "\\(--?"
20986 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20987 "Regular expression to match a timestamp time or time range.
20988 After a match, the following groups carry important information:
20989 0 the full match
20990 1 date plus weekday, for backreferencing to make sure both times on same day
20991 2 the first time, range or not
20992 4 the second time, if it is a range.")
20994 (defvar org-prefix-has-time nil
20995 "A flag, set by `org-compile-prefix-format'.
20996 The flag is set if the currently compiled format contains a `%t'.")
20997 (defvar org-prefix-has-tag nil
20998 "A flag, set by `org-compile-prefix-format'.
20999 The flag is set if the currently compiled format contains a `%T'.")
21001 (defun org-format-agenda-item (extra txt &optional category tags dotime
21002 noprefix remove-re)
21003 "Format TXT to be inserted into the agenda buffer.
21004 In particular, it adds the prefix and corresponding text properties. EXTRA
21005 must be a string and replaces the `%s' specifier in the prefix format.
21006 CATEGORY (string, symbol or nil) may be used to overrule the default
21007 category taken from local variable or file name. It will replace the `%c'
21008 specifier in the format. DOTIME, when non-nil, indicates that a
21009 time-of-day should be extracted from TXT for sorting of this entry, and for
21010 the `%t' specifier in the format. When DOTIME is a string, this string is
21011 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21012 only the correctly processes TXT should be returned - this is used by
21013 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21014 Any match of REMOVE-RE will be removed from TXT."
21015 (save-match-data
21016 ;; Diary entries sometimes have extra whitespace at the beginning
21017 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21018 (let* ((category (or category
21019 org-category
21020 (if buffer-file-name
21021 (file-name-sans-extension
21022 (file-name-nondirectory buffer-file-name))
21023 "")))
21024 (tag (if tags (nth (1- (length tags)) tags) ""))
21025 time ; time and tag are needed for the eval of the prefix format
21026 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21027 (time-of-day (and dotime (org-get-time-of-day ts)))
21028 stamp plain s0 s1 s2 rtn srp)
21029 (when (and dotime time-of-day org-prefix-has-time)
21030 ;; Extract starting and ending time and move them to prefix
21031 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21032 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21033 (setq s0 (match-string 0 ts)
21034 srp (and stamp (match-end 3))
21035 s1 (match-string (if plain 1 2) ts)
21036 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21038 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21039 ;; them, we might want to remove them there to avoid duplication.
21040 ;; The user can turn this off with a variable.
21041 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21042 (string-match (concat (regexp-quote s0) " *") txt)
21043 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21044 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21045 (= (match-beginning 0) 0)
21047 (setq txt (replace-match "" nil nil txt))))
21048 ;; Normalize the time(s) to 24 hour
21049 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21050 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21052 (when (and s1 (not s2) org-agenda-default-appointment-duration
21053 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21054 (let ((m (+ (string-to-number (match-string 2 s1))
21055 (* 60 (string-to-number (match-string 1 s1)))
21056 org-agenda-default-appointment-duration))
21058 (setq h (/ m 60) m (- m (* h 60)))
21059 (setq s2 (format "%02d:%02d" h m))))
21061 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21062 txt)
21063 ;; Tags are in the string
21064 (if (or (eq org-agenda-remove-tags t)
21065 (and org-agenda-remove-tags
21066 org-prefix-has-tag))
21067 (setq txt (replace-match "" t t txt))
21068 (setq txt (replace-match
21069 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21070 (match-string 2 txt))
21071 t t txt))))
21073 (when remove-re
21074 (while (string-match remove-re txt)
21075 (setq txt (replace-match "" t t txt))))
21077 ;; Create the final string
21078 (if noprefix
21079 (setq rtn txt)
21080 ;; Prepare the variables needed in the eval of the compiled format
21081 (setq time (cond (s2 (concat s1 "-" s2))
21082 (s1 (concat s1 "......"))
21083 (t ""))
21084 extra (or extra "")
21085 category (if (symbolp category) (symbol-name category) category))
21086 ;; Evaluate the compiled format
21087 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21089 ;; And finally add the text properties
21090 (org-add-props rtn nil
21091 'org-category (downcase category) 'tags tags
21092 'org-highest-priority org-highest-priority
21093 'org-lowest-priority org-lowest-priority
21094 'prefix-length (- (length rtn) (length txt))
21095 'time-of-day time-of-day
21096 'txt txt
21097 'time time
21098 'extra extra
21099 'dotime dotime))))
21101 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21102 (defvar org-agenda-sorting-strategy-selected nil)
21104 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21105 (catch 'exit
21106 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21107 ((and todayp (member 'today (car org-agenda-time-grid))))
21108 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21109 ((member 'weekly (car org-agenda-time-grid)))
21110 (t (throw 'exit list)))
21111 (let* ((have (delq nil (mapcar
21112 (lambda (x) (get-text-property 1 'time-of-day x))
21113 list)))
21114 (string (nth 1 org-agenda-time-grid))
21115 (gridtimes (nth 2 org-agenda-time-grid))
21116 (req (car org-agenda-time-grid))
21117 (remove (member 'remove-match req))
21118 new time)
21119 (if (and (member 'require-timed req) (not have))
21120 ;; don't show empty grid
21121 (throw 'exit list))
21122 (while (setq time (pop gridtimes))
21123 (unless (and remove (member time have))
21124 (setq time (int-to-string time))
21125 (push (org-format-agenda-item
21126 nil string "" nil
21127 (concat (substring time 0 -2) ":" (substring time -2)))
21128 new)
21129 (put-text-property
21130 1 (length (car new)) 'face 'org-time-grid (car new))))
21131 (if (member 'time-up org-agenda-sorting-strategy-selected)
21132 (append new list)
21133 (append list new)))))
21135 (defun org-compile-prefix-format (key)
21136 "Compile the prefix format into a Lisp form that can be evaluated.
21137 The resulting form is returned and stored in the variable
21138 `org-prefix-format-compiled'."
21139 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21140 (let ((s (cond
21141 ((stringp org-agenda-prefix-format)
21142 org-agenda-prefix-format)
21143 ((assq key org-agenda-prefix-format)
21144 (cdr (assq key org-agenda-prefix-format)))
21145 (t " %-12:c%?-12t% s")))
21146 (start 0)
21147 varform vars var e c f opt)
21148 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21149 s start)
21150 (setq var (cdr (assoc (match-string 4 s)
21151 '(("c" . category) ("t" . time) ("s" . extra)
21152 ("T" . tag))))
21153 c (or (match-string 3 s) "")
21154 opt (match-beginning 1)
21155 start (1+ (match-beginning 0)))
21156 (if (equal var 'time) (setq org-prefix-has-time t))
21157 (if (equal var 'tag) (setq org-prefix-has-tag t))
21158 (setq f (concat "%" (match-string 2 s) "s"))
21159 (if opt
21160 (setq varform
21161 `(if (equal "" ,var)
21163 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21164 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21165 (setq s (replace-match "%s" t nil s))
21166 (push varform vars))
21167 (setq vars (nreverse vars))
21168 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21170 (defun org-set-sorting-strategy (key)
21171 (if (symbolp (car org-agenda-sorting-strategy))
21172 ;; the old format
21173 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21174 (setq org-agenda-sorting-strategy-selected
21175 (or (cdr (assq key org-agenda-sorting-strategy))
21176 (cdr (assq 'agenda org-agenda-sorting-strategy))
21177 '(time-up category-keep priority-down)))))
21179 (defun org-get-time-of-day (s &optional string mod24)
21180 "Check string S for a time of day.
21181 If found, return it as a military time number between 0 and 2400.
21182 If not found, return nil.
21183 The optional STRING argument forces conversion into a 5 character wide string
21184 HH:MM."
21185 (save-match-data
21186 (when
21187 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21188 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21189 (let* ((h (string-to-number (match-string 1 s)))
21190 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21191 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21192 (am-p (equal ampm "am"))
21193 (h1 (cond ((not ampm) h)
21194 ((= h 12) (if am-p 0 12))
21195 (t (+ h (if am-p 0 12)))))
21196 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21197 (mod h1 24) h1))
21198 (t0 (+ (* 100 h2) m))
21199 (t1 (concat (if (>= h1 24) "+" " ")
21200 (if (< t0 100) "0" "")
21201 (if (< t0 10) "0" "")
21202 (int-to-string t0))))
21203 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21205 (defun org-finalize-agenda-entries (list &optional nosort)
21206 "Sort and concatenate the agenda items."
21207 (setq list (mapcar 'org-agenda-highlight-todo list))
21208 (if nosort
21209 list
21210 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21212 (defun org-agenda-highlight-todo (x)
21213 (let (re pl)
21214 (if (eq x 'line)
21215 (save-excursion
21216 (beginning-of-line 1)
21217 (setq re (get-text-property (point) 'org-todo-regexp))
21218 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21219 (and (looking-at (concat "[ \t]*\\.*" re))
21220 (add-text-properties (match-beginning 0) (match-end 0)
21221 (list 'face (org-get-todo-face 0)))))
21222 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21223 pl (get-text-property 0 'prefix-length x))
21224 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21225 (add-text-properties
21226 (or (match-end 1) (match-end 0)) (match-end 0)
21227 (list 'face (org-get-todo-face (match-string 2 x)))
21229 x)))
21231 (defsubst org-cmp-priority (a b)
21232 "Compare the priorities of string A and B."
21233 (let ((pa (or (get-text-property 1 'priority a) 0))
21234 (pb (or (get-text-property 1 'priority b) 0)))
21235 (cond ((> pa pb) +1)
21236 ((< pa pb) -1)
21237 (t nil))))
21239 (defsubst org-cmp-category (a b)
21240 "Compare the string values of categories of strings A and B."
21241 (let ((ca (or (get-text-property 1 'org-category a) ""))
21242 (cb (or (get-text-property 1 'org-category b) "")))
21243 (cond ((string-lessp ca cb) -1)
21244 ((string-lessp cb ca) +1)
21245 (t nil))))
21247 (defsubst org-cmp-tag (a b)
21248 "Compare the string values of categories of strings A and B."
21249 (let ((ta (car (last (get-text-property 1 'tags a))))
21250 (tb (car (last (get-text-property 1 'tags b)))))
21251 (cond ((not ta) +1)
21252 ((not tb) -1)
21253 ((string-lessp ta tb) -1)
21254 ((string-lessp tb ta) +1)
21255 (t nil))))
21257 (defsubst org-cmp-time (a b)
21258 "Compare the time-of-day values of strings A and B."
21259 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21260 (ta (or (get-text-property 1 'time-of-day a) def))
21261 (tb (or (get-text-property 1 'time-of-day b) def)))
21262 (cond ((< ta tb) -1)
21263 ((< tb ta) +1)
21264 (t nil))))
21266 (defun org-entries-lessp (a b)
21267 "Predicate for sorting agenda entries."
21268 ;; The following variables will be used when the form is evaluated.
21269 ;; So even though the compiler complains, keep them.
21270 (let* ((time-up (org-cmp-time a b))
21271 (time-down (if time-up (- time-up) nil))
21272 (priority-up (org-cmp-priority a b))
21273 (priority-down (if priority-up (- priority-up) nil))
21274 (category-up (org-cmp-category a b))
21275 (category-down (if category-up (- category-up) nil))
21276 (category-keep (if category-up +1 nil))
21277 (tag-up (org-cmp-tag a b))
21278 (tag-down (if tag-up (- tag-up) nil)))
21279 (cdr (assoc
21280 (eval (cons 'or org-agenda-sorting-strategy-selected))
21281 '((-1 . t) (1 . nil) (nil . nil))))))
21283 ;;; Agenda restriction lock
21285 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21286 "Overlay to mark the headline to which arenda commands are restricted.")
21287 (org-overlay-put org-agenda-restriction-lock-overlay
21288 'face 'org-agenda-restriction-lock)
21289 (org-overlay-put org-agenda-restriction-lock-overlay
21290 'help-echo "Agendas are currently limited to this subtree.")
21291 (org-detach-overlay org-agenda-restriction-lock-overlay)
21292 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21293 "Overlay marking the agenda restriction line in speedbar.")
21294 (org-overlay-put org-speedbar-restriction-lock-overlay
21295 'face 'org-agenda-restriction-lock)
21296 (org-overlay-put org-speedbar-restriction-lock-overlay
21297 'help-echo "Agendas are currently limited to this item.")
21298 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21300 (defun org-agenda-set-restriction-lock (&optional type)
21301 "Set restriction lock for agenda, to current subtree or file.
21302 Restriction will be the file if TYPE is `file', or if type is the
21303 universal prefix '(4), or if the cursor is before the first headline
21304 in the file. Otherwise, restriction will be to the current subtree."
21305 (interactive "P")
21306 (and (equal type '(4)) (setq type 'file))
21307 (setq type (cond
21308 (type type)
21309 ((org-at-heading-p) 'subtree)
21310 ((condition-case nil (org-back-to-heading t) (error nil))
21311 'subtree)
21312 (t 'file)))
21313 (if (eq type 'subtree)
21314 (progn
21315 (setq org-agenda-restrict t)
21316 (setq org-agenda-overriding-restriction 'subtree)
21317 (put 'org-agenda-files 'org-restrict
21318 (list (buffer-file-name (buffer-base-buffer))))
21319 (org-back-to-heading t)
21320 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21321 (move-marker org-agenda-restrict-begin (point))
21322 (move-marker org-agenda-restrict-end
21323 (save-excursion (org-end-of-subtree t)))
21324 (message "Locking agenda restriction to subtree"))
21325 (put 'org-agenda-files 'org-restrict
21326 (list (buffer-file-name (buffer-base-buffer))))
21327 (setq org-agenda-restrict nil)
21328 (setq org-agenda-overriding-restriction 'file)
21329 (move-marker org-agenda-restrict-begin nil)
21330 (move-marker org-agenda-restrict-end nil)
21331 (message "Locking agenda restriction to file"))
21332 (setq current-prefix-arg nil)
21333 (org-agenda-maybe-redo))
21335 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21336 "Remove the agenda restriction lock."
21337 (interactive "P")
21338 (org-detach-overlay org-agenda-restriction-lock-overlay)
21339 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21340 (setq org-agenda-overriding-restriction nil)
21341 (setq org-agenda-restrict nil)
21342 (put 'org-agenda-files 'org-restrict nil)
21343 (move-marker org-agenda-restrict-begin nil)
21344 (move-marker org-agenda-restrict-end nil)
21345 (setq current-prefix-arg nil)
21346 (message "Agenda restriction lock removed")
21347 (or noupdate (org-agenda-maybe-redo)))
21349 (defun org-agenda-maybe-redo ()
21350 "If there is any window showing the agenda view, update it."
21351 (let ((w (get-buffer-window org-agenda-buffer-name t))
21352 (w0 (selected-window)))
21353 (when w
21354 (select-window w)
21355 (org-agenda-redo)
21356 (select-window w0)
21357 (if org-agenda-overriding-restriction
21358 (message "Agenda view shifted to new %s restriction"
21359 org-agenda-overriding-restriction)
21360 (message "Agenda restriction lock removed")))))
21362 ;;; Agenda commands
21364 (defun org-agenda-check-type (error &rest types)
21365 "Check if agenda buffer is of allowed type.
21366 If ERROR is non-nil, throw an error, otherwise just return nil."
21367 (if (memq org-agenda-type types)
21369 (if error
21370 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21371 nil)))
21373 (defun org-agenda-quit ()
21374 "Exit agenda by removing the window or the buffer."
21375 (interactive)
21376 (let ((buf (current-buffer)))
21377 (if (not (one-window-p)) (delete-window))
21378 (kill-buffer buf)
21379 (org-agenda-maybe-reset-markers 'force)
21380 (org-columns-remove-overlays))
21381 ;; Maybe restore the pre-agenda window configuration.
21382 (and org-agenda-restore-windows-after-quit
21383 (not (eq org-agenda-window-setup 'other-frame))
21384 org-pre-agenda-window-conf
21385 (set-window-configuration org-pre-agenda-window-conf)))
21387 (defun org-agenda-exit ()
21388 "Exit agenda by removing the window or the buffer.
21389 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21390 Org-mode buffers visited directly by the user will not be touched."
21391 (interactive)
21392 (org-release-buffers org-agenda-new-buffers)
21393 (setq org-agenda-new-buffers nil)
21394 (org-agenda-quit))
21396 (defun org-agenda-execute (arg)
21397 "Execute another agenda command, keeping same window.\\<global-map>
21398 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21399 (interactive "P")
21400 (let ((org-agenda-window-setup 'current-window))
21401 (org-agenda arg)))
21403 (defun org-save-all-org-buffers ()
21404 "Save all Org-mode buffers without user confirmation."
21405 (interactive)
21406 (message "Saving all Org-mode buffers...")
21407 (save-some-buffers t 'org-mode-p)
21408 (message "Saving all Org-mode buffers... done"))
21410 (defun org-agenda-redo ()
21411 "Rebuild Agenda.
21412 When this is the global TODO list, a prefix argument will be interpreted."
21413 (interactive)
21414 (let* ((org-agenda-keep-modes t)
21415 (line (org-current-line))
21416 (window-line (- line (org-current-line (window-start))))
21417 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21418 (message "Rebuilding agenda buffer...")
21419 (org-let lprops '(eval org-agenda-redo-command))
21420 (setq org-agenda-undo-list nil
21421 org-agenda-pending-undo-list nil)
21422 (message "Rebuilding agenda buffer...done")
21423 (goto-line line)
21424 (recenter window-line)))
21426 (defun org-agenda-goto-date (date)
21427 "Jump to DATE in agenda."
21428 (interactive (list (org-read-date)))
21429 (org-agenda-list nil date))
21431 (defun org-agenda-goto-today ()
21432 "Go to today."
21433 (interactive)
21434 (org-agenda-check-type t 'timeline 'agenda)
21435 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21436 (cond
21437 (tdpos (goto-char tdpos))
21438 ((eq org-agenda-type 'agenda)
21439 (let* ((sd (time-to-days
21440 (time-subtract (current-time)
21441 (list 0 (* 3600 org-extend-today-until) 0))))
21442 (comp (org-agenda-compute-time-span sd org-agenda-span))
21443 (org-agenda-overriding-arguments org-agenda-last-arguments))
21444 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21445 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21446 (org-agenda-redo)
21447 (org-agenda-find-same-or-today-or-agenda)))
21448 (t (error "Cannot find today")))))
21450 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21451 (goto-char
21452 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21453 (text-property-any (point-min) (point-max) 'org-today t)
21454 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21455 (point-min))))
21457 (defun org-agenda-later (arg)
21458 "Go forward in time by thee current span.
21459 With prefix ARG, go forward that many times the current span."
21460 (interactive "p")
21461 (org-agenda-check-type t 'agenda)
21462 (let* ((span org-agenda-span)
21463 (sd org-starting-day)
21464 (greg (calendar-gregorian-from-absolute sd))
21465 (cnt (get-text-property (point) 'org-day-cnt))
21466 greg2 nd)
21467 (cond
21468 ((eq span 'day)
21469 (setq sd (+ arg sd) nd 1))
21470 ((eq span 'week)
21471 (setq sd (+ (* 7 arg) sd) nd 7))
21472 ((eq span 'month)
21473 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21474 sd (calendar-absolute-from-gregorian greg2))
21475 (setcar greg2 (1+ (car greg2)))
21476 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21477 ((eq span 'year)
21478 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21479 sd (calendar-absolute-from-gregorian greg2))
21480 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21481 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21482 (let ((org-agenda-overriding-arguments
21483 (list (car org-agenda-last-arguments) sd nd t)))
21484 (org-agenda-redo)
21485 (org-agenda-find-same-or-today-or-agenda cnt))))
21487 (defun org-agenda-earlier (arg)
21488 "Go backward in time by the current span.
21489 With prefix ARG, go backward that many times the current span."
21490 (interactive "p")
21491 (org-agenda-later (- arg)))
21493 (defun org-agenda-day-view ()
21494 "Switch to daily view for agenda."
21495 (interactive)
21496 (setq org-agenda-ndays 1)
21497 (org-agenda-change-time-span 'day))
21498 (defun org-agenda-week-view ()
21499 "Switch to daily view for agenda."
21500 (interactive)
21501 (setq org-agenda-ndays 7)
21502 (org-agenda-change-time-span 'week))
21503 (defun org-agenda-month-view ()
21504 "Switch to daily view for agenda."
21505 (interactive)
21506 (org-agenda-change-time-span 'month))
21507 (defun org-agenda-year-view ()
21508 "Switch to daily view for agenda."
21509 (interactive)
21510 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21511 (org-agenda-change-time-span 'year)
21512 (error "Abort")))
21514 (defun org-agenda-change-time-span (span)
21515 "Change the agenda view to SPAN.
21516 SPAN may be `day', `week', `month', `year'."
21517 (org-agenda-check-type t 'agenda)
21518 (if (equal org-agenda-span span)
21519 (error "Viewing span is already \"%s\"" span))
21520 (let* ((sd (or (get-text-property (point) 'day)
21521 org-starting-day))
21522 (computed (org-agenda-compute-time-span sd span))
21523 (org-agenda-overriding-arguments
21524 (list (car org-agenda-last-arguments)
21525 (car computed) (cdr computed) t)))
21526 (org-agenda-redo)
21527 (org-agenda-find-same-or-today-or-agenda))
21528 (org-agenda-set-mode-name)
21529 (message "Switched to %s view" span))
21531 (defun org-agenda-compute-time-span (sd span)
21532 "Compute starting date and number of days for agenda.
21533 SPAN may be `day', `week', `month', `year'. The return value
21534 is a cons cell with the starting date and the number of days,
21535 so that the date SD will be in that range."
21536 (let* ((greg (calendar-gregorian-from-absolute sd))
21538 (cond
21539 ((eq span 'day)
21540 (setq nd 1))
21541 ((eq span 'week)
21542 (let* ((nt (calendar-day-of-week
21543 (calendar-gregorian-from-absolute sd)))
21544 (d (if org-agenda-start-on-weekday
21545 (- nt org-agenda-start-on-weekday)
21546 0)))
21547 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21548 (setq nd 7)))
21549 ((eq span 'month)
21550 (setq sd (calendar-absolute-from-gregorian
21551 (list (car greg) 1 (nth 2 greg)))
21552 nd (- (calendar-absolute-from-gregorian
21553 (list (1+ (car greg)) 1 (nth 2 greg)))
21554 sd)))
21555 ((eq span 'year)
21556 (setq sd (calendar-absolute-from-gregorian
21557 (list 1 1 (nth 2 greg)))
21558 nd (- (calendar-absolute-from-gregorian
21559 (list 1 1 (1+ (nth 2 greg))))
21560 sd))))
21561 (cons sd nd)))
21563 ;; FIXME: does not work if user makes date format that starts with a blank
21564 (defun org-agenda-next-date-line (&optional arg)
21565 "Jump to the next line indicating a date in agenda buffer."
21566 (interactive "p")
21567 (org-agenda-check-type t 'agenda 'timeline)
21568 (beginning-of-line 1)
21569 (if (looking-at "^\\S-") (forward-char 1))
21570 (if (not (re-search-forward "^\\S-" nil t arg))
21571 (progn
21572 (backward-char 1)
21573 (error "No next date after this line in this buffer")))
21574 (goto-char (match-beginning 0)))
21576 (defun org-agenda-previous-date-line (&optional arg)
21577 "Jump to the previous line indicating a date in agenda buffer."
21578 (interactive "p")
21579 (org-agenda-check-type t 'agenda 'timeline)
21580 (beginning-of-line 1)
21581 (if (not (re-search-backward "^\\S-" nil t arg))
21582 (error "No previous date before this line in this buffer")))
21584 ;; Initialize the highlight
21585 (defvar org-hl (org-make-overlay 1 1))
21586 (org-overlay-put org-hl 'face 'highlight)
21588 (defun org-highlight (begin end &optional buffer)
21589 "Highlight a region with overlay."
21590 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
21591 org-hl begin end (or buffer (current-buffer))))
21593 (defun org-unhighlight ()
21594 "Detach overlay INDEX."
21595 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
21597 ;; FIXME this is currently not used.
21598 (defun org-highlight-until-next-command (beg end &optional buffer)
21599 (org-highlight beg end buffer)
21600 (add-hook 'pre-command-hook 'org-unhighlight-once))
21601 (defun org-unhighlight-once ()
21602 (remove-hook 'pre-command-hook 'org-unhighlight-once)
21603 (org-unhighlight))
21605 (defun org-agenda-follow-mode ()
21606 "Toggle follow mode in an agenda buffer."
21607 (interactive)
21608 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
21609 (org-agenda-set-mode-name)
21610 (message "Follow mode is %s"
21611 (if org-agenda-follow-mode "on" "off")))
21613 (defun org-agenda-log-mode ()
21614 "Toggle log mode in an agenda buffer."
21615 (interactive)
21616 (org-agenda-check-type t 'agenda 'timeline)
21617 (setq org-agenda-show-log (not org-agenda-show-log))
21618 (org-agenda-set-mode-name)
21619 (org-agenda-redo)
21620 (message "Log mode is %s"
21621 (if org-agenda-show-log "on" "off")))
21623 (defun org-agenda-toggle-diary ()
21624 "Toggle diary inclusion in an agenda buffer."
21625 (interactive)
21626 (org-agenda-check-type t 'agenda)
21627 (setq org-agenda-include-diary (not org-agenda-include-diary))
21628 (org-agenda-redo)
21629 (org-agenda-set-mode-name)
21630 (message "Diary inclusion turned %s"
21631 (if org-agenda-include-diary "on" "off")))
21633 (defun org-agenda-toggle-time-grid ()
21634 "Toggle time grid in an agenda buffer."
21635 (interactive)
21636 (org-agenda-check-type t 'agenda)
21637 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
21638 (org-agenda-redo)
21639 (org-agenda-set-mode-name)
21640 (message "Time-grid turned %s"
21641 (if org-agenda-use-time-grid "on" "off")))
21643 (defun org-agenda-set-mode-name ()
21644 "Set the mode name to indicate all the small mode settings."
21645 (setq mode-name
21646 (concat "Org-Agenda"
21647 (if (equal org-agenda-ndays 1) " Day" "")
21648 (if (equal org-agenda-ndays 7) " Week" "")
21649 (if org-agenda-follow-mode " Follow" "")
21650 (if org-agenda-include-diary " Diary" "")
21651 (if org-agenda-use-time-grid " Grid" "")
21652 (if org-agenda-show-log " Log" "")))
21653 (force-mode-line-update))
21655 (defun org-agenda-post-command-hook ()
21656 (and (eolp) (not (bolp)) (backward-char 1))
21657 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
21658 (if (and org-agenda-follow-mode
21659 (get-text-property (point) 'org-marker))
21660 (org-agenda-show)))
21662 (defun org-agenda-show-priority ()
21663 "Show the priority of the current item.
21664 This priority is composed of the main priority given with the [#A] cookies,
21665 and by additional input from the age of a schedules or deadline entry."
21666 (interactive)
21667 (let* ((pri (get-text-property (point-at-bol) 'priority)))
21668 (message "Priority is %d" (if pri pri -1000))))
21670 (defun org-agenda-show-tags ()
21671 "Show the tags applicable to the current item."
21672 (interactive)
21673 (let* ((tags (get-text-property (point-at-bol) 'tags)))
21674 (if tags
21675 (message "Tags are :%s:"
21676 (org-no-properties (mapconcat 'identity tags ":")))
21677 (message "No tags associated with this line"))))
21679 (defun org-agenda-goto (&optional highlight)
21680 "Go to the Org-mode file which contains the item at point."
21681 (interactive)
21682 (let* ((marker (or (get-text-property (point) 'org-marker)
21683 (org-agenda-error)))
21684 (buffer (marker-buffer marker))
21685 (pos (marker-position marker)))
21686 (switch-to-buffer-other-window buffer)
21687 (widen)
21688 (goto-char pos)
21689 (when (org-mode-p)
21690 (org-show-context 'agenda)
21691 (save-excursion
21692 (and (outline-next-heading)
21693 (org-flag-heading nil)))) ; show the next heading
21694 (run-hooks 'org-agenda-after-show-hook)
21695 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
21697 (defvar org-agenda-after-show-hook nil
21698 "Normal hook run after an item has been shown from the agenda.
21699 Point is in the buffer where the item originated.")
21701 (defun org-agenda-kill ()
21702 "Kill the entry or subtree belonging to the current agenda entry."
21703 (interactive)
21704 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21705 (let* ((marker (or (get-text-property (point) 'org-marker)
21706 (org-agenda-error)))
21707 (buffer (marker-buffer marker))
21708 (pos (marker-position marker))
21709 (type (get-text-property (point) 'type))
21710 dbeg dend (n 0) conf)
21711 (org-with-remote-undo buffer
21712 (with-current-buffer buffer
21713 (save-excursion
21714 (goto-char pos)
21715 (if (and (org-mode-p) (not (member type '("sexp"))))
21716 (setq dbeg (progn (org-back-to-heading t) (point))
21717 dend (org-end-of-subtree t t))
21718 (setq dbeg (point-at-bol)
21719 dend (min (point-max) (1+ (point-at-eol)))))
21720 (goto-char dbeg)
21721 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
21722 (setq conf (or (eq t org-agenda-confirm-kill)
21723 (and (numberp org-agenda-confirm-kill)
21724 (> n org-agenda-confirm-kill))))
21725 (and conf
21726 (not (y-or-n-p
21727 (format "Delete entry with %d lines in buffer \"%s\"? "
21728 n (buffer-name buffer))))
21729 (error "Abort"))
21730 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
21731 (with-current-buffer buffer (delete-region dbeg dend))
21732 (message "Agenda item and source killed"))))
21734 (defun org-agenda-archive ()
21735 "Kill the entry or subtree belonging to the current agenda entry."
21736 (interactive)
21737 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21738 (let* ((marker (or (get-text-property (point) 'org-marker)
21739 (org-agenda-error)))
21740 (buffer (marker-buffer marker))
21741 (pos (marker-position marker)))
21742 (org-with-remote-undo buffer
21743 (with-current-buffer buffer
21744 (if (org-mode-p)
21745 (save-excursion
21746 (goto-char pos)
21747 (org-remove-subtree-entries-from-agenda)
21748 (org-back-to-heading t)
21749 (org-archive-subtree))
21750 (error "Archiving works only in Org-mode files"))))))
21752 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
21753 "Remove all lines in the agenda that correspond to a given subtree.
21754 The subtree is the one in buffer BUF, starting at BEG and ending at END.
21755 If this information is not given, the function uses the tree at point."
21756 (let ((buf (or buf (current-buffer))) m p)
21757 (save-excursion
21758 (unless (and beg end)
21759 (org-back-to-heading t)
21760 (setq beg (point))
21761 (org-end-of-subtree t)
21762 (setq end (point)))
21763 (set-buffer (get-buffer org-agenda-buffer-name))
21764 (save-excursion
21765 (goto-char (point-max))
21766 (beginning-of-line 1)
21767 (while (not (bobp))
21768 (when (and (setq m (get-text-property (point) 'org-marker))
21769 (equal buf (marker-buffer m))
21770 (setq p (marker-position m))
21771 (>= p beg)
21772 (<= p end))
21773 (let ((inhibit-read-only t))
21774 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21775 (beginning-of-line 0))))))
21777 (defun org-agenda-open-link ()
21778 "Follow the link in the current line, if any."
21779 (interactive)
21780 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21781 (save-excursion
21782 (save-restriction
21783 (narrow-to-region (point-at-bol) (point-at-eol))
21784 (org-open-at-point))))
21786 (defun org-agenda-copy-local-variable (var)
21787 "Get a variable from a referenced buffer and install it here."
21788 (let ((m (get-text-property (point) 'org-marker)))
21789 (when (and m (buffer-live-p (marker-buffer m)))
21790 (org-set-local var (with-current-buffer (marker-buffer m)
21791 (symbol-value var))))))
21793 (defun org-agenda-switch-to (&optional delete-other-windows)
21794 "Go to the Org-mode file which contains the item at point."
21795 (interactive)
21796 (let* ((marker (or (get-text-property (point) 'org-marker)
21797 (org-agenda-error)))
21798 (buffer (marker-buffer marker))
21799 (pos (marker-position marker)))
21800 (switch-to-buffer buffer)
21801 (and delete-other-windows (delete-other-windows))
21802 (widen)
21803 (goto-char pos)
21804 (when (org-mode-p)
21805 (org-show-context 'agenda)
21806 (save-excursion
21807 (and (outline-next-heading)
21808 (org-flag-heading nil)))))) ; show the next heading
21810 (defun org-agenda-goto-mouse (ev)
21811 "Go to the Org-mode file which contains the item at the mouse click."
21812 (interactive "e")
21813 (mouse-set-point ev)
21814 (org-agenda-goto))
21816 (defun org-agenda-show ()
21817 "Display the Org-mode file which contains the item at point."
21818 (interactive)
21819 (let ((win (selected-window)))
21820 (org-agenda-goto t)
21821 (select-window win)))
21823 (defun org-agenda-recenter (arg)
21824 "Display the Org-mode file which contains the item at point and recenter."
21825 (interactive "P")
21826 (let ((win (selected-window)))
21827 (org-agenda-goto t)
21828 (recenter arg)
21829 (select-window win)))
21831 (defun org-agenda-show-mouse (ev)
21832 "Display the Org-mode file which contains the item at the mouse click."
21833 (interactive "e")
21834 (mouse-set-point ev)
21835 (org-agenda-show))
21837 (defun org-agenda-check-no-diary ()
21838 "Check if the entry is a diary link and abort if yes."
21839 (if (get-text-property (point) 'org-agenda-diary-link)
21840 (org-agenda-error)))
21842 (defun org-agenda-error ()
21843 (error "Command not allowed in this line"))
21845 (defun org-agenda-tree-to-indirect-buffer ()
21846 "Show the subtree corresponding to the current entry in an indirect buffer.
21847 This calls the command `org-tree-to-indirect-buffer' from the original
21848 Org-mode buffer.
21849 With numerical prefix arg ARG, go up to this level and then take that tree.
21850 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21851 dedicated frame)."
21852 (interactive)
21853 (org-agenda-check-no-diary)
21854 (let* ((marker (or (get-text-property (point) 'org-marker)
21855 (org-agenda-error)))
21856 (buffer (marker-buffer marker))
21857 (pos (marker-position marker)))
21858 (with-current-buffer buffer
21859 (save-excursion
21860 (goto-char pos)
21861 (call-interactively 'org-tree-to-indirect-buffer)))))
21863 (defvar org-last-heading-marker (make-marker)
21864 "Marker pointing to the headline that last changed its TODO state
21865 by a remote command from the agenda.")
21867 (defun org-agenda-todo-nextset ()
21868 "Switch TODO entry to next sequence."
21869 (interactive)
21870 (org-agenda-todo 'nextset))
21872 (defun org-agenda-todo-previousset ()
21873 "Switch TODO entry to previous sequence."
21874 (interactive)
21875 (org-agenda-todo 'previousset))
21877 (defun org-agenda-todo (&optional arg)
21878 "Cycle TODO state of line at point, also in Org-mode file.
21879 This changes the line at point, all other lines in the agenda referring to
21880 the same tree node, and the headline of the tree node in the Org-mode file."
21881 (interactive "P")
21882 (org-agenda-check-no-diary)
21883 (let* ((col (current-column))
21884 (marker (or (get-text-property (point) 'org-marker)
21885 (org-agenda-error)))
21886 (buffer (marker-buffer marker))
21887 (pos (marker-position marker))
21888 (hdmarker (get-text-property (point) 'org-hd-marker))
21889 (inhibit-read-only t)
21890 newhead)
21891 (org-with-remote-undo buffer
21892 (with-current-buffer buffer
21893 (widen)
21894 (goto-char pos)
21895 (org-show-context 'agenda)
21896 (save-excursion
21897 (and (outline-next-heading)
21898 (org-flag-heading nil))) ; show the next heading
21899 (org-todo arg)
21900 (and (bolp) (forward-char 1))
21901 (setq newhead (org-get-heading))
21902 (save-excursion
21903 (org-back-to-heading)
21904 (move-marker org-last-heading-marker (point))))
21905 (beginning-of-line 1)
21906 (save-excursion
21907 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21908 (move-to-column col))))
21910 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21911 "Change all lines in the agenda buffer which match HDMARKER.
21912 The new content of the line will be NEWHEAD (as modified by
21913 `org-format-agenda-item'). HDMARKER is checked with
21914 `equal' against all `org-hd-marker' text properties in the file.
21915 If FIXFACE is non-nil, the face of each item is modified acording to
21916 the new TODO state."
21917 (let* ((inhibit-read-only t)
21918 props m pl undone-face done-face finish new dotime cat tags)
21919 (save-excursion
21920 (goto-char (point-max))
21921 (beginning-of-line 1)
21922 (while (not finish)
21923 (setq finish (bobp))
21924 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21925 (equal m hdmarker))
21926 (setq props (text-properties-at (point))
21927 dotime (get-text-property (point) 'dotime)
21928 cat (get-text-property (point) 'org-category)
21929 tags (get-text-property (point) 'tags)
21930 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21931 pl (get-text-property (point) 'prefix-length)
21932 undone-face (get-text-property (point) 'undone-face)
21933 done-face (get-text-property (point) 'done-face))
21934 (move-to-column pl)
21935 (cond
21936 ((equal new "")
21937 (beginning-of-line 1)
21938 (and (looking-at ".*\n?") (replace-match "")))
21939 ((looking-at ".*")
21940 (replace-match new t t)
21941 (beginning-of-line 1)
21942 (add-text-properties (point-at-bol) (point-at-eol) props)
21943 (when fixface
21944 (add-text-properties
21945 (point-at-bol) (point-at-eol)
21946 (list 'face
21947 (if org-last-todo-state-is-todo
21948 undone-face done-face))))
21949 (org-agenda-highlight-todo 'line)
21950 (beginning-of-line 1))
21951 (t (error "Line update did not work"))))
21952 (beginning-of-line 0)))
21953 (org-finalize-agenda)))
21955 (defun org-agenda-align-tags (&optional line)
21956 "Align all tags in agenda items to `org-agenda-tags-column'."
21957 (let ((inhibit-read-only t) l c)
21958 (save-excursion
21959 (goto-char (if line (point-at-bol) (point-min)))
21960 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21961 (if line (point-at-eol) nil) t)
21962 (add-text-properties
21963 (match-beginning 2) (match-end 2)
21964 (list 'face (list 'org-tag (get-text-property
21965 (match-beginning 2) 'face))))
21966 (setq l (- (match-end 2) (match-beginning 2))
21967 c (if (< org-agenda-tags-column 0)
21968 (- (abs org-agenda-tags-column) l)
21969 org-agenda-tags-column))
21970 (delete-region (match-beginning 1) (match-end 1))
21971 (goto-char (match-beginning 1))
21972 (insert (org-add-props
21973 (make-string (max 1 (- c (current-column))) ?\ )
21974 (text-properties-at (point))))))))
21976 (defun org-agenda-priority-up ()
21977 "Increase the priority of line at point, also in Org-mode file."
21978 (interactive)
21979 (org-agenda-priority 'up))
21981 (defun org-agenda-priority-down ()
21982 "Decrease the priority of line at point, also in Org-mode file."
21983 (interactive)
21984 (org-agenda-priority 'down))
21986 (defun org-agenda-priority (&optional force-direction)
21987 "Set the priority of line at point, also in Org-mode file.
21988 This changes the line at point, all other lines in the agenda referring to
21989 the same tree node, and the headline of the tree node in the Org-mode file."
21990 (interactive)
21991 (org-agenda-check-no-diary)
21992 (let* ((marker (or (get-text-property (point) 'org-marker)
21993 (org-agenda-error)))
21994 (hdmarker (get-text-property (point) 'org-hd-marker))
21995 (buffer (marker-buffer hdmarker))
21996 (pos (marker-position hdmarker))
21997 (inhibit-read-only t)
21998 newhead)
21999 (org-with-remote-undo buffer
22000 (with-current-buffer buffer
22001 (widen)
22002 (goto-char pos)
22003 (org-show-context 'agenda)
22004 (save-excursion
22005 (and (outline-next-heading)
22006 (org-flag-heading nil))) ; show the next heading
22007 (funcall 'org-priority force-direction)
22008 (end-of-line 1)
22009 (setq newhead (org-get-heading)))
22010 (org-agenda-change-all-lines newhead hdmarker)
22011 (beginning-of-line 1))))
22013 (defun org-get-tags-at (&optional pos)
22014 "Get a list of all headline tags applicable at POS.
22015 POS defaults to point. If tags are inherited, the list contains
22016 the targets in the same sequence as the headlines appear, i.e.
22017 the tags of the current headline come last."
22018 (interactive)
22019 (let (tags lastpos)
22020 (save-excursion
22021 (save-restriction
22022 (widen)
22023 (goto-char (or pos (point)))
22024 (save-match-data
22025 (org-back-to-heading t)
22026 (condition-case nil
22027 (while (not (equal lastpos (point)))
22028 (setq lastpos (point))
22029 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22030 (setq tags (append (org-split-string
22031 (org-match-string-no-properties 1) ":")
22032 tags)))
22033 (or org-use-tag-inheritance (error ""))
22034 (org-up-heading-all 1))
22035 (error nil))))
22036 tags)))
22038 ;; FIXME: should fix the tags property of the agenda line.
22039 (defun org-agenda-set-tags ()
22040 "Set tags for the current headline."
22041 (interactive)
22042 (org-agenda-check-no-diary)
22043 (if (and (org-region-active-p) (interactive-p))
22044 (call-interactively 'org-change-tag-in-region)
22045 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22046 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22047 (org-agenda-error)))
22048 (buffer (marker-buffer hdmarker))
22049 (pos (marker-position hdmarker))
22050 (inhibit-read-only t)
22051 newhead)
22052 (org-with-remote-undo buffer
22053 (with-current-buffer buffer
22054 (widen)
22055 (goto-char pos)
22056 (save-excursion
22057 (org-show-context 'agenda))
22058 (save-excursion
22059 (and (outline-next-heading)
22060 (org-flag-heading nil))) ; show the next heading
22061 (goto-char pos)
22062 (call-interactively 'org-set-tags)
22063 (end-of-line 1)
22064 (setq newhead (org-get-heading)))
22065 (org-agenda-change-all-lines newhead hdmarker)
22066 (beginning-of-line 1)))))
22068 (defun org-agenda-toggle-archive-tag ()
22069 "Toggle the archive tag for the current entry."
22070 (interactive)
22071 (org-agenda-check-no-diary)
22072 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22073 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22074 (org-agenda-error)))
22075 (buffer (marker-buffer hdmarker))
22076 (pos (marker-position hdmarker))
22077 (inhibit-read-only t)
22078 newhead)
22079 (org-with-remote-undo buffer
22080 (with-current-buffer buffer
22081 (widen)
22082 (goto-char pos)
22083 (org-show-context 'agenda)
22084 (save-excursion
22085 (and (outline-next-heading)
22086 (org-flag-heading nil))) ; show the next heading
22087 (call-interactively 'org-toggle-archive-tag)
22088 (end-of-line 1)
22089 (setq newhead (org-get-heading)))
22090 (org-agenda-change-all-lines newhead hdmarker)
22091 (beginning-of-line 1))))
22093 (defun org-agenda-date-later (arg &optional what)
22094 "Change the date of this item to one day later."
22095 (interactive "p")
22096 (org-agenda-check-type t 'agenda 'timeline)
22097 (org-agenda-check-no-diary)
22098 (let* ((marker (or (get-text-property (point) 'org-marker)
22099 (org-agenda-error)))
22100 (buffer (marker-buffer marker))
22101 (pos (marker-position marker)))
22102 (org-with-remote-undo buffer
22103 (with-current-buffer buffer
22104 (widen)
22105 (goto-char pos)
22106 (if (not (org-at-timestamp-p))
22107 (error "Cannot find time stamp"))
22108 (org-timestamp-change arg (or what 'day)))
22109 (org-agenda-show-new-time marker org-last-changed-timestamp))
22110 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22112 (defun org-agenda-date-earlier (arg &optional what)
22113 "Change the date of this item to one day earlier."
22114 (interactive "p")
22115 (org-agenda-date-later (- arg) what))
22117 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22118 "Show new date stamp via text properties."
22119 ;; We use text properties to make this undoable
22120 (let ((inhibit-read-only t))
22121 (setq stamp (concat " " prefix " => " stamp))
22122 (save-excursion
22123 (goto-char (point-max))
22124 (while (not (bobp))
22125 (when (equal marker (get-text-property (point) 'org-marker))
22126 (move-to-column (- (window-width) (length stamp)) t)
22127 (if (featurep 'xemacs)
22128 ;; Use `duplicable' property to trigger undo recording
22129 (let ((ex (make-extent nil nil))
22130 (gl (make-glyph stamp)))
22131 (set-glyph-face gl 'secondary-selection)
22132 (set-extent-properties
22133 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22134 (insert-extent ex (1- (point)) (point-at-eol)))
22135 (add-text-properties
22136 (1- (point)) (point-at-eol)
22137 (list 'display (org-add-props stamp nil
22138 'face 'secondary-selection))))
22139 (beginning-of-line 1))
22140 (beginning-of-line 0)))))
22142 (defun org-agenda-date-prompt (arg)
22143 "Change the date of this item. Date is prompted for, with default today.
22144 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22145 be used to request time specification in the time stamp."
22146 (interactive "P")
22147 (org-agenda-check-type t 'agenda 'timeline)
22148 (org-agenda-check-no-diary)
22149 (let* ((marker (or (get-text-property (point) 'org-marker)
22150 (org-agenda-error)))
22151 (buffer (marker-buffer marker))
22152 (pos (marker-position marker)))
22153 (org-with-remote-undo buffer
22154 (with-current-buffer buffer
22155 (widen)
22156 (goto-char pos)
22157 (if (not (org-at-timestamp-p))
22158 (error "Cannot find time stamp"))
22159 (org-time-stamp arg)
22160 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22162 (defun org-agenda-schedule (arg)
22163 "Schedule the item at point."
22164 (interactive "P")
22165 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22166 (org-agenda-check-no-diary)
22167 (let* ((marker (or (get-text-property (point) 'org-marker)
22168 (org-agenda-error)))
22169 (buffer (marker-buffer marker))
22170 (pos (marker-position marker))
22171 (org-insert-labeled-timestamps-at-point nil)
22173 (org-with-remote-undo buffer
22174 (with-current-buffer buffer
22175 (widen)
22176 (goto-char pos)
22177 (setq ts (org-schedule arg)))
22178 (org-agenda-show-new-time marker ts "S"))
22179 (message "Item scheduled for %s" ts)))
22181 (defun org-agenda-deadline (arg)
22182 "Schedule the item at point."
22183 (interactive "P")
22184 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22185 (org-agenda-check-no-diary)
22186 (let* ((marker (or (get-text-property (point) 'org-marker)
22187 (org-agenda-error)))
22188 (buffer (marker-buffer marker))
22189 (pos (marker-position marker))
22190 (org-insert-labeled-timestamps-at-point nil)
22192 (org-with-remote-undo buffer
22193 (with-current-buffer buffer
22194 (widen)
22195 (goto-char pos)
22196 (setq ts (org-deadline arg)))
22197 (org-agenda-show-new-time marker ts "S"))
22198 (message "Deadline for this item set to %s" ts)))
22200 (defun org-get-heading (&optional no-tags)
22201 "Return the heading of the current entry, without the stars."
22202 (save-excursion
22203 (org-back-to-heading t)
22204 (if (looking-at
22205 (if no-tags
22206 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22207 "\\*+[ \t]+\\([^\r\n]*\\)"))
22208 (match-string 1) "")))
22210 (defun org-agenda-clock-in (&optional arg)
22211 "Start the clock on the currently selected item."
22212 (interactive "P")
22213 (org-agenda-check-no-diary)
22214 (let* ((marker (or (get-text-property (point) 'org-marker)
22215 (org-agenda-error)))
22216 (pos (marker-position marker)))
22217 (org-with-remote-undo (marker-buffer marker)
22218 (with-current-buffer (marker-buffer marker)
22219 (widen)
22220 (goto-char pos)
22221 (org-clock-in)))))
22223 (defun org-agenda-clock-out (&optional arg)
22224 "Stop the currently running clock."
22225 (interactive "P")
22226 (unless (marker-buffer org-clock-marker)
22227 (error "No running clock"))
22228 (org-with-remote-undo (marker-buffer org-clock-marker)
22229 (org-clock-out)))
22231 (defun org-agenda-clock-cancel (&optional arg)
22232 "Cancel the currently running clock."
22233 (interactive "P")
22234 (unless (marker-buffer org-clock-marker)
22235 (error "No running clock"))
22236 (org-with-remote-undo (marker-buffer org-clock-marker)
22237 (org-clock-cancel)))
22239 (defun org-agenda-diary-entry ()
22240 "Make a diary entry, like the `i' command from the calendar.
22241 All the standard commands work: block, weekly etc."
22242 (interactive)
22243 (org-agenda-check-type t 'agenda 'timeline)
22244 (require 'diary-lib)
22245 (let* ((char (progn
22246 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22247 (read-char-exclusive)))
22248 (cmd (cdr (assoc char
22249 '((?d . insert-diary-entry)
22250 (?w . insert-weekly-diary-entry)
22251 (?m . insert-monthly-diary-entry)
22252 (?y . insert-yearly-diary-entry)
22253 (?a . insert-anniversary-diary-entry)
22254 (?b . insert-block-diary-entry)
22255 (?c . insert-cyclic-diary-entry)))))
22256 (oldf (symbol-function 'calendar-cursor-to-date))
22257 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22258 (point (point))
22259 (mark (or (mark t) (point))))
22260 (unless cmd
22261 (error "No command associated with <%c>" char))
22262 (unless (and (get-text-property point 'day)
22263 (or (not (equal ?b char))
22264 (get-text-property mark 'day)))
22265 (error "Don't know which date to use for diary entry"))
22266 ;; We implement this by hacking the `calendar-cursor-to-date' function
22267 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22268 (let ((calendar-mark-ring
22269 (list (calendar-gregorian-from-absolute
22270 (or (get-text-property mark 'day)
22271 (get-text-property point 'day))))))
22272 (unwind-protect
22273 (progn
22274 (fset 'calendar-cursor-to-date
22275 (lambda (&optional error)
22276 (calendar-gregorian-from-absolute
22277 (get-text-property point 'day))))
22278 (call-interactively cmd))
22279 (fset 'calendar-cursor-to-date oldf)))))
22282 (defun org-agenda-execute-calendar-command (cmd)
22283 "Execute a calendar command from the agenda, with the date associated to
22284 the cursor position."
22285 (org-agenda-check-type t 'agenda 'timeline)
22286 (require 'diary-lib)
22287 (unless (get-text-property (point) 'day)
22288 (error "Don't know which date to use for calendar command"))
22289 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22290 (point (point))
22291 (date (calendar-gregorian-from-absolute
22292 (get-text-property point 'day)))
22293 ;; the following 3 vars are needed in the calendar
22294 (displayed-day (extract-calendar-day date))
22295 (displayed-month (extract-calendar-month date))
22296 (displayed-year (extract-calendar-year date)))
22297 (unwind-protect
22298 (progn
22299 (fset 'calendar-cursor-to-date
22300 (lambda (&optional error)
22301 (calendar-gregorian-from-absolute
22302 (get-text-property point 'day))))
22303 (call-interactively cmd))
22304 (fset 'calendar-cursor-to-date oldf))))
22306 (defun org-agenda-phases-of-moon ()
22307 "Display the phases of the moon for the 3 months around the cursor date."
22308 (interactive)
22309 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22311 (defun org-agenda-holidays ()
22312 "Display the holidays for the 3 months around the cursor date."
22313 (interactive)
22314 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22316 (defun org-agenda-sunrise-sunset (arg)
22317 "Display sunrise and sunset for the cursor date.
22318 Latitude and longitude can be specified with the variables
22319 `calendar-latitude' and `calendar-longitude'. When called with prefix
22320 argument, latitude and longitude will be prompted for."
22321 (interactive "P")
22322 (let ((calendar-longitude (if arg nil calendar-longitude))
22323 (calendar-latitude (if arg nil calendar-latitude))
22324 (calendar-location-name
22325 (if arg "the given coordinates" calendar-location-name)))
22326 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22328 (defun org-agenda-goto-calendar ()
22329 "Open the Emacs calendar with the date at the cursor."
22330 (interactive)
22331 (org-agenda-check-type t 'agenda 'timeline)
22332 (let* ((day (or (get-text-property (point) 'day)
22333 (error "Don't know which date to open in calendar")))
22334 (date (calendar-gregorian-from-absolute day))
22335 (calendar-move-hook nil)
22336 (view-calendar-holidays-initially nil)
22337 (view-diary-entries-initially nil))
22338 (calendar)
22339 (calendar-goto-date date)))
22341 (defun org-calendar-goto-agenda ()
22342 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22343 This is a command that has to be installed in `calendar-mode-map'."
22344 (interactive)
22345 (org-agenda-list nil (calendar-absolute-from-gregorian
22346 (calendar-cursor-to-date))
22347 nil))
22349 (defun org-agenda-convert-date ()
22350 (interactive)
22351 (org-agenda-check-type t 'agenda 'timeline)
22352 (let ((day (get-text-property (point) 'day))
22353 date s)
22354 (unless day
22355 (error "Don't know which date to convert"))
22356 (setq date (calendar-gregorian-from-absolute day))
22357 (setq s (concat
22358 "Gregorian: " (calendar-date-string date) "\n"
22359 "ISO: " (calendar-iso-date-string date) "\n"
22360 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22361 "Julian: " (calendar-julian-date-string date) "\n"
22362 "Astron. JD: " (calendar-astro-date-string date)
22363 " (Julian date number at noon UTC)\n"
22364 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22365 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22366 "French: " (calendar-french-date-string date) "\n"
22367 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22368 "Mayan: " (calendar-mayan-date-string date) "\n"
22369 "Coptic: " (calendar-coptic-date-string date) "\n"
22370 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22371 "Persian: " (calendar-persian-date-string date) "\n"
22372 "Chinese: " (calendar-chinese-date-string date) "\n"))
22373 (with-output-to-temp-buffer "*Dates*"
22374 (princ s))
22375 (if (fboundp 'fit-window-to-buffer)
22376 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22379 ;;;; Embedded LaTeX
22381 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22382 "Keymap for the minor `org-cdlatex-mode'.")
22384 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22385 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22386 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22387 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22388 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22390 (defvar org-cdlatex-texmathp-advice-is-done nil
22391 "Flag remembering if we have applied the advice to texmathp already.")
22393 (define-minor-mode org-cdlatex-mode
22394 "Toggle the minor `org-cdlatex-mode'.
22395 This mode supports entering LaTeX environment and math in LaTeX fragments
22396 in Org-mode.
22397 \\{org-cdlatex-mode-map}"
22398 nil " OCDL" nil
22399 (when org-cdlatex-mode (require 'cdlatex))
22400 (unless org-cdlatex-texmathp-advice-is-done
22401 (setq org-cdlatex-texmathp-advice-is-done t)
22402 (defadvice texmathp (around org-math-always-on activate)
22403 "Always return t in org-mode buffers.
22404 This is because we want to insert math symbols without dollars even outside
22405 the LaTeX math segments. If Orgmode thinks that point is actually inside
22406 en embedded LaTeX fragement, let texmathp do its job.
22407 \\[org-cdlatex-mode-map]"
22408 (interactive)
22409 (let (p)
22410 (cond
22411 ((not (org-mode-p)) ad-do-it)
22412 ((eq this-command 'cdlatex-math-symbol)
22413 (setq ad-return-value t
22414 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22416 (let ((p (org-inside-LaTeX-fragment-p)))
22417 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22418 (setq ad-return-value t
22419 texmathp-why '("Org-mode embedded math" . 0))
22420 (if p ad-do-it)))))))))
22422 (defun turn-on-org-cdlatex ()
22423 "Unconditionally turn on `org-cdlatex-mode'."
22424 (org-cdlatex-mode 1))
22426 (defun org-inside-LaTeX-fragment-p ()
22427 "Test if point is inside a LaTeX fragment.
22428 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22429 sequence appearing also before point.
22430 Even though the matchers for math are configurable, this function assumes
22431 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22432 delimiters are skipped when they have been removed by customization.
22433 The return value is nil, or a cons cell with the delimiter and
22434 and the position of this delimiter.
22436 This function does a reasonably good job, but can locally be fooled by
22437 for example currency specifications. For example it will assume being in
22438 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22439 fragments that are properly closed, but during editing, we have to live
22440 with the uncertainty caused by missing closing delimiters. This function
22441 looks only before point, not after."
22442 (catch 'exit
22443 (let ((pos (point))
22444 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22445 (lim (progn
22446 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22447 (point)))
22448 dd-on str (start 0) m re)
22449 (goto-char pos)
22450 (when dodollar
22451 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22452 re (nth 1 (assoc "$" org-latex-regexps)))
22453 (while (string-match re str start)
22454 (cond
22455 ((= (match-end 0) (length str))
22456 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22457 ((= (match-end 0) (- (length str) 5))
22458 (throw 'exit nil))
22459 (t (setq start (match-end 0))))))
22460 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22461 (goto-char pos)
22462 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22463 (and (match-beginning 2) (throw 'exit nil))
22464 ;; count $$
22465 (while (re-search-backward "\\$\\$" lim t)
22466 (setq dd-on (not dd-on)))
22467 (goto-char pos)
22468 (if dd-on (cons "$$" m))))))
22471 (defun org-try-cdlatex-tab ()
22472 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22473 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22474 - inside a LaTeX fragment, or
22475 - after the first word in a line, where an abbreviation expansion could
22476 insert a LaTeX environment."
22477 (when org-cdlatex-mode
22478 (cond
22479 ((save-excursion
22480 (skip-chars-backward "a-zA-Z0-9*")
22481 (skip-chars-backward " \t")
22482 (bolp))
22483 (cdlatex-tab) t)
22484 ((org-inside-LaTeX-fragment-p)
22485 (cdlatex-tab) t)
22486 (t nil))))
22488 (defun org-cdlatex-underscore-caret (&optional arg)
22489 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22490 Revert to the normal definition outside of these fragments."
22491 (interactive "P")
22492 (if (org-inside-LaTeX-fragment-p)
22493 (call-interactively 'cdlatex-sub-superscript)
22494 (let (org-cdlatex-mode)
22495 (call-interactively (key-binding (vector last-input-event))))))
22497 (defun org-cdlatex-math-modify (&optional arg)
22498 "Execute `cdlatex-math-modify' in LaTeX fragments.
22499 Revert to the normal definition outside of these fragments."
22500 (interactive "P")
22501 (if (org-inside-LaTeX-fragment-p)
22502 (call-interactively 'cdlatex-math-modify)
22503 (let (org-cdlatex-mode)
22504 (call-interactively (key-binding (vector last-input-event))))))
22506 (defvar org-latex-fragment-image-overlays nil
22507 "List of overlays carrying the images of latex fragments.")
22508 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22510 (defun org-remove-latex-fragment-image-overlays ()
22511 "Remove all overlays with LaTeX fragment images in current buffer."
22512 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22513 (setq org-latex-fragment-image-overlays nil))
22515 (defun org-preview-latex-fragment (&optional subtree)
22516 "Preview the LaTeX fragment at point, or all locally or globally.
22517 If the cursor is in a LaTeX fragment, create the image and overlay
22518 it over the source code. If there is no fragment at point, display
22519 all fragments in the current text, from one headline to the next. With
22520 prefix SUBTREE, display all fragments in the current subtree. With a
22521 double prefix `C-u C-u', or when the cursor is before the first headline,
22522 display all fragments in the buffer.
22523 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22524 (interactive "P")
22525 (org-remove-latex-fragment-image-overlays)
22526 (save-excursion
22527 (save-restriction
22528 (let (beg end at msg)
22529 (cond
22530 ((or (equal subtree '(16))
22531 (not (save-excursion
22532 (re-search-backward (concat "^" outline-regexp) nil t))))
22533 (setq beg (point-min) end (point-max)
22534 msg "Creating images for buffer...%s"))
22535 ((equal subtree '(4))
22536 (org-back-to-heading)
22537 (setq beg (point) end (org-end-of-subtree t)
22538 msg "Creating images for subtree...%s"))
22540 (if (setq at (org-inside-LaTeX-fragment-p))
22541 (goto-char (max (point-min) (- (cdr at) 2)))
22542 (org-back-to-heading))
22543 (setq beg (point) end (progn (outline-next-heading) (point))
22544 msg (if at "Creating image...%s"
22545 "Creating images for entry...%s"))))
22546 (message msg "")
22547 (narrow-to-region beg end)
22548 (goto-char beg)
22549 (org-format-latex
22550 (concat "ltxpng/" (file-name-sans-extension
22551 (file-name-nondirectory
22552 buffer-file-name)))
22553 default-directory 'overlays msg at 'forbuffer)
22554 (message msg "done. Use `C-c C-c' to remove images.")))))
22556 (defvar org-latex-regexps
22557 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22558 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22559 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22560 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22561 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22562 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22563 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22564 "Regular expressions for matching embedded LaTeX.")
22566 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22567 "Replace LaTeX fragments with links to an image, and produce images."
22568 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22569 (let* ((prefixnodir (file-name-nondirectory prefix))
22570 (absprefix (expand-file-name prefix dir))
22571 (todir (file-name-directory absprefix))
22572 (opt org-format-latex-options)
22573 (matchers (plist-get opt :matchers))
22574 (re-list org-latex-regexps)
22575 (cnt 0) txt link beg end re e checkdir
22576 m n block linkfile movefile ov)
22577 ;; Check if there are old images files with this prefix, and remove them
22578 (when (file-directory-p todir)
22579 (mapc 'delete-file
22580 (directory-files
22581 todir 'full
22582 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22583 ;; Check the different regular expressions
22584 (while (setq e (pop re-list))
22585 (setq m (car e) re (nth 1 e) n (nth 2 e)
22586 block (if (nth 3 e) "\n\n" ""))
22587 (when (member m matchers)
22588 (goto-char (point-min))
22589 (while (re-search-forward re nil t)
22590 (when (or (not at) (equal (cdr at) (match-beginning n)))
22591 (setq txt (match-string n)
22592 beg (match-beginning n) end (match-end n)
22593 cnt (1+ cnt)
22594 linkfile (format "%s_%04d.png" prefix cnt)
22595 movefile (format "%s_%04d.png" absprefix cnt)
22596 link (concat block "[[file:" linkfile "]]" block))
22597 (if msg (message msg cnt))
22598 (goto-char beg)
22599 (unless checkdir ; make sure the directory exists
22600 (setq checkdir t)
22601 (or (file-directory-p todir) (make-directory todir)))
22602 (org-create-formula-image
22603 txt movefile opt forbuffer)
22604 (if overlays
22605 (progn
22606 (setq ov (org-make-overlay beg end))
22607 (if (featurep 'xemacs)
22608 (progn
22609 (org-overlay-put ov 'invisible t)
22610 (org-overlay-put
22611 ov 'end-glyph
22612 (make-glyph (vector 'png :file movefile))))
22613 (org-overlay-put
22614 ov 'display
22615 (list 'image :type 'png :file movefile :ascent 'center)))
22616 (push ov org-latex-fragment-image-overlays)
22617 (goto-char end))
22618 (delete-region beg end)
22619 (insert link))))))))
22621 ;; This function borrows from Ganesh Swami's latex2png.el
22622 (defun org-create-formula-image (string tofile options buffer)
22623 (let* ((tmpdir (if (featurep 'xemacs)
22624 (temp-directory)
22625 temporary-file-directory))
22626 (texfilebase (make-temp-name
22627 (expand-file-name "orgtex" tmpdir)))
22628 (texfile (concat texfilebase ".tex"))
22629 (dvifile (concat texfilebase ".dvi"))
22630 (pngfile (concat texfilebase ".png"))
22631 (fnh (face-attribute 'default :height nil))
22632 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
22633 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
22634 (fg (or (plist-get options (if buffer :foreground :html-foreground))
22635 "Black"))
22636 (bg (or (plist-get options (if buffer :background :html-background))
22637 "Transparent")))
22638 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
22639 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
22640 (with-temp-file texfile
22641 (insert org-format-latex-header
22642 "\n\\begin{document}\n" string "\n\\end{document}\n"))
22643 (let ((dir default-directory))
22644 (condition-case nil
22645 (progn
22646 (cd tmpdir)
22647 (call-process "latex" nil nil nil texfile))
22648 (error nil))
22649 (cd dir))
22650 (if (not (file-exists-p dvifile))
22651 (progn (message "Failed to create dvi file from %s" texfile) nil)
22652 (call-process "dvipng" nil nil nil
22653 "-E" "-fg" fg "-bg" bg
22654 "-D" dpi
22655 ;;"-x" scale "-y" scale
22656 "-T" "tight"
22657 "-o" pngfile
22658 dvifile)
22659 (if (not (file-exists-p pngfile))
22660 (progn (message "Failed to create png file from %s" texfile) nil)
22661 ;; Use the requested file name and clean up
22662 (copy-file pngfile tofile 'replace)
22663 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
22664 (delete-file (concat texfilebase e)))
22665 pngfile))))
22667 (defun org-dvipng-color (attr)
22668 "Return an rgb color specification for dvipng."
22669 (apply 'format "rgb %s %s %s"
22670 (mapcar 'org-normalize-color
22671 (color-values (face-attribute 'default attr nil)))))
22673 (defun org-normalize-color (value)
22674 "Return string to be used as color value for an RGB component."
22675 (format "%g" (/ value 65535.0)))
22677 ;;;; Exporting
22679 ;;; Variables, constants, and parameter plists
22681 (defconst org-level-max 20)
22683 (defvar org-export-html-preamble nil
22684 "Preamble, to be inserted just after <body>. Set by publishing functions.")
22685 (defvar org-export-html-postamble nil
22686 "Preamble, to be inserted just before </body>. Set by publishing functions.")
22687 (defvar org-export-html-auto-preamble t
22688 "Should default preamble be inserted? Set by publishing functions.")
22689 (defvar org-export-html-auto-postamble t
22690 "Should default postamble be inserted? Set by publishing functions.")
22691 (defvar org-current-export-file nil) ; dynamically scoped parameter
22692 (defvar org-current-export-dir nil) ; dynamically scoped parameter
22695 (defconst org-export-plist-vars
22696 '((:language . org-export-default-language)
22697 (:customtime . org-display-custom-times)
22698 (:headline-levels . org-export-headline-levels)
22699 (:section-numbers . org-export-with-section-numbers)
22700 (:table-of-contents . org-export-with-toc)
22701 (:preserve-breaks . org-export-preserve-breaks)
22702 (:archived-trees . org-export-with-archived-trees)
22703 (:emphasize . org-export-with-emphasize)
22704 (:sub-superscript . org-export-with-sub-superscripts)
22705 (:special-strings . org-export-with-special-strings)
22706 (:footnotes . org-export-with-footnotes)
22707 (:drawers . org-export-with-drawers)
22708 (:tags . org-export-with-tags)
22709 (:TeX-macros . org-export-with-TeX-macros)
22710 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
22711 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
22712 (:fixed-width . org-export-with-fixed-width)
22713 (:timestamps . org-export-with-timestamps)
22714 (:author-info . org-export-author-info)
22715 (:time-stamp-file . org-export-time-stamp-file)
22716 (:tables . org-export-with-tables)
22717 (:table-auto-headline . org-export-highlight-first-table-line)
22718 (:style . org-export-html-style)
22719 (:agenda-style . org-agenda-export-html-style)
22720 (:convert-org-links . org-export-html-link-org-files-as-html)
22721 (:inline-images . org-export-html-inline-images)
22722 (:html-extension . org-export-html-extension)
22723 (:html-table-tag . org-export-html-table-tag)
22724 (:expand-quoted-html . org-export-html-expand)
22725 (:timestamp . org-export-html-with-timestamp)
22726 (:publishing-directory . org-export-publishing-directory)
22727 (:preamble . org-export-html-preamble)
22728 (:postamble . org-export-html-postamble)
22729 (:auto-preamble . org-export-html-auto-preamble)
22730 (:auto-postamble . org-export-html-auto-postamble)
22731 (:author . user-full-name)
22732 (:email . user-mail-address)))
22734 (defun org-default-export-plist ()
22735 "Return the property list with default settings for the export variables."
22736 (let ((l org-export-plist-vars) rtn e)
22737 (while (setq e (pop l))
22738 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
22739 rtn))
22741 (defun org-infile-export-plist ()
22742 "Return the property list with file-local settings for export."
22743 (save-excursion
22744 (goto-char 0)
22745 (let ((re (org-make-options-regexp
22746 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
22747 p key val text options)
22748 (while (re-search-forward re nil t)
22749 (setq key (org-match-string-no-properties 1)
22750 val (org-match-string-no-properties 2))
22751 (cond
22752 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
22753 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
22754 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
22755 ((string-equal key "DATE") (setq p (plist-put p :date val)))
22756 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
22757 ((string-equal key "TEXT")
22758 (setq text (if text (concat text "\n" val) val)))
22759 ((string-equal key "OPTIONS") (setq options val))))
22760 (setq p (plist-put p :text text))
22761 (when options
22762 (let ((op '(("H" . :headline-levels)
22763 ("num" . :section-numbers)
22764 ("toc" . :table-of-contents)
22765 ("\\n" . :preserve-breaks)
22766 ("@" . :expand-quoted-html)
22767 (":" . :fixed-width)
22768 ("|" . :tables)
22769 ("^" . :sub-superscript)
22770 ("-" . :special-strings)
22771 ("f" . :footnotes)
22772 ("d" . :drawers)
22773 ("tags" . :tags)
22774 ("*" . :emphasize)
22775 ("TeX" . :TeX-macros)
22776 ("LaTeX" . :LaTeX-fragments)
22777 ("skip" . :skip-before-1st-heading)
22778 ("author" . :author-info)
22779 ("timestamp" . :time-stamp-file)))
22781 (while (setq o (pop op))
22782 (if (string-match (concat (regexp-quote (car o))
22783 ":\\([^ \t\n\r;,.]*\\)")
22784 options)
22785 (setq p (plist-put p (cdr o)
22786 (car (read-from-string
22787 (match-string 1 options)))))))))
22788 p)))
22790 (defun org-export-directory (type plist)
22791 (let* ((val (plist-get plist :publishing-directory))
22792 (dir (if (listp val)
22793 (or (cdr (assoc type val)) ".")
22794 val)))
22795 dir))
22797 (defun org-skip-comments (lines)
22798 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22799 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22800 (re2 "^\\(\\*+\\)[ \t\n\r]")
22801 (case-fold-search nil)
22802 rtn line level)
22803 (while (setq line (pop lines))
22804 (cond
22805 ((and (string-match re1 line)
22806 (setq level (- (match-end 1) (match-beginning 1))))
22807 ;; Beginning of a COMMENT subtree. Skip it.
22808 (while (and (setq line (pop lines))
22809 (or (not (string-match re2 line))
22810 (> (- (match-end 1) (match-beginning 1)) level))))
22811 (setq lines (cons line lines)))
22812 ((string-match "^#" line)
22813 ;; an ordinary comment line
22815 ((and org-export-table-remove-special-lines
22816 (string-match "^[ \t]*|" line)
22817 (or (string-match "^[ \t]*| *[!_^] *|" line)
22818 (and (string-match "| *<[0-9]+> *|" line)
22819 (not (string-match "| *[^ <|]" line)))))
22820 ;; a special table line that should be removed
22822 (t (setq rtn (cons line rtn)))))
22823 (nreverse rtn)))
22825 (defun org-export (&optional arg)
22826 (interactive)
22827 (let ((help "[t] insert the export option template
22828 \[v] limit export to visible part of outline tree
22830 \[a] export as ASCII
22832 \[h] export as HTML
22833 \[H] export as HTML to temporary buffer
22834 \[R] export region as HTML
22835 \[b] export as HTML and browse immediately
22836 \[x] export as XOXO
22838 \[l] export as LaTeX
22839 \[L] export as LaTeX to temporary buffer
22841 \[i] export current file as iCalendar file
22842 \[I] export all agenda files as iCalendar files
22843 \[c] export agenda files into combined iCalendar file
22845 \[F] publish current file
22846 \[P] publish current project
22847 \[X] publish... (project will be prompted for)
22848 \[A] publish all projects")
22849 (cmds
22850 '((?t . org-insert-export-options-template)
22851 (?v . org-export-visible)
22852 (?a . org-export-as-ascii)
22853 (?h . org-export-as-html)
22854 (?b . org-export-as-html-and-open)
22855 (?H . org-export-as-html-to-buffer)
22856 (?R . org-export-region-as-html)
22857 (?x . org-export-as-xoxo)
22858 (?l . org-export-as-latex)
22859 (?L . org-export-as-latex-to-buffer)
22860 (?i . org-export-icalendar-this-file)
22861 (?I . org-export-icalendar-all-agenda-files)
22862 (?c . org-export-icalendar-combine-agenda-files)
22863 (?F . org-publish-current-file)
22864 (?P . org-publish-current-project)
22865 (?X . org-publish)
22866 (?A . org-publish-all)))
22867 r1 r2 ass)
22868 (save-window-excursion
22869 (delete-other-windows)
22870 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22871 (princ help))
22872 (message "Select command: ")
22873 (setq r1 (read-char-exclusive)))
22874 (setq r2 (if (< r1 27) (+ r1 96) r1))
22875 (if (setq ass (assq r2 cmds))
22876 (call-interactively (cdr ass))
22877 (error "No command associated with key %c" r1))))
22879 (defconst org-html-entities
22880 '(("nbsp")
22881 ("iexcl")
22882 ("cent")
22883 ("pound")
22884 ("curren")
22885 ("yen")
22886 ("brvbar")
22887 ("vert" . "&#124;")
22888 ("sect")
22889 ("uml")
22890 ("copy")
22891 ("ordf")
22892 ("laquo")
22893 ("not")
22894 ("shy")
22895 ("reg")
22896 ("macr")
22897 ("deg")
22898 ("plusmn")
22899 ("sup2")
22900 ("sup3")
22901 ("acute")
22902 ("micro")
22903 ("para")
22904 ("middot")
22905 ("odot"."o")
22906 ("star"."*")
22907 ("cedil")
22908 ("sup1")
22909 ("ordm")
22910 ("raquo")
22911 ("frac14")
22912 ("frac12")
22913 ("frac34")
22914 ("iquest")
22915 ("Agrave")
22916 ("Aacute")
22917 ("Acirc")
22918 ("Atilde")
22919 ("Auml")
22920 ("Aring") ("AA"."&Aring;")
22921 ("AElig")
22922 ("Ccedil")
22923 ("Egrave")
22924 ("Eacute")
22925 ("Ecirc")
22926 ("Euml")
22927 ("Igrave")
22928 ("Iacute")
22929 ("Icirc")
22930 ("Iuml")
22931 ("ETH")
22932 ("Ntilde")
22933 ("Ograve")
22934 ("Oacute")
22935 ("Ocirc")
22936 ("Otilde")
22937 ("Ouml")
22938 ("times")
22939 ("Oslash")
22940 ("Ugrave")
22941 ("Uacute")
22942 ("Ucirc")
22943 ("Uuml")
22944 ("Yacute")
22945 ("THORN")
22946 ("szlig")
22947 ("agrave")
22948 ("aacute")
22949 ("acirc")
22950 ("atilde")
22951 ("auml")
22952 ("aring")
22953 ("aelig")
22954 ("ccedil")
22955 ("egrave")
22956 ("eacute")
22957 ("ecirc")
22958 ("euml")
22959 ("igrave")
22960 ("iacute")
22961 ("icirc")
22962 ("iuml")
22963 ("eth")
22964 ("ntilde")
22965 ("ograve")
22966 ("oacute")
22967 ("ocirc")
22968 ("otilde")
22969 ("ouml")
22970 ("divide")
22971 ("oslash")
22972 ("ugrave")
22973 ("uacute")
22974 ("ucirc")
22975 ("uuml")
22976 ("yacute")
22977 ("thorn")
22978 ("yuml")
22979 ("fnof")
22980 ("Alpha")
22981 ("Beta")
22982 ("Gamma")
22983 ("Delta")
22984 ("Epsilon")
22985 ("Zeta")
22986 ("Eta")
22987 ("Theta")
22988 ("Iota")
22989 ("Kappa")
22990 ("Lambda")
22991 ("Mu")
22992 ("Nu")
22993 ("Xi")
22994 ("Omicron")
22995 ("Pi")
22996 ("Rho")
22997 ("Sigma")
22998 ("Tau")
22999 ("Upsilon")
23000 ("Phi")
23001 ("Chi")
23002 ("Psi")
23003 ("Omega")
23004 ("alpha")
23005 ("beta")
23006 ("gamma")
23007 ("delta")
23008 ("epsilon")
23009 ("varepsilon"."&epsilon;")
23010 ("zeta")
23011 ("eta")
23012 ("theta")
23013 ("iota")
23014 ("kappa")
23015 ("lambda")
23016 ("mu")
23017 ("nu")
23018 ("xi")
23019 ("omicron")
23020 ("pi")
23021 ("rho")
23022 ("sigmaf") ("varsigma"."&sigmaf;")
23023 ("sigma")
23024 ("tau")
23025 ("upsilon")
23026 ("phi")
23027 ("chi")
23028 ("psi")
23029 ("omega")
23030 ("thetasym") ("vartheta"."&thetasym;")
23031 ("upsih")
23032 ("piv")
23033 ("bull") ("bullet"."&bull;")
23034 ("hellip") ("dots"."&hellip;")
23035 ("prime")
23036 ("Prime")
23037 ("oline")
23038 ("frasl")
23039 ("weierp")
23040 ("image")
23041 ("real")
23042 ("trade")
23043 ("alefsym")
23044 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23045 ("uarr") ("uparrow"."&uarr;")
23046 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23047 ("darr")("downarrow"."&darr;")
23048 ("harr") ("leftrightarrow"."&harr;")
23049 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23050 ("lArr") ("Leftarrow"."&lArr;")
23051 ("uArr") ("Uparrow"."&uArr;")
23052 ("rArr") ("Rightarrow"."&rArr;")
23053 ("dArr") ("Downarrow"."&dArr;")
23054 ("hArr") ("Leftrightarrow"."&hArr;")
23055 ("forall")
23056 ("part") ("partial"."&part;")
23057 ("exist") ("exists"."&exist;")
23058 ("empty") ("emptyset"."&empty;")
23059 ("nabla")
23060 ("isin") ("in"."&isin;")
23061 ("notin")
23062 ("ni")
23063 ("prod")
23064 ("sum")
23065 ("minus")
23066 ("lowast") ("ast"."&lowast;")
23067 ("radic")
23068 ("prop") ("proptp"."&prop;")
23069 ("infin") ("infty"."&infin;")
23070 ("ang") ("angle"."&ang;")
23071 ("and") ("wedge"."&and;")
23072 ("or") ("vee"."&or;")
23073 ("cap")
23074 ("cup")
23075 ("int")
23076 ("there4")
23077 ("sim")
23078 ("cong") ("simeq"."&cong;")
23079 ("asymp")("approx"."&asymp;")
23080 ("ne") ("neq"."&ne;")
23081 ("equiv")
23082 ("le")
23083 ("ge")
23084 ("sub") ("subset"."&sub;")
23085 ("sup") ("supset"."&sup;")
23086 ("nsub")
23087 ("sube")
23088 ("supe")
23089 ("oplus")
23090 ("otimes")
23091 ("perp")
23092 ("sdot") ("cdot"."&sdot;")
23093 ("lceil")
23094 ("rceil")
23095 ("lfloor")
23096 ("rfloor")
23097 ("lang")
23098 ("rang")
23099 ("loz") ("Diamond"."&loz;")
23100 ("spades") ("spadesuit"."&spades;")
23101 ("clubs") ("clubsuit"."&clubs;")
23102 ("hearts") ("diamondsuit"."&hearts;")
23103 ("diams") ("diamondsuit"."&diams;")
23104 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23105 ("quot")
23106 ("amp")
23107 ("lt")
23108 ("gt")
23109 ("OElig")
23110 ("oelig")
23111 ("Scaron")
23112 ("scaron")
23113 ("Yuml")
23114 ("circ")
23115 ("tilde")
23116 ("ensp")
23117 ("emsp")
23118 ("thinsp")
23119 ("zwnj")
23120 ("zwj")
23121 ("lrm")
23122 ("rlm")
23123 ("ndash")
23124 ("mdash")
23125 ("lsquo")
23126 ("rsquo")
23127 ("sbquo")
23128 ("ldquo")
23129 ("rdquo")
23130 ("bdquo")
23131 ("dagger")
23132 ("Dagger")
23133 ("permil")
23134 ("lsaquo")
23135 ("rsaquo")
23136 ("euro")
23138 ("arccos"."arccos")
23139 ("arcsin"."arcsin")
23140 ("arctan"."arctan")
23141 ("arg"."arg")
23142 ("cos"."cos")
23143 ("cosh"."cosh")
23144 ("cot"."cot")
23145 ("coth"."coth")
23146 ("csc"."csc")
23147 ("deg"."deg")
23148 ("det"."det")
23149 ("dim"."dim")
23150 ("exp"."exp")
23151 ("gcd"."gcd")
23152 ("hom"."hom")
23153 ("inf"."inf")
23154 ("ker"."ker")
23155 ("lg"."lg")
23156 ("lim"."lim")
23157 ("liminf"."liminf")
23158 ("limsup"."limsup")
23159 ("ln"."ln")
23160 ("log"."log")
23161 ("max"."max")
23162 ("min"."min")
23163 ("Pr"."Pr")
23164 ("sec"."sec")
23165 ("sin"."sin")
23166 ("sinh"."sinh")
23167 ("sup"."sup")
23168 ("tan"."tan")
23169 ("tanh"."tanh")
23171 "Entities for TeX->HTML translation.
23172 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23173 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23174 In that case, \"\\ent\" will be translated to \"&other;\".
23175 The list contains HTML entities for Latin-1, Greek and other symbols.
23176 It is supplemented by a number of commonly used TeX macros with appropriate
23177 translations. There is currently no way for users to extend this.")
23179 ;;; General functions for all backends
23181 (defun org-cleaned-string-for-export (string &rest parameters)
23182 "Cleanup a buffer STRING so that links can be created safely."
23183 (interactive)
23184 (let* ((re-radio (and org-target-link-regexp
23185 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23186 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23187 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23188 (re-archive (concat ":" org-archive-tag ":"))
23189 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23190 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23191 (htmlp (plist-get parameters :for-html))
23192 (asciip (plist-get parameters :for-ascii))
23193 (latexp (plist-get parameters :for-LaTeX))
23194 (commentsp (plist-get parameters :comments))
23195 (archived-trees (plist-get parameters :archived-trees))
23196 (inhibit-read-only t)
23197 (drawers org-drawers)
23198 (exp-drawers (plist-get parameters :drawers))
23199 (outline-regexp "\\*+ ")
23200 a b xx
23201 rtn p)
23202 (with-current-buffer (get-buffer-create " org-mode-tmp")
23203 (erase-buffer)
23204 (insert string)
23205 ;; Remove license-to-kill stuff
23206 (while (setq p (text-property-any (point-min) (point-max)
23207 :org-license-to-kill t))
23208 (delete-region p (next-single-property-change p :org-license-to-kill)))
23210 (let ((org-inhibit-startup t)) (org-mode))
23211 (untabify (point-min) (point-max))
23213 ;; Get the correct stuff before the first headline
23214 (when (plist-get parameters :skip-before-1st-heading)
23215 (goto-char (point-min))
23216 (when (re-search-forward "^\\*+[ \t]" nil t)
23217 (delete-region (point-min) (match-beginning 0))
23218 (goto-char (point-min))
23219 (insert "\n")))
23220 (when (plist-get parameters :add-text)
23221 (goto-char (point-min))
23222 (insert (plist-get parameters :add-text) "\n"))
23224 ;; Get rid of archived trees
23225 (when (not (eq archived-trees t))
23226 (goto-char (point-min))
23227 (while (re-search-forward re-archive nil t)
23228 (if (not (org-on-heading-p t))
23229 (org-end-of-subtree t)
23230 (beginning-of-line 1)
23231 (setq a (if archived-trees
23232 (1+ (point-at-eol)) (point))
23233 b (org-end-of-subtree t))
23234 (if (> b a) (delete-region a b)))))
23236 ;; Get rid of drawers
23237 (unless (eq t exp-drawers)
23238 (goto-char (point-min))
23239 (let ((re (concat "^[ \t]*:\\("
23240 (mapconcat
23241 'identity
23242 (org-delete-all exp-drawers
23243 (copy-sequence drawers))
23244 "\\|")
23245 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23246 (while (re-search-forward re nil t)
23247 (replace-match ""))))
23249 ;; Find targets in comments and move them out of comments,
23250 ;; but mark them as targets that should be invisible
23251 (goto-char (point-min))
23252 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23253 (replace-match "\\1(INVISIBLE)"))
23255 ;; Protect backend specific stuff, throw away the others.
23256 (let ((formatters
23257 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23258 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23259 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23260 fmt)
23261 (goto-char (point-min))
23262 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23263 (goto-char (match-end 0))
23264 (while (not (looking-at "#\\+END_EXAMPLE"))
23265 (insert ": ")
23266 (beginning-of-line 2)))
23267 (goto-char (point-min))
23268 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23269 (add-text-properties (match-beginning 0) (match-end 0)
23270 '(org-protected t)))
23271 (while formatters
23272 (setq fmt (pop formatters))
23273 (when (car fmt)
23274 (goto-char (point-min))
23275 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23276 ":[ \t]*\\(.*\\)") nil t)
23277 (replace-match "\\1" t)
23278 (add-text-properties
23279 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23280 '(org-protected t))))
23281 (goto-char (point-min))
23282 (while (re-search-forward
23283 (concat "^#\\+"
23284 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23285 (cadddr fmt) "\\>.*\n?") nil t)
23286 (if (car fmt)
23287 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23288 '(org-protected t))
23289 (delete-region (match-beginning 0) (match-end 0))))))
23291 ;; Protect quoted subtrees
23292 (goto-char (point-min))
23293 (while (re-search-forward re-quote nil t)
23294 (goto-char (match-beginning 0))
23295 (end-of-line 1)
23296 (add-text-properties (point) (org-end-of-subtree t)
23297 '(org-protected t)))
23299 ;; Protect verbatim elements
23300 (goto-char (point-min))
23301 (while (re-search-forward org-verbatim-re nil t)
23302 (add-text-properties (match-beginning 4) (match-end 4)
23303 '(org-protected t))
23304 (goto-char (1+ (match-end 4))))
23306 ;; Remove subtrees that are commented
23307 (goto-char (point-min))
23308 (while (re-search-forward re-commented nil t)
23309 (goto-char (match-beginning 0))
23310 (delete-region (point) (org-end-of-subtree t)))
23312 ;; Remove special table lines
23313 (when org-export-table-remove-special-lines
23314 (goto-char (point-min))
23315 (while (re-search-forward "^[ \t]*|" nil t)
23316 (beginning-of-line 1)
23317 (if (or (looking-at "[ \t]*| *[!_^] *|")
23318 (and (looking-at ".*?| *<[0-9]+> *|")
23319 (not (looking-at ".*?| *[^ <|]"))))
23320 (delete-region (max (point-min) (1- (point-at-bol)))
23321 (point-at-eol))
23322 (end-of-line 1))))
23324 ;; Specific LaTeX stuff
23325 (when latexp
23326 (require 'org-export-latex nil)
23327 (org-export-latex-cleaned-string))
23329 (when asciip
23330 (org-export-ascii-clean-string))
23332 ;; Specific HTML stuff
23333 (when htmlp
23334 ;; Convert LaTeX fragments to images
23335 (when (plist-get parameters :LaTeX-fragments)
23336 (org-format-latex
23337 (concat "ltxpng/" (file-name-sans-extension
23338 (file-name-nondirectory
23339 org-current-export-file)))
23340 org-current-export-dir nil "Creating LaTeX image %s"))
23341 (message "Exporting..."))
23343 ;; Remove or replace comments
23344 (goto-char (point-min))
23345 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23346 (if commentsp
23347 (progn (add-text-properties
23348 (match-beginning 0) (match-end 0) '(org-protected t))
23349 (replace-match (format commentsp (match-string 1)) t t))
23350 (replace-match "")))
23352 ;; Find matches for radio targets and turn them into internal links
23353 (goto-char (point-min))
23354 (when re-radio
23355 (while (re-search-forward re-radio nil t)
23356 (org-if-unprotected
23357 (replace-match "\\1[[\\2]]"))))
23359 ;; Find all links that contain a newline and put them into a single line
23360 (goto-char (point-min))
23361 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23362 (org-if-unprotected
23363 (replace-match "\\1 \\3")
23364 (goto-char (match-beginning 0))))
23367 ;; Normalize links: Convert angle and plain links into bracket links
23368 ;; Expand link abbreviations
23369 (goto-char (point-min))
23370 (while (re-search-forward re-plain-link nil t)
23371 (goto-char (1- (match-end 0)))
23372 (org-if-unprotected
23373 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23374 ":" (match-string 3) "]]")))
23375 ;; added 'org-link face to links
23376 (put-text-property 0 (length s) 'face 'org-link s)
23377 (replace-match s t t))))
23378 (goto-char (point-min))
23379 (while (re-search-forward re-angle-link nil t)
23380 (goto-char (1- (match-end 0)))
23381 (org-if-unprotected
23382 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23383 ":" (match-string 3) "]]")))
23384 (put-text-property 0 (length s) 'face 'org-link s)
23385 (replace-match s t t))))
23386 (goto-char (point-min))
23387 (while (re-search-forward org-bracket-link-regexp nil t)
23388 (org-if-unprotected
23389 (let* ((s (concat "[[" (setq xx (save-match-data
23390 (org-link-expand-abbrev (match-string 1))))
23392 (if (match-end 3)
23393 (match-string 2)
23394 (concat "[" xx "]"))
23395 "]")))
23396 (put-text-property 0 (length s) 'face 'org-link s)
23397 (replace-match s t t))))
23399 ;; Find multiline emphasis and put them into single line
23400 (when (plist-get parameters :emph-multiline)
23401 (goto-char (point-min))
23402 (while (re-search-forward org-emph-re nil t)
23403 (if (not (= (char-after (match-beginning 3))
23404 (char-after (match-beginning 4))))
23405 (org-if-unprotected
23406 (subst-char-in-region (match-beginning 0) (match-end 0)
23407 ?\n ?\ t)
23408 (goto-char (1- (match-end 0))))
23409 (goto-char (1+ (match-beginning 0))))))
23411 (setq rtn (buffer-string)))
23412 (kill-buffer " org-mode-tmp")
23413 rtn))
23415 (defun org-export-grab-title-from-buffer ()
23416 "Get a title for the current document, from looking at the buffer."
23417 (let ((inhibit-read-only t))
23418 (save-excursion
23419 (goto-char (point-min))
23420 (let ((end (save-excursion (outline-next-heading) (point))))
23421 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23422 ;; Mark the line so that it will not be exported as normal text.
23423 (org-unmodified
23424 (add-text-properties (match-beginning 0) (match-end 0)
23425 (list :org-license-to-kill t)))
23426 ;; Return the title string
23427 (org-trim (match-string 0)))))))
23429 (defun org-export-get-title-from-subtree ()
23430 "Return subtree title and exclude it from export."
23431 (let (title (m (mark)))
23432 (save-excursion
23433 (goto-char (region-beginning))
23434 (when (and (org-at-heading-p)
23435 (>= (org-end-of-subtree t t) (region-end)))
23436 ;; This is a subtree, we take the title from the first heading
23437 (goto-char (region-beginning))
23438 (looking-at org-todo-line-regexp)
23439 (setq title (match-string 3))
23440 (org-unmodified
23441 (add-text-properties (point) (1+ (point-at-eol))
23442 (list :org-license-to-kill t)))))
23443 title))
23445 (defun org-solidify-link-text (s &optional alist)
23446 "Take link text and make a safe target out of it."
23447 (save-match-data
23448 (let* ((rtn
23449 (mapconcat
23450 'identity
23451 (org-split-string s "[ \t\r\n]+") "--"))
23452 (a (assoc rtn alist)))
23453 (or (cdr a) rtn))))
23455 (defun org-get-min-level (lines)
23456 "Get the minimum level in LINES."
23457 (let ((re "^\\(\\*+\\) ") l min)
23458 (catch 'exit
23459 (while (setq l (pop lines))
23460 (if (string-match re l)
23461 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23462 1)))
23464 ;; Variable holding the vector with section numbers
23465 (defvar org-section-numbers (make-vector org-level-max 0))
23467 (defun org-init-section-numbers ()
23468 "Initialize the vector for the section numbers."
23469 (let* ((level -1)
23470 (numbers (nreverse (org-split-string "" "\\.")))
23471 (depth (1- (length org-section-numbers)))
23472 (i depth) number-string)
23473 (while (>= i 0)
23474 (if (> i level)
23475 (aset org-section-numbers i 0)
23476 (setq number-string (or (car numbers) "0"))
23477 (if (string-match "\\`[A-Z]\\'" number-string)
23478 (aset org-section-numbers i
23479 (- (string-to-char number-string) ?A -1))
23480 (aset org-section-numbers i (string-to-number number-string)))
23481 (pop numbers))
23482 (setq i (1- i)))))
23484 (defun org-section-number (&optional level)
23485 "Return a string with the current section number.
23486 When LEVEL is non-nil, increase section numbers on that level."
23487 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23488 (when level
23489 (when (> level -1)
23490 (aset org-section-numbers
23491 level (1+ (aref org-section-numbers level))))
23492 (setq idx (1+ level))
23493 (while (<= idx depth)
23494 (if (not (= idx 1))
23495 (aset org-section-numbers idx 0))
23496 (setq idx (1+ idx))))
23497 (setq idx 0)
23498 (while (<= idx depth)
23499 (setq n (aref org-section-numbers idx))
23500 (setq string (concat string (if (not (string= string "")) "." "")
23501 (int-to-string n)))
23502 (setq idx (1+ idx)))
23503 (save-match-data
23504 (if (string-match "\\`\\([@0]\\.\\)+" string)
23505 (setq string (replace-match "" t nil string)))
23506 (if (string-match "\\(\\.0\\)+\\'" string)
23507 (setq string (replace-match "" t nil string))))
23508 string))
23510 ;;; ASCII export
23512 (defvar org-last-level nil) ; dynamically scoped variable
23513 (defvar org-min-level nil) ; dynamically scoped variable
23514 (defvar org-levels-open nil) ; dynamically scoped parameter
23515 (defvar org-ascii-current-indentation nil) ; For communication
23517 (defun org-export-as-ascii (arg)
23518 "Export the outline as a pretty ASCII file.
23519 If there is an active region, export only the region.
23520 The prefix ARG specifies how many levels of the outline should become
23521 underlined headlines. The default is 3."
23522 (interactive "P")
23523 (setq-default org-todo-line-regexp org-todo-line-regexp)
23524 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23525 (org-infile-export-plist)))
23526 (region-p (org-region-active-p))
23527 (subtree-p
23528 (when region-p
23529 (save-excursion
23530 (goto-char (region-beginning))
23531 (and (org-at-heading-p)
23532 (>= (org-end-of-subtree t t) (region-end))))))
23533 (custom-times org-display-custom-times)
23534 (org-ascii-current-indentation '(0 . 0))
23535 (level 0) line txt
23536 (umax nil)
23537 (umax-toc nil)
23538 (case-fold-search nil)
23539 (filename (concat (file-name-as-directory
23540 (org-export-directory :ascii opt-plist))
23541 (file-name-sans-extension
23542 (or (and subtree-p
23543 (org-entry-get (region-beginning)
23544 "EXPORT_FILE_NAME" t))
23545 (file-name-nondirectory buffer-file-name)))
23546 ".txt"))
23547 (filename (if (equal (file-truename filename)
23548 (file-truename buffer-file-name))
23549 (concat filename ".txt")
23550 filename))
23551 (buffer (find-file-noselect filename))
23552 (org-levels-open (make-vector org-level-max nil))
23553 (odd org-odd-levels-only)
23554 (date (plist-get opt-plist :date))
23555 (author (plist-get opt-plist :author))
23556 (title (or (and subtree-p (org-export-get-title-from-subtree))
23557 (plist-get opt-plist :title)
23558 (and (not
23559 (plist-get opt-plist :skip-before-1st-heading))
23560 (org-export-grab-title-from-buffer))
23561 (file-name-sans-extension
23562 (file-name-nondirectory buffer-file-name))))
23563 (email (plist-get opt-plist :email))
23564 (language (plist-get opt-plist :language))
23565 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23566 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23567 (todo nil)
23568 (lang-words nil)
23569 (region
23570 (buffer-substring
23571 (if (org-region-active-p) (region-beginning) (point-min))
23572 (if (org-region-active-p) (region-end) (point-max))))
23573 (lines (org-split-string
23574 (org-cleaned-string-for-export
23575 region
23576 :for-ascii t
23577 :skip-before-1st-heading
23578 (plist-get opt-plist :skip-before-1st-heading)
23579 :drawers (plist-get opt-plist :drawers)
23580 :verbatim-multiline t
23581 :archived-trees
23582 (plist-get opt-plist :archived-trees)
23583 :add-text (plist-get opt-plist :text))
23584 "\n"))
23585 thetoc have-headings first-heading-pos
23586 table-open table-buffer)
23588 (let ((inhibit-read-only t))
23589 (org-unmodified
23590 (remove-text-properties (point-min) (point-max)
23591 '(:org-license-to-kill t))))
23593 (setq org-min-level (org-get-min-level lines))
23594 (setq org-last-level org-min-level)
23595 (org-init-section-numbers)
23597 (find-file-noselect filename)
23599 (setq lang-words (or (assoc language org-export-language-setup)
23600 (assoc "en" org-export-language-setup)))
23601 (switch-to-buffer-other-window buffer)
23602 (erase-buffer)
23603 (fundamental-mode)
23604 ;; create local variables for all options, to make sure all called
23605 ;; functions get the correct information
23606 (mapc (lambda (x)
23607 (set (make-local-variable (cdr x))
23608 (plist-get opt-plist (car x))))
23609 org-export-plist-vars)
23610 (org-set-local 'org-odd-levels-only odd)
23611 (setq umax (if arg (prefix-numeric-value arg)
23612 org-export-headline-levels))
23613 (setq umax-toc (if (integerp org-export-with-toc)
23614 (min org-export-with-toc umax)
23615 umax))
23617 ;; File header
23618 (if title (org-insert-centered title ?=))
23619 (insert "\n")
23620 (if (and (or author email)
23621 org-export-author-info)
23622 (insert (concat (nth 1 lang-words) ": " (or author "")
23623 (if email (concat " <" email ">") "")
23624 "\n")))
23626 (cond
23627 ((and date (string-match "%" date))
23628 (setq date (format-time-string date (current-time))))
23629 (date)
23630 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23632 (if (and date org-export-time-stamp-file)
23633 (insert (concat (nth 2 lang-words) ": " date"\n")))
23635 (insert "\n\n")
23637 (if org-export-with-toc
23638 (progn
23639 (push (concat (nth 3 lang-words) "\n") thetoc)
23640 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
23641 (mapc '(lambda (line)
23642 (if (string-match org-todo-line-regexp
23643 line)
23644 ;; This is a headline
23645 (progn
23646 (setq have-headings t)
23647 (setq level (- (match-end 1) (match-beginning 1))
23648 level (org-tr-level level)
23649 txt (match-string 3 line)
23650 todo
23651 (or (and org-export-mark-todo-in-toc
23652 (match-beginning 2)
23653 (not (member (match-string 2 line)
23654 org-done-keywords)))
23655 ; TODO, not DONE
23656 (and org-export-mark-todo-in-toc
23657 (= level umax-toc)
23658 (org-search-todo-below
23659 line lines level))))
23660 (setq txt (org-html-expand-for-ascii txt))
23662 (while (string-match org-bracket-link-regexp txt)
23663 (setq txt
23664 (replace-match
23665 (match-string (if (match-end 2) 3 1) txt)
23666 t t txt)))
23668 (if (and (memq org-export-with-tags '(not-in-toc nil))
23669 (string-match
23670 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
23671 txt))
23672 (setq txt (replace-match "" t t txt)))
23673 (if (string-match quote-re0 txt)
23674 (setq txt (replace-match "" t t txt)))
23676 (if org-export-with-section-numbers
23677 (setq txt (concat (org-section-number level)
23678 " " txt)))
23679 (if (<= level umax-toc)
23680 (progn
23681 (push
23682 (concat
23683 (make-string
23684 (* (max 0 (- level org-min-level)) 4) ?\ )
23685 (format (if todo "%s (*)\n" "%s\n") txt))
23686 thetoc)
23687 (setq org-last-level level))
23688 ))))
23689 lines)
23690 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23692 (org-init-section-numbers)
23693 (while (setq line (pop lines))
23694 ;; Remove the quoted HTML tags.
23695 (setq line (org-html-expand-for-ascii line))
23696 ;; Remove targets
23697 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
23698 (setq line (replace-match "" t t line)))
23699 ;; Replace internal links
23700 (while (string-match org-bracket-link-regexp line)
23701 (setq line (replace-match
23702 (if (match-end 3) "[\\3]" "[\\1]")
23703 t nil line)))
23704 (when custom-times
23705 (setq line (org-translate-time line)))
23706 (cond
23707 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23708 ;; a Headline
23709 (setq first-heading-pos (or first-heading-pos (point)))
23710 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23711 txt (match-string 2 line))
23712 (org-ascii-level-start level txt umax lines))
23714 ((and org-export-with-tables
23715 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23716 (if (not table-open)
23717 ;; New table starts
23718 (setq table-open t table-buffer nil))
23719 ;; Accumulate lines
23720 (setq table-buffer (cons line table-buffer))
23721 (when (or (not lines)
23722 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23723 (car lines))))
23724 (setq table-open nil
23725 table-buffer (nreverse table-buffer))
23726 (insert (mapconcat
23727 (lambda (x)
23728 (org-fix-indentation x org-ascii-current-indentation))
23729 (org-format-table-ascii table-buffer)
23730 "\n") "\n")))
23732 (setq line (org-fix-indentation line org-ascii-current-indentation))
23733 (if (and org-export-with-fixed-width
23734 (string-match "^\\([ \t]*\\)\\(:\\)" line))
23735 (setq line (replace-match "\\1" nil nil line)))
23736 (insert line "\n"))))
23738 (normal-mode)
23740 ;; insert the table of contents
23741 (when thetoc
23742 (goto-char (point-min))
23743 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
23744 (progn
23745 (goto-char (match-beginning 0))
23746 (replace-match ""))
23747 (goto-char first-heading-pos))
23748 (mapc 'insert thetoc)
23749 (or (looking-at "[ \t]*\n[ \t]*\n")
23750 (insert "\n\n")))
23752 ;; Convert whitespace place holders
23753 (goto-char (point-min))
23754 (let (beg end)
23755 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23756 (setq end (next-single-property-change beg 'org-whitespace))
23757 (goto-char beg)
23758 (delete-region beg end)
23759 (insert (make-string (- end beg) ?\ ))))
23761 (save-buffer)
23762 ;; remove display and invisible chars
23763 (let (beg end)
23764 (goto-char (point-min))
23765 (while (setq beg (next-single-property-change (point) 'display))
23766 (setq end (next-single-property-change beg 'display))
23767 (delete-region beg end)
23768 (goto-char beg)
23769 (insert "=>"))
23770 (goto-char (point-min))
23771 (while (setq beg (next-single-property-change (point) 'org-cwidth))
23772 (setq end (next-single-property-change beg 'org-cwidth))
23773 (delete-region beg end)
23774 (goto-char beg)))
23775 (goto-char (point-min))))
23777 (defun org-export-ascii-clean-string ()
23778 "Do extra work for ASCII export"
23779 (goto-char (point-min))
23780 (while (re-search-forward org-verbatim-re nil t)
23781 (goto-char (match-end 2))
23782 (backward-delete-char 1) (insert "'")
23783 (goto-char (match-beginning 2))
23784 (delete-char 1) (insert "`")
23785 (goto-char (match-end 2))))
23787 (defun org-search-todo-below (line lines level)
23788 "Search the subtree below LINE for any TODO entries."
23789 (let ((rest (cdr (memq line lines)))
23790 (re org-todo-line-regexp)
23791 line lv todo)
23792 (catch 'exit
23793 (while (setq line (pop rest))
23794 (if (string-match re line)
23795 (progn
23796 (setq lv (- (match-end 1) (match-beginning 1))
23797 todo (and (match-beginning 2)
23798 (not (member (match-string 2 line)
23799 org-done-keywords))))
23800 ; TODO, not DONE
23801 (if (<= lv level) (throw 'exit nil))
23802 (if todo (throw 'exit t))))))))
23804 (defun org-html-expand-for-ascii (line)
23805 "Handle quoted HTML for ASCII export."
23806 (if org-export-html-expand
23807 (while (string-match "@<[^<>\n]*>" line)
23808 ;; We just remove the tags for now.
23809 (setq line (replace-match "" nil nil line))))
23810 line)
23812 (defun org-insert-centered (s &optional underline)
23813 "Insert the string S centered and underline it with character UNDERLINE."
23814 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23815 (insert (make-string ind ?\ ) s "\n")
23816 (if underline
23817 (insert (make-string ind ?\ )
23818 (make-string (string-width s) underline)
23819 "\n"))))
23821 (defun org-ascii-level-start (level title umax &optional lines)
23822 "Insert a new level in ASCII export."
23823 (let (char (n (- level umax 1)) (ind 0))
23824 (if (> level umax)
23825 (progn
23826 (insert (make-string (* 2 n) ?\ )
23827 (char-to-string (nth (% n (length org-export-ascii-bullets))
23828 org-export-ascii-bullets))
23829 " " title "\n")
23830 ;; find the indentation of the next non-empty line
23831 (catch 'stop
23832 (while lines
23833 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23834 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23835 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23836 (pop lines)))
23837 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23838 (if (or (not (equal (char-before) ?\n))
23839 (not (equal (char-before (1- (point))) ?\n)))
23840 (insert "\n"))
23841 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23842 (unless org-export-with-tags
23843 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23844 (setq title (replace-match "" t t title))))
23845 (if org-export-with-section-numbers
23846 (setq title (concat (org-section-number level) " " title)))
23847 (insert title "\n" (make-string (string-width title) char) "\n")
23848 (setq org-ascii-current-indentation '(0 . 0)))))
23850 (defun org-export-visible (type arg)
23851 "Create a copy of the visible part of the current buffer, and export it.
23852 The copy is created in a temporary buffer and removed after use.
23853 TYPE is the final key (as a string) that also select the export command in
23854 the `C-c C-e' export dispatcher.
23855 As a special case, if the you type SPC at the prompt, the temporary
23856 org-mode file will not be removed but presented to you so that you can
23857 continue to use it. The prefix arg ARG is passed through to the exporting
23858 command."
23859 (interactive
23860 (list (progn
23861 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23862 (read-char-exclusive))
23863 current-prefix-arg))
23864 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23865 (error "Invalid export key"))
23866 (let* ((binding (cdr (assoc type
23867 '((?a . org-export-as-ascii)
23868 (?\C-a . org-export-as-ascii)
23869 (?b . org-export-as-html-and-open)
23870 (?\C-b . org-export-as-html-and-open)
23871 (?h . org-export-as-html)
23872 (?H . org-export-as-html-to-buffer)
23873 (?R . org-export-region-as-html)
23874 (?x . org-export-as-xoxo)))))
23875 (keepp (equal type ?\ ))
23876 (file buffer-file-name)
23877 (buffer (get-buffer-create "*Org Export Visible*"))
23878 s e)
23879 ;; Need to hack the drawers here.
23880 (save-excursion
23881 (goto-char (point-min))
23882 (while (re-search-forward org-drawer-regexp nil t)
23883 (goto-char (match-beginning 1))
23884 (or (org-invisible-p) (org-flag-drawer nil))))
23885 (with-current-buffer buffer (erase-buffer))
23886 (save-excursion
23887 (setq s (goto-char (point-min)))
23888 (while (not (= (point) (point-max)))
23889 (goto-char (org-find-invisible))
23890 (append-to-buffer buffer s (point))
23891 (setq s (goto-char (org-find-visible))))
23892 (org-cycle-hide-drawers 'all)
23893 (goto-char (point-min))
23894 (unless keepp
23895 ;; Copy all comment lines to the end, to make sure #+ settings are
23896 ;; still available for the second export step. Kind of a hack, but
23897 ;; does do the trick.
23898 (if (looking-at "#[^\r\n]*")
23899 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23900 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23901 (append-to-buffer buffer (1+ (match-beginning 0))
23902 (min (point-max) (1+ (match-end 0))))))
23903 (set-buffer buffer)
23904 (let ((buffer-file-name file)
23905 (org-inhibit-startup t))
23906 (org-mode)
23907 (show-all)
23908 (unless keepp (funcall binding arg))))
23909 (if (not keepp)
23910 (kill-buffer buffer)
23911 (switch-to-buffer-other-window buffer)
23912 (goto-char (point-min)))))
23914 (defun org-find-visible ()
23915 (let ((s (point)))
23916 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23917 (get-char-property s 'invisible)))
23919 (defun org-find-invisible ()
23920 (let ((s (point)))
23921 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23922 (not (get-char-property s 'invisible))))
23925 ;;; HTML export
23927 (defun org-get-current-options ()
23928 "Return a string with current options as keyword options.
23929 Does include HTML export options as well as TODO and CATEGORY stuff."
23930 (format
23931 "#+TITLE: %s
23932 #+AUTHOR: %s
23933 #+EMAIL: %s
23934 #+LANGUAGE: %s
23935 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23936 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s -:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
23937 #+CATEGORY: %s
23938 #+SEQ_TODO: %s
23939 #+TYP_TODO: %s
23940 #+PRIORITIES: %c %c %c
23941 #+DRAWERS: %s
23942 #+STARTUP: %s %s %s %s %s
23943 #+TAGS: %s
23944 #+ARCHIVE: %s
23945 #+LINK: %s
23947 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23948 org-export-headline-levels
23949 org-export-with-section-numbers
23950 org-export-with-toc
23951 org-export-preserve-breaks
23952 org-export-html-expand
23953 org-export-with-fixed-width
23954 org-export-with-tables
23955 org-export-with-sub-superscripts
23956 org-export-with-special-strings
23957 org-export-with-footnotes
23958 org-export-with-emphasize
23959 org-export-with-TeX-macros
23960 org-export-with-LaTeX-fragments
23961 org-export-skip-text-before-1st-heading
23962 org-export-with-drawers
23963 org-export-with-tags
23964 (file-name-nondirectory buffer-file-name)
23965 "TODO FEEDBACK VERIFY DONE"
23966 "Me Jason Marie DONE"
23967 org-highest-priority org-lowest-priority org-default-priority
23968 (mapconcat 'identity org-drawers " ")
23969 (cdr (assoc org-startup-folded
23970 '((nil . "showall") (t . "overview") (content . "content"))))
23971 (if org-odd-levels-only "odd" "oddeven")
23972 (if org-hide-leading-stars "hidestars" "showstars")
23973 (if org-startup-align-all-tables "align" "noalign")
23974 (cond ((eq t org-log-done) "logdone")
23975 ((not org-log-done) "nologging")
23976 ((listp org-log-done)
23977 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23978 org-log-done " ")))
23979 (or (mapconcat (lambda (x)
23980 (cond
23981 ((equal '(:startgroup) x) "{")
23982 ((equal '(:endgroup) x) "}")
23983 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23984 (t (car x))))
23985 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23986 org-archive-location
23987 "org file:~/org/%s.org"
23990 (defun org-insert-export-options-template ()
23991 "Insert into the buffer a template with information for exporting."
23992 (interactive)
23993 (if (not (bolp)) (newline))
23994 (let ((s (org-get-current-options)))
23995 (and (string-match "#\\+CATEGORY" s)
23996 (setq s (substring s 0 (match-beginning 0))))
23997 (insert s)))
23999 (defun org-toggle-fixed-width-section (arg)
24000 "Toggle the fixed-width export.
24001 If there is no active region, the QUOTE keyword at the current headline is
24002 inserted or removed. When present, it causes the text between this headline
24003 and the next to be exported as fixed-width text, and unmodified.
24004 If there is an active region, this command adds or removes a colon as the
24005 first character of this line. If the first character of a line is a colon,
24006 this line is also exported in fixed-width font."
24007 (interactive "P")
24008 (let* ((cc 0)
24009 (regionp (org-region-active-p))
24010 (beg (if regionp (region-beginning) (point)))
24011 (end (if regionp (region-end)))
24012 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24013 (case-fold-search nil)
24014 (re "[ \t]*\\(:\\)")
24015 off)
24016 (if regionp
24017 (save-excursion
24018 (goto-char beg)
24019 (setq cc (current-column))
24020 (beginning-of-line 1)
24021 (setq off (looking-at re))
24022 (while (> nlines 0)
24023 (setq nlines (1- nlines))
24024 (beginning-of-line 1)
24025 (cond
24026 (arg
24027 (move-to-column cc t)
24028 (insert ":\n")
24029 (forward-line -1))
24030 ((and off (looking-at re))
24031 (replace-match "" t t nil 1))
24032 ((not off) (move-to-column cc t) (insert ":")))
24033 (forward-line 1)))
24034 (save-excursion
24035 (org-back-to-heading)
24036 (if (looking-at (concat outline-regexp
24037 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24038 (replace-match "" t t nil 1)
24039 (if (looking-at outline-regexp)
24040 (progn
24041 (goto-char (match-end 0))
24042 (insert org-quote-string " "))))))))
24044 (defun org-export-as-html-and-open (arg)
24045 "Export the outline as HTML and immediately open it with a browser.
24046 If there is an active region, export only the region.
24047 The prefix ARG specifies how many levels of the outline should become
24048 headlines. The default is 3. Lower levels will become bulleted lists."
24049 (interactive "P")
24050 (org-export-as-html arg 'hidden)
24051 (org-open-file buffer-file-name))
24053 (defun org-export-as-html-batch ()
24054 "Call `org-export-as-html', may be used in batch processing as
24055 emacs --batch
24056 --load=$HOME/lib/emacs/org.el
24057 --eval \"(setq org-export-headline-levels 2)\"
24058 --visit=MyFile --funcall org-export-as-html-batch"
24059 (org-export-as-html org-export-headline-levels 'hidden))
24061 (defun org-export-as-html-to-buffer (arg)
24062 "Call `org-exort-as-html` with output to a temporary buffer.
24063 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24064 (interactive "P")
24065 (org-export-as-html arg nil nil "*Org HTML Export*")
24066 (switch-to-buffer-other-window "*Org HTML Export*"))
24068 (defun org-replace-region-by-html (beg end)
24069 "Assume the current region has org-mode syntax, and convert it to HTML.
24070 This can be used in any buffer. For example, you could write an
24071 itemized list in org-mode syntax in an HTML buffer and then use this
24072 command to convert it."
24073 (interactive "r")
24074 (let (reg html buf pop-up-frames)
24075 (save-window-excursion
24076 (if (org-mode-p)
24077 (setq html (org-export-region-as-html
24078 beg end t 'string))
24079 (setq reg (buffer-substring beg end)
24080 buf (get-buffer-create "*Org tmp*"))
24081 (with-current-buffer buf
24082 (erase-buffer)
24083 (insert reg)
24084 (org-mode)
24085 (setq html (org-export-region-as-html
24086 (point-min) (point-max) t 'string)))
24087 (kill-buffer buf)))
24088 (delete-region beg end)
24089 (insert html)))
24091 (defun org-export-region-as-html (beg end &optional body-only buffer)
24092 "Convert region from BEG to END in org-mode buffer to HTML.
24093 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24094 contents, and only produce the region of converted text, useful for
24095 cut-and-paste operations.
24096 If BUFFER is a buffer or a string, use/create that buffer as a target
24097 of the converted HTML. If BUFFER is the symbol `string', return the
24098 produced HTML as a string and leave not buffer behind. For example,
24099 a Lisp program could call this function in the following way:
24101 (setq html (org-export-region-as-html beg end t 'string))
24103 When called interactively, the output buffer is selected, and shown
24104 in a window. A non-interactive call will only retunr the buffer."
24105 (interactive "r\nP")
24106 (when (interactive-p)
24107 (setq buffer "*Org HTML Export*"))
24108 (let ((transient-mark-mode t) (zmacs-regions t)
24109 rtn)
24110 (goto-char end)
24111 (set-mark (point)) ;; to activate the region
24112 (goto-char beg)
24113 (setq rtn (org-export-as-html
24114 nil nil nil
24115 buffer body-only))
24116 (if (fboundp 'deactivate-mark) (deactivate-mark))
24117 (if (and (interactive-p) (bufferp rtn))
24118 (switch-to-buffer-other-window rtn)
24119 rtn)))
24121 (defvar html-table-tag nil) ; dynamically scoped into this.
24122 (defun org-export-as-html (arg &optional hidden ext-plist
24123 to-buffer body-only)
24124 "Export the outline as a pretty HTML file.
24125 If there is an active region, export only the region. The prefix
24126 ARG specifies how many levels of the outline should become
24127 headlines. The default is 3. Lower levels will become bulleted
24128 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24129 EXT-PLIST is a property list with external parameters overriding
24130 org-mode's default settings, but still inferior to file-local
24131 settings. When TO-BUFFER is non-nil, create a buffer with that
24132 name and export to that buffer. If TO-BUFFER is the symbol `string',
24133 don't leave any buffer behind but just return the resulting HTML as
24134 a string. When BODY-ONLY is set, don't produce the file header and footer,
24135 simply return the content of <body>...</body>, without even
24136 the body tags themselves."
24137 (interactive "P")
24139 ;; Make sure we have a file name when we need it.
24140 (when (and (not (or to-buffer body-only))
24141 (not buffer-file-name))
24142 (if (buffer-base-buffer)
24143 (org-set-local 'buffer-file-name
24144 (with-current-buffer (buffer-base-buffer)
24145 buffer-file-name))
24146 (error "Need a file name to be able to export.")))
24148 (message "Exporting...")
24149 (setq-default org-todo-line-regexp org-todo-line-regexp)
24150 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24151 (setq-default org-done-keywords org-done-keywords)
24152 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24153 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24154 ext-plist
24155 (org-infile-export-plist)))
24157 (style (plist-get opt-plist :style))
24158 (link-validate (plist-get opt-plist :link-validation-function))
24159 valid thetoc have-headings first-heading-pos
24160 (odd org-odd-levels-only)
24161 (region-p (org-region-active-p))
24162 (subtree-p
24163 (when region-p
24164 (save-excursion
24165 (goto-char (region-beginning))
24166 (and (org-at-heading-p)
24167 (>= (org-end-of-subtree t t) (region-end))))))
24168 ;; The following two are dynamically scoped into other
24169 ;; routines below.
24170 (org-current-export-dir (org-export-directory :html opt-plist))
24171 (org-current-export-file buffer-file-name)
24172 (level 0) (line "") (origline "") txt todo
24173 (umax nil)
24174 (umax-toc nil)
24175 (filename (if to-buffer nil
24176 (concat (file-name-as-directory
24177 (org-export-directory :html opt-plist))
24178 (file-name-sans-extension
24179 (or (and subtree-p
24180 (org-entry-get (region-beginning)
24181 "EXPORT_FILE_NAME" t))
24182 (file-name-nondirectory buffer-file-name)))
24183 "." org-export-html-extension)))
24184 (current-dir (if buffer-file-name
24185 (file-name-directory buffer-file-name)
24186 default-directory))
24187 (buffer (if to-buffer
24188 (cond
24189 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24190 (t (get-buffer-create to-buffer)))
24191 (find-file-noselect filename)))
24192 (org-levels-open (make-vector org-level-max nil))
24193 (date (plist-get opt-plist :date))
24194 (author (plist-get opt-plist :author))
24195 (title (or (and subtree-p (org-export-get-title-from-subtree))
24196 (plist-get opt-plist :title)
24197 (and (not
24198 (plist-get opt-plist :skip-before-1st-heading))
24199 (org-export-grab-title-from-buffer))
24200 (and buffer-file-name
24201 (file-name-sans-extension
24202 (file-name-nondirectory buffer-file-name)))
24203 "UNTITLED"))
24204 (html-table-tag (plist-get opt-plist :html-table-tag))
24205 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24206 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24207 (inquote nil)
24208 (infixed nil)
24209 (in-local-list nil)
24210 (local-list-num nil)
24211 (local-list-indent nil)
24212 (llt org-plain-list-ordered-item-terminator)
24213 (email (plist-get opt-plist :email))
24214 (language (plist-get opt-plist :language))
24215 (lang-words nil)
24216 (target-alist nil) tg
24217 (head-count 0) cnt
24218 (start 0)
24219 (coding-system (and (boundp 'buffer-file-coding-system)
24220 buffer-file-coding-system))
24221 (coding-system-for-write (or org-export-html-coding-system
24222 coding-system))
24223 (save-buffer-coding-system (or org-export-html-coding-system
24224 coding-system))
24225 (charset (and coding-system-for-write
24226 (fboundp 'coding-system-get)
24227 (coding-system-get coding-system-for-write
24228 'mime-charset)))
24229 (region
24230 (buffer-substring
24231 (if region-p (region-beginning) (point-min))
24232 (if region-p (region-end) (point-max))))
24233 (lines
24234 (org-split-string
24235 (org-cleaned-string-for-export
24236 region
24237 :emph-multiline t
24238 :for-html t
24239 :skip-before-1st-heading
24240 (plist-get opt-plist :skip-before-1st-heading)
24241 :drawers (plist-get opt-plist :drawers)
24242 :archived-trees
24243 (plist-get opt-plist :archived-trees)
24244 :add-text
24245 (plist-get opt-plist :text)
24246 :LaTeX-fragments
24247 (plist-get opt-plist :LaTeX-fragments))
24248 "[\r\n]"))
24249 table-open type
24250 table-buffer table-orig-buffer
24251 ind start-is-num starter didclose
24252 rpl path desc descp desc1 desc2 link
24255 (let ((inhibit-read-only t))
24256 (org-unmodified
24257 (remove-text-properties (point-min) (point-max)
24258 '(:org-license-to-kill t))))
24260 (message "Exporting...")
24262 (setq org-min-level (org-get-min-level lines))
24263 (setq org-last-level org-min-level)
24264 (org-init-section-numbers)
24266 (cond
24267 ((and date (string-match "%" date))
24268 (setq date (format-time-string date (current-time))))
24269 (date)
24270 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24272 ;; Get the language-dependent settings
24273 (setq lang-words (or (assoc language org-export-language-setup)
24274 (assoc "en" org-export-language-setup)))
24276 ;; Switch to the output buffer
24277 (set-buffer buffer)
24278 (erase-buffer)
24279 (fundamental-mode)
24281 (and (fboundp 'set-buffer-file-coding-system)
24282 (set-buffer-file-coding-system coding-system-for-write))
24284 (let ((case-fold-search nil)
24285 (org-odd-levels-only odd))
24286 ;; create local variables for all options, to make sure all called
24287 ;; functions get the correct information
24288 (mapc (lambda (x)
24289 (set (make-local-variable (cdr x))
24290 (plist-get opt-plist (car x))))
24291 org-export-plist-vars)
24292 (setq umax (if arg (prefix-numeric-value arg)
24293 org-export-headline-levels))
24294 (setq umax-toc (if (integerp org-export-with-toc)
24295 (min org-export-with-toc umax)
24296 umax))
24297 (unless body-only
24298 ;; File header
24299 (insert (format
24300 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24301 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24302 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24303 lang=\"%s\" xml:lang=\"%s\">
24304 <head>
24305 <title>%s</title>
24306 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24307 <meta name=\"generator\" content=\"Org-mode\"/>
24308 <meta name=\"generated\" content=\"%s\"/>
24309 <meta name=\"author\" content=\"%s\"/>
24311 </head><body>
24313 language language (org-html-expand title)
24314 (or charset "iso-8859-1") date author style))
24316 (insert (or (plist-get opt-plist :preamble) ""))
24318 (when (plist-get opt-plist :auto-preamble)
24319 (if title (insert (format org-export-html-title-format
24320 (org-html-expand title))))))
24322 (if (and org-export-with-toc (not body-only))
24323 (progn
24324 (push (format "<h%d>%s</h%d>\n"
24325 org-export-html-toplevel-hlevel
24326 (nth 3 lang-words)
24327 org-export-html-toplevel-hlevel)
24328 thetoc)
24329 (push "<ul>\n<li>" thetoc)
24330 (setq lines
24331 (mapcar '(lambda (line)
24332 (if (string-match org-todo-line-regexp line)
24333 ;; This is a headline
24334 (progn
24335 (setq have-headings t)
24336 (setq level (- (match-end 1) (match-beginning 1))
24337 level (org-tr-level level)
24338 txt (save-match-data
24339 (org-html-expand
24340 (org-export-cleanup-toc-line
24341 (match-string 3 line))))
24342 todo
24343 (or (and org-export-mark-todo-in-toc
24344 (match-beginning 2)
24345 (not (member (match-string 2 line)
24346 org-done-keywords)))
24347 ; TODO, not DONE
24348 (and org-export-mark-todo-in-toc
24349 (= level umax-toc)
24350 (org-search-todo-below
24351 line lines level))))
24352 (if (string-match
24353 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24354 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24355 (if (string-match quote-re0 txt)
24356 (setq txt (replace-match "" t t txt)))
24357 (if org-export-with-section-numbers
24358 (setq txt (concat (org-section-number level)
24359 " " txt)))
24360 (if (<= level (max umax umax-toc))
24361 (setq head-count (+ head-count 1)))
24362 (if (<= level umax-toc)
24363 (progn
24364 (if (> level org-last-level)
24365 (progn
24366 (setq cnt (- level org-last-level))
24367 (while (>= (setq cnt (1- cnt)) 0)
24368 (push "\n<ul>\n<li>" thetoc))
24369 (push "\n" thetoc)))
24370 (if (< level org-last-level)
24371 (progn
24372 (setq cnt (- org-last-level level))
24373 (while (>= (setq cnt (1- cnt)) 0)
24374 (push "</li>\n</ul>" thetoc))
24375 (push "\n" thetoc)))
24376 ;; Check for targets
24377 (while (string-match org-target-regexp line)
24378 (setq tg (match-string 1 line)
24379 line (replace-match
24380 (concat "@<span class=\"target\">" tg "@</span> ")
24381 t t line))
24382 (push (cons (org-solidify-link-text tg)
24383 (format "sec-%d" head-count))
24384 target-alist))
24385 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24386 (setq txt (replace-match "" t t txt)))
24387 (push
24388 (format
24389 (if todo
24390 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24391 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24392 head-count txt) thetoc)
24394 (setq org-last-level level))
24396 line)
24397 lines))
24398 (while (> org-last-level (1- org-min-level))
24399 (setq org-last-level (1- org-last-level))
24400 (push "</li>\n</ul>\n" thetoc))
24401 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24403 (setq head-count 0)
24404 (org-init-section-numbers)
24406 (while (setq line (pop lines) origline line)
24407 (catch 'nextline
24409 ;; end of quote section?
24410 (when (and inquote (string-match "^\\*+ " line))
24411 (insert "</pre>\n")
24412 (setq inquote nil))
24413 ;; inside a quote section?
24414 (when inquote
24415 (insert (org-html-protect line) "\n")
24416 (throw 'nextline nil))
24418 ;; verbatim lines
24419 (when (and org-export-with-fixed-width
24420 (string-match "^[ \t]*:\\(.*\\)" line))
24421 (when (not infixed)
24422 (setq infixed t)
24423 (insert "<pre>\n"))
24424 (insert (org-html-protect (match-string 1 line)) "\n")
24425 (when (and lines
24426 (not (string-match "^[ \t]*\\(:.*\\)"
24427 (car lines))))
24428 (setq infixed nil)
24429 (insert "</pre>\n"))
24430 (throw 'nextline nil))
24432 ;; Protected HTML
24433 (when (get-text-property 0 'org-protected line)
24434 (let (par)
24435 (when (re-search-backward
24436 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24437 (setq par (match-string 1))
24438 (replace-match "\\2\n"))
24439 (insert line "\n")
24440 (while (and lines
24441 (get-text-property 0 'org-protected (car lines)))
24442 (insert (pop lines) "\n"))
24443 (and par (insert "<p>\n")))
24444 (throw 'nextline nil))
24446 ;; Horizontal line
24447 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24448 (insert "\n<hr/>\n")
24449 (throw 'nextline nil))
24451 ;; make targets to anchors
24452 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24453 (cond
24454 ((match-end 2)
24455 (setq line (replace-match
24456 (concat "@<a name=\""
24457 (org-solidify-link-text (match-string 1 line))
24458 "\">\\nbsp@</a>")
24459 t t line)))
24460 ((and org-export-with-toc (equal (string-to-char line) ?*))
24461 (setq line (replace-match
24462 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24463 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24464 t t line)))
24466 (setq line (replace-match
24467 (concat "@<a name=\""
24468 (org-solidify-link-text (match-string 1 line))
24469 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24470 t t line)))))
24472 (setq line (org-html-handle-time-stamps line))
24474 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24475 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24476 ;; Also handle sub_superscripts and checkboxes
24477 (or (string-match org-table-hline-regexp line)
24478 (setq line (org-html-expand line)))
24480 ;; Format the links
24481 (setq start 0)
24482 (while (string-match org-bracket-link-analytic-regexp line start)
24483 (setq start (match-beginning 0))
24484 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24485 (setq path (match-string 3 line))
24486 (setq desc1 (if (match-end 5) (match-string 5 line))
24487 desc2 (if (match-end 2) (concat type ":" path) path)
24488 descp (and desc1 (not (equal desc1 desc2)))
24489 desc (or desc1 desc2))
24490 ;; Make an image out of the description if that is so wanted
24491 (when (and descp (org-file-image-p desc))
24492 (save-match-data
24493 (if (string-match "^file:" desc)
24494 (setq desc (substring desc (match-end 0)))))
24495 (setq desc (concat "<img src=\"" desc "\"/>")))
24496 ;; FIXME: do we need to unescape here somewhere?
24497 (cond
24498 ((equal type "internal")
24499 (setq rpl
24500 (concat
24501 "<a href=\"#"
24502 (org-solidify-link-text
24503 (save-match-data (org-link-unescape path)) target-alist)
24504 "\">" desc "</a>")))
24505 ((member type '("http" "https"))
24506 ;; standard URL, just check if we need to inline an image
24507 (if (and (or (eq t org-export-html-inline-images)
24508 (and org-export-html-inline-images (not descp)))
24509 (org-file-image-p path))
24510 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24511 (setq link (concat type ":" path))
24512 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24513 ((member type '("ftp" "mailto" "news"))
24514 ;; standard URL
24515 (setq link (concat type ":" path))
24516 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24517 ((string= type "file")
24518 ;; FILE link
24519 (let* ((filename path)
24520 (abs-p (file-name-absolute-p filename))
24521 thefile file-is-image-p search)
24522 (save-match-data
24523 (if (string-match "::\\(.*\\)" filename)
24524 (setq search (match-string 1 filename)
24525 filename (replace-match "" t nil filename)))
24526 (setq valid
24527 (if (functionp link-validate)
24528 (funcall link-validate filename current-dir)
24530 (setq file-is-image-p (org-file-image-p filename))
24531 (setq thefile (if abs-p (expand-file-name filename) filename))
24532 (when (and org-export-html-link-org-files-as-html
24533 (string-match "\\.org$" thefile))
24534 (setq thefile (concat (substring thefile 0
24535 (match-beginning 0))
24536 "." org-export-html-extension))
24537 (if (and search
24538 ;; make sure this is can be used as target search
24539 (not (string-match "^[0-9]*$" search))
24540 (not (string-match "^\\*" search))
24541 (not (string-match "^/.*/$" search)))
24542 (setq thefile (concat thefile "#"
24543 (org-solidify-link-text
24544 (org-link-unescape search)))))
24545 (when (string-match "^file:" desc)
24546 (setq desc (replace-match "" t t desc))
24547 (if (string-match "\\.org$" desc)
24548 (setq desc (replace-match "" t t desc))))))
24549 (setq rpl (if (and file-is-image-p
24550 (or (eq t org-export-html-inline-images)
24551 (and org-export-html-inline-images
24552 (not descp))))
24553 (concat "<img src=\"" thefile "\"/>")
24554 (concat "<a href=\"" thefile "\">" desc "</a>")))
24555 (if (not valid) (setq rpl desc))))
24556 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24557 (setq rpl (concat "<i>&lt;" type ":"
24558 (save-match-data (org-link-unescape path))
24559 "&gt;</i>"))))
24560 (setq line (replace-match rpl t t line)
24561 start (+ start (length rpl))))
24563 ;; TODO items
24564 (if (and (string-match org-todo-line-regexp line)
24565 (match-beginning 2))
24567 (setq line
24568 (concat (substring line 0 (match-beginning 2))
24569 "<span class=\""
24570 (if (member (match-string 2 line)
24571 org-done-keywords)
24572 "done" "todo")
24573 "\">" (match-string 2 line)
24574 "</span>" (substring line (match-end 2)))))
24576 ;; Does this contain a reference to a footnote?
24577 (when org-export-with-footnotes
24578 (setq start 0)
24579 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24580 (if (get-text-property (match-beginning 2) 'org-protected line)
24581 (setq start (match-end 2))
24582 (let ((n (match-string 2 line)))
24583 (setq line
24584 (replace-match
24585 (format
24586 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
24587 (match-string 1 line) n n n)
24588 t t line))))))
24590 (cond
24591 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24592 ;; This is a headline
24593 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24594 txt (match-string 2 line))
24595 (if (string-match quote-re0 txt)
24596 (setq txt (replace-match "" t t txt)))
24597 (if (<= level (max umax umax-toc))
24598 (setq head-count (+ head-count 1)))
24599 (when in-local-list
24600 ;; Close any local lists before inserting a new header line
24601 (while local-list-num
24602 (org-close-li)
24603 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24604 (pop local-list-num))
24605 (setq local-list-indent nil
24606 in-local-list nil))
24607 (setq first-heading-pos (or first-heading-pos (point)))
24608 (org-html-level-start level txt umax
24609 (and org-export-with-toc (<= level umax))
24610 head-count)
24611 ;; QUOTES
24612 (when (string-match quote-re line)
24613 (insert "<pre>")
24614 (setq inquote t)))
24616 ((and org-export-with-tables
24617 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24618 (if (not table-open)
24619 ;; New table starts
24620 (setq table-open t table-buffer nil table-orig-buffer nil))
24621 ;; Accumulate lines
24622 (setq table-buffer (cons line table-buffer)
24623 table-orig-buffer (cons origline table-orig-buffer))
24624 (when (or (not lines)
24625 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24626 (car lines))))
24627 (setq table-open nil
24628 table-buffer (nreverse table-buffer)
24629 table-orig-buffer (nreverse table-orig-buffer))
24630 (org-close-par-maybe)
24631 (insert (org-format-table-html table-buffer table-orig-buffer))))
24633 ;; Normal lines
24634 (when (string-match
24635 (cond
24636 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24637 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24638 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24639 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
24640 line)
24641 (setq ind (org-get-string-indentation line)
24642 start-is-num (match-beginning 4)
24643 starter (if (match-beginning 2)
24644 (substring (match-string 2 line) 0 -1))
24645 line (substring line (match-beginning 5)))
24646 (unless (string-match "[^ \t]" line)
24647 ;; empty line. Pretend indentation is large.
24648 (setq ind (if org-empty-line-terminates-plain-lists
24650 (1+ (or (car local-list-indent) 1)))))
24651 (setq didclose nil)
24652 (while (and in-local-list
24653 (or (and (= ind (car local-list-indent))
24654 (not starter))
24655 (< ind (car local-list-indent))))
24656 (setq didclose t)
24657 (org-close-li)
24658 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24659 (pop local-list-num) (pop local-list-indent)
24660 (setq in-local-list local-list-indent))
24661 (cond
24662 ((and starter
24663 (or (not in-local-list)
24664 (> ind (car local-list-indent))))
24665 ;; Start new (level of) list
24666 (org-close-par-maybe)
24667 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
24668 (push start-is-num local-list-num)
24669 (push ind local-list-indent)
24670 (setq in-local-list t))
24671 (starter
24672 ;; continue current list
24673 (org-close-li)
24674 (insert "<li>\n"))
24675 (didclose
24676 ;; we did close a list, normal text follows: need <p>
24677 (org-open-par)))
24678 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
24679 (setq line
24680 (replace-match
24681 (if (equal (match-string 1 line) "X")
24682 "<b>[X]</b>"
24683 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
24684 t t line))))
24686 ;; Empty lines start a new paragraph. If hand-formatted lists
24687 ;; are not fully interpreted, lines starting with "-", "+", "*"
24688 ;; also start a new paragraph.
24689 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
24691 ;; Is this the start of a footnote?
24692 (when org-export-with-footnotes
24693 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
24694 (org-close-par-maybe)
24695 (let ((n (match-string 1 line)))
24696 (setq line (replace-match
24697 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
24699 ;; Check if the line break needs to be conserved
24700 (cond
24701 ((string-match "\\\\\\\\[ \t]*$" line)
24702 (setq line (replace-match "<br/>" t t line)))
24703 (org-export-preserve-breaks
24704 (setq line (concat line "<br/>"))))
24706 (insert line "\n")))))
24708 ;; Properly close all local lists and other lists
24709 (when inquote (insert "</pre>\n"))
24710 (when in-local-list
24711 ;; Close any local lists before inserting a new header line
24712 (while local-list-num
24713 (org-close-li)
24714 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
24715 (pop local-list-num))
24716 (setq local-list-indent nil
24717 in-local-list nil))
24718 (org-html-level-start 1 nil umax
24719 (and org-export-with-toc (<= level umax))
24720 head-count)
24722 (unless body-only
24723 (when (plist-get opt-plist :auto-postamble)
24724 (insert "<div id=\"postamble\">")
24725 (when (and org-export-author-info author)
24726 (insert "<p class=\"author\"> "
24727 (nth 1 lang-words) ": " author "\n")
24728 (when email
24729 (if (listp (split-string email ",+ *"))
24730 (mapc (lambda(e)
24731 (insert "<a href=\"mailto:" e "\">&lt;"
24732 e "&gt;</a>\n"))
24733 (split-string email ",+ *"))
24734 (insert "<a href=\"mailto:" email "\">&lt;"
24735 email "&gt;</a>\n")))
24736 (insert "</p>\n"))
24737 (when (and date org-export-time-stamp-file)
24738 (insert "<p class=\"date\"> "
24739 (nth 2 lang-words) ": "
24740 date "</p>\n"))
24741 (insert "</div>"))
24743 (if org-export-html-with-timestamp
24744 (insert org-export-html-html-helper-timestamp))
24745 (insert (or (plist-get opt-plist :postamble) ""))
24746 (insert "</body>\n</html>\n"))
24748 (normal-mode)
24749 (if (eq major-mode default-major-mode) (html-mode))
24751 ;; insert the table of contents
24752 (goto-char (point-min))
24753 (when thetoc
24754 (if (or (re-search-forward
24755 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
24756 (re-search-forward
24757 "\\[TABLE-OF-CONTENTS\\]" nil t))
24758 (progn
24759 (goto-char (match-beginning 0))
24760 (replace-match ""))
24761 (goto-char first-heading-pos)
24762 (when (looking-at "\\s-*</p>")
24763 (goto-char (match-end 0))
24764 (insert "\n")))
24765 (insert "<div id=\"table-of-contents\">\n")
24766 (mapc 'insert thetoc)
24767 (insert "</div>\n"))
24768 ;; remove empty paragraphs and lists
24769 (goto-char (point-min))
24770 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
24771 (replace-match ""))
24772 (goto-char (point-min))
24773 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
24774 (replace-match ""))
24775 ;; Convert whitespace place holders
24776 (goto-char (point-min))
24777 (let (beg end n)
24778 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24779 (setq n (get-text-property beg 'org-whitespace)
24780 end (next-single-property-change beg 'org-whitespace))
24781 (goto-char beg)
24782 (delete-region beg end)
24783 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
24784 (make-string n ?x)))))
24786 (or to-buffer (save-buffer))
24787 (goto-char (point-min))
24788 (message "Exporting... done")
24789 (if (eq to-buffer 'string)
24790 (prog1 (buffer-substring (point-min) (point-max))
24791 (kill-buffer (current-buffer)))
24792 (current-buffer)))))
24794 (defvar org-table-colgroup-info nil)
24795 (defun org-format-table-ascii (lines)
24796 "Format a table for ascii export."
24797 (if (stringp lines)
24798 (setq lines (org-split-string lines "\n")))
24799 (if (not (string-match "^[ \t]*|" (car lines)))
24800 ;; Table made by table.el - test for spanning
24801 lines
24803 ;; A normal org table
24804 ;; Get rid of hlines at beginning and end
24805 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24806 (setq lines (nreverse lines))
24807 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24808 (setq lines (nreverse lines))
24809 (when org-export-table-remove-special-lines
24810 ;; Check if the table has a marking column. If yes remove the
24811 ;; column and the special lines
24812 (setq lines (org-table-clean-before-export lines)))
24813 ;; Get rid of the vertical lines except for grouping
24814 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24815 rtn line vl1 start)
24816 (while (setq line (pop lines))
24817 (if (string-match org-table-hline-regexp line)
24818 (and (string-match "|\\(.*\\)|" line)
24819 (setq line (replace-match " \\1" t nil line)))
24820 (setq start 0 vl1 vl)
24821 (while (string-match "|" line start)
24822 (setq start (match-end 0))
24823 (or (pop vl1) (setq line (replace-match " " t t line)))))
24824 (push line rtn))
24825 (nreverse rtn))))
24827 (defun org-colgroup-info-to-vline-list (info)
24828 (let (vl new last)
24829 (while info
24830 (setq last new new (pop info))
24831 (if (or (memq last '(:end :startend))
24832 (memq new '(:start :startend)))
24833 (push t vl)
24834 (push nil vl)))
24835 (setq vl (nreverse vl))
24836 (and vl (setcar vl nil))
24837 vl))
24839 (defun org-format-table-html (lines olines)
24840 "Find out which HTML converter to use and return the HTML code."
24841 (if (stringp lines)
24842 (setq lines (org-split-string lines "\n")))
24843 (if (string-match "^[ \t]*|" (car lines))
24844 ;; A normal org table
24845 (org-format-org-table-html lines)
24846 ;; Table made by table.el - test for spanning
24847 (let* ((hlines (delq nil (mapcar
24848 (lambda (x)
24849 (if (string-match "^[ \t]*\\+-" x) x
24850 nil))
24851 lines)))
24852 (first (car hlines))
24853 (ll (and (string-match "\\S-+" first)
24854 (match-string 0 first)))
24855 (re (concat "^[ \t]*" (regexp-quote ll)))
24856 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24857 hlines))))
24858 (if (and (not spanning)
24859 (not org-export-prefer-native-exporter-for-tables))
24860 ;; We can use my own converter with HTML conversions
24861 (org-format-table-table-html lines)
24862 ;; Need to use the code generator in table.el, with the original text.
24863 (org-format-table-table-html-using-table-generate-source olines)))))
24865 (defun org-format-org-table-html (lines &optional splice)
24866 "Format a table into HTML."
24867 ;; Get rid of hlines at beginning and end
24868 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24869 (setq lines (nreverse lines))
24870 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24871 (setq lines (nreverse lines))
24872 (when org-export-table-remove-special-lines
24873 ;; Check if the table has a marking column. If yes remove the
24874 ;; column and the special lines
24875 (setq lines (org-table-clean-before-export lines)))
24877 (let ((head (and org-export-highlight-first-table-line
24878 (delq nil (mapcar
24879 (lambda (x) (string-match "^[ \t]*|-" x))
24880 (cdr lines)))))
24881 (nlines 0) fnum i
24882 tbopen line fields html gr colgropen)
24883 (if splice (setq head nil))
24884 (unless splice (push (if head "<thead>" "<tbody>") html))
24885 (setq tbopen t)
24886 (while (setq line (pop lines))
24887 (catch 'next-line
24888 (if (string-match "^[ \t]*|-" line)
24889 (progn
24890 (unless splice
24891 (push (if head "</thead>" "</tbody>") html)
24892 (if lines (push "<tbody>" html) (setq tbopen nil)))
24893 (setq head nil) ;; head ends here, first time around
24894 ;; ignore this line
24895 (throw 'next-line t)))
24896 ;; Break the line into fields
24897 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24898 (unless fnum (setq fnum (make-vector (length fields) 0)))
24899 (setq nlines (1+ nlines) i -1)
24900 (push (concat "<tr>"
24901 (mapconcat
24902 (lambda (x)
24903 (setq i (1+ i))
24904 (if (and (< i nlines)
24905 (string-match org-table-number-regexp x))
24906 (incf (aref fnum i)))
24907 (if head
24908 (concat (car org-export-table-header-tags) x
24909 (cdr org-export-table-header-tags))
24910 (concat (car org-export-table-data-tags) x
24911 (cdr org-export-table-data-tags))))
24912 fields "")
24913 "</tr>")
24914 html)))
24915 (unless splice (if tbopen (push "</tbody>" html)))
24916 (unless splice (push "</table>\n" html))
24917 (setq html (nreverse html))
24918 (unless splice
24919 ;; Put in col tags with the alignment (unfortuntely often ignored...)
24920 (push (mapconcat
24921 (lambda (x)
24922 (setq gr (pop org-table-colgroup-info))
24923 (format "%s<col align=\"%s\"></col>%s"
24924 (if (memq gr '(:start :startend))
24925 (prog1
24926 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24927 (setq colgropen t))
24929 (if (> (/ (float x) nlines) org-table-number-fraction)
24930 "right" "left")
24931 (if (memq gr '(:end :startend))
24932 (progn (setq colgropen nil) "</colgroup>")
24933 "")))
24934 fnum "")
24935 html)
24936 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24937 (push html-table-tag html))
24938 (concat (mapconcat 'identity html "\n") "\n")))
24940 (defun org-table-clean-before-export (lines)
24941 "Check if the table has a marking column.
24942 If yes remove the column and the special lines."
24943 (setq org-table-colgroup-info nil)
24944 (if (memq nil
24945 (mapcar
24946 (lambda (x) (or (string-match "^[ \t]*|-" x)
24947 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24948 lines))
24949 (progn
24950 (setq org-table-clean-did-remove-column nil)
24951 (delq nil
24952 (mapcar
24953 (lambda (x)
24954 (cond
24955 ((string-match "^[ \t]*| */ *|" x)
24956 (setq org-table-colgroup-info
24957 (mapcar (lambda (x)
24958 (cond ((member x '("<" "&lt;")) :start)
24959 ((member x '(">" "&gt;")) :end)
24960 ((member x '("<>" "&lt;&gt;")) :startend)
24961 (t nil)))
24962 (org-split-string x "[ \t]*|[ \t]*")))
24963 nil)
24964 (t x)))
24965 lines)))
24966 (setq org-table-clean-did-remove-column t)
24967 (delq nil
24968 (mapcar
24969 (lambda (x)
24970 (cond
24971 ((string-match "^[ \t]*| */ *|" x)
24972 (setq org-table-colgroup-info
24973 (mapcar (lambda (x)
24974 (cond ((member x '("<" "&lt;")) :start)
24975 ((member x '(">" "&gt;")) :end)
24976 ((member x '("<>" "&lt;&gt;")) :startend)
24977 (t nil)))
24978 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24979 nil)
24980 ((string-match "^[ \t]*| *[!_^/] *|" x)
24981 nil) ; ignore this line
24982 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24983 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24984 ;; remove the first column
24985 (replace-match "\\1|" t nil x))))
24986 lines))))
24988 (defun org-format-table-table-html (lines)
24989 "Format a table generated by table.el into HTML.
24990 This conversion does *not* use `table-generate-source' from table.el.
24991 This has the advantage that Org-mode's HTML conversions can be used.
24992 But it has the disadvantage, that no cell- or row-spanning is allowed."
24993 (let (line field-buffer
24994 (head org-export-highlight-first-table-line)
24995 fields html empty)
24996 (setq html (concat html-table-tag "\n"))
24997 (while (setq line (pop lines))
24998 (setq empty "&nbsp;")
24999 (catch 'next-line
25000 (if (string-match "^[ \t]*\\+-" line)
25001 (progn
25002 (if field-buffer
25003 (progn
25004 (setq
25005 html
25006 (concat
25007 html
25008 "<tr>"
25009 (mapconcat
25010 (lambda (x)
25011 (if (equal x "") (setq x empty))
25012 (if head
25013 (concat (car org-export-table-header-tags) x
25014 (cdr org-export-table-header-tags))
25015 (concat (car org-export-table-data-tags) x
25016 (cdr org-export-table-data-tags))))
25017 field-buffer "\n")
25018 "</tr>\n"))
25019 (setq head nil)
25020 (setq field-buffer nil)))
25021 ;; Ignore this line
25022 (throw 'next-line t)))
25023 ;; Break the line into fields and store the fields
25024 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25025 (if field-buffer
25026 (setq field-buffer (mapcar
25027 (lambda (x)
25028 (concat x "<br/>" (pop fields)))
25029 field-buffer))
25030 (setq field-buffer fields))))
25031 (setq html (concat html "</table>\n"))
25032 html))
25034 (defun org-format-table-table-html-using-table-generate-source (lines)
25035 "Format a table into html, using `table-generate-source' from table.el.
25036 This has the advantage that cell- or row-spanning is allowed.
25037 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25038 (require 'table)
25039 (with-current-buffer (get-buffer-create " org-tmp1 ")
25040 (erase-buffer)
25041 (insert (mapconcat 'identity lines "\n"))
25042 (goto-char (point-min))
25043 (if (not (re-search-forward "|[^+]" nil t))
25044 (error "Error processing table"))
25045 (table-recognize-table)
25046 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25047 (table-generate-source 'html " org-tmp2 ")
25048 (set-buffer " org-tmp2 ")
25049 (buffer-substring (point-min) (point-max))))
25051 (defun org-html-handle-time-stamps (s)
25052 "Format time stamps in string S, or remove them."
25053 (catch 'exit
25054 (let (r b)
25055 (while (string-match org-maybe-keyword-time-regexp s)
25056 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25057 ;; never export CLOCK
25058 (throw 'exit ""))
25059 (or b (setq b (substring s 0 (match-beginning 0))))
25060 (if (not org-export-with-timestamps)
25061 (setq r (concat r (substring s 0 (match-beginning 0)))
25062 s (substring s (match-end 0)))
25063 (setq r (concat
25064 r (substring s 0 (match-beginning 0))
25065 (if (match-end 1)
25066 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25067 (match-string 1 s)))
25068 (format " @<span class=\"timestamp\">%s@</span>"
25069 (substring
25070 (org-translate-time (match-string 3 s)) 1 -1)))
25071 s (substring s (match-end 0)))))
25072 ;; Line break if line started and ended with time stamp stuff
25073 (if (not r)
25075 (setq r (concat r s))
25076 (unless (string-match "\\S-" (concat b s))
25077 (setq r (concat r "@<br/>")))
25078 r))))
25080 (defun org-html-protect (s)
25081 ;; convert & to &amp;, < to &lt; and > to &gt;
25082 (let ((start 0))
25083 (while (string-match "&" s start)
25084 (setq s (replace-match "&amp;" t t s)
25085 start (1+ (match-beginning 0))))
25086 (while (string-match "<" s)
25087 (setq s (replace-match "&lt;" t t s)))
25088 (while (string-match ">" s)
25089 (setq s (replace-match "&gt;" t t s))))
25092 (defun org-export-cleanup-toc-line (s)
25093 "Remove tags and time staps from lines going into the toc."
25094 (when (memq org-export-with-tags '(not-in-toc nil))
25095 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25096 (setq s (replace-match "" t t s))))
25097 (when org-export-remove-timestamps-from-toc
25098 (while (string-match org-maybe-keyword-time-regexp s)
25099 (setq s (replace-match "" t t s))))
25100 (while (string-match org-bracket-link-regexp s)
25101 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25102 t t s)))
25105 (defun org-html-expand (string)
25106 "Prepare STRING for HTML export. Applies all active conversions.
25107 If there are links in the string, don't modify these."
25108 (let* ((re (concat org-bracket-link-regexp "\\|"
25109 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25110 m s l res)
25111 (while (setq m (string-match re string))
25112 (setq s (substring string 0 m)
25113 l (match-string 0 string)
25114 string (substring string (match-end 0)))
25115 (push (org-html-do-expand s) res)
25116 (push l res))
25117 (push (org-html-do-expand string) res)
25118 (apply 'concat (nreverse res))))
25120 (defun org-html-do-expand (s)
25121 "Apply all active conversions to translate special ASCII to HTML."
25122 (setq s (org-html-protect s))
25123 (if org-export-html-expand
25124 (let ((start 0))
25125 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25126 (setq s (replace-match "<\\1>" t nil s)))))
25127 (if org-export-with-emphasize
25128 (setq s (org-export-html-convert-emphasize s)))
25129 (if org-export-with-special-strings
25130 (setq s (org-export-html-convert-special-strings s)))
25131 (if org-export-with-sub-superscripts
25132 (setq s (org-export-html-convert-sub-super s)))
25133 (if org-export-with-TeX-macros
25134 (let ((start 0) wd ass)
25135 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25136 (if (get-text-property (match-beginning 0) 'org-protected s)
25137 (setq start (match-end 0))
25138 (setq wd (match-string 1 s))
25139 (if (setq ass (assoc wd org-html-entities))
25140 (setq s (replace-match (or (cdr ass)
25141 (concat "&" (car ass) ";"))
25142 t t s))
25143 (setq start (+ start (length wd))))))))
25146 (defun org-create-multibrace-regexp (left right n)
25147 "Create a regular expression which will match a balanced sexp.
25148 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25149 as single character strings.
25150 The regexp returned will match the entire expression including the
25151 delimiters. It will also define a single group which contains the
25152 match except for the outermost delimiters. The maximum depth of
25153 stacked delimiters is N. Escaping delimiters is not possible."
25154 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25155 (or "\\|")
25156 (re nothing)
25157 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25158 (while (> n 1)
25159 (setq n (1- n)
25160 re (concat re or next)
25161 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25162 (concat left "\\(" re "\\)" right)))
25164 (defvar org-match-substring-regexp
25165 (concat
25166 "\\([^\\]\\)\\([_^]\\)\\("
25167 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25168 "\\|"
25169 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25170 "\\|"
25171 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25172 "The regular expression matching a sub- or superscript.")
25174 (defvar org-match-substring-with-braces-regexp
25175 (concat
25176 "\\([^\\]\\)\\([_^]\\)\\("
25177 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25178 "\\)")
25179 "The regular expression matching a sub- or superscript, forcing braces.")
25181 (defconst org-export-html-special-string-regexps
25182 '(("\\\\-" . "&shy;")
25183 ("---\\([^-]\\)" . "&mdash;\\1")
25184 ("--\\([^-]\\)" . "&ndash;\\1")
25185 ("\\.\\.\\." . "&hellip;"))
25186 "Regular expressions for special string conversion.")
25188 (defun org-export-html-convert-special-strings (string)
25189 "Convert special characters in STRING to HTML."
25190 (let ((all org-export-html-special-string-regexps)
25191 e a re rpl start)
25192 (while (setq a (pop all))
25193 (setq re (car a) rpl (cdr a) start 0)
25194 (while (string-match re string start)
25195 (if (get-text-property (match-beginning 0) 'org-protected string)
25196 (setq start (match-end 0))
25197 (setq string (replace-match rpl t nil string)))))
25198 string))
25200 (defun org-export-html-convert-sub-super (string)
25201 "Convert sub- and superscripts in STRING to HTML."
25202 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25203 (while (string-match org-match-substring-regexp string s)
25204 (cond
25205 ((and requireb (match-end 8)) (setq s (match-end 2)))
25206 ((get-text-property (match-beginning 2) 'org-protected string)
25207 (setq s (match-end 2)))
25209 (setq s (match-end 1)
25210 key (if (string= (match-string 2 string) "_") "sub" "sup")
25211 c (or (match-string 8 string)
25212 (match-string 6 string)
25213 (match-string 5 string))
25214 string (replace-match
25215 (concat (match-string 1 string)
25216 "<" key ">" c "</" key ">")
25217 t t string)))))
25218 (while (string-match "\\\\\\([_^]\\)" string)
25219 (setq string (replace-match (match-string 1 string) t t string)))
25220 string))
25222 (defun org-export-html-convert-emphasize (string)
25223 "Apply emphasis."
25224 (let ((s 0) rpl)
25225 (while (string-match org-emph-re string s)
25226 (if (not (equal
25227 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25228 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25229 (setq s (match-beginning 0)
25231 (concat
25232 (match-string 1 string)
25233 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25234 (match-string 4 string)
25235 (nth 3 (assoc (match-string 3 string)
25236 org-emphasis-alist))
25237 (match-string 5 string))
25238 string (replace-match rpl t t string)
25239 s (+ s (- (length rpl) 2)))
25240 (setq s (1+ s))))
25241 string))
25243 (defvar org-par-open nil)
25244 (defun org-open-par ()
25245 "Insert <p>, but first close previous paragraph if any."
25246 (org-close-par-maybe)
25247 (insert "\n<p>")
25248 (setq org-par-open t))
25249 (defun org-close-par-maybe ()
25250 "Close paragraph if there is one open."
25251 (when org-par-open
25252 (insert "</p>")
25253 (setq org-par-open nil)))
25254 (defun org-close-li ()
25255 "Close <li> if necessary."
25256 (org-close-par-maybe)
25257 (insert "</li>\n"))
25259 (defvar body-only) ; dynamically scoped into this.
25260 (defun org-html-level-start (level title umax with-toc head-count)
25261 "Insert a new level in HTML export.
25262 When TITLE is nil, just close all open levels."
25263 (org-close-par-maybe)
25264 (let ((l org-level-max))
25265 (while (>= l level)
25266 (if (aref org-levels-open (1- l))
25267 (progn
25268 (org-html-level-close l umax)
25269 (aset org-levels-open (1- l) nil)))
25270 (setq l (1- l)))
25271 (when title
25272 ;; If title is nil, this means this function is called to close
25273 ;; all levels, so the rest is done only if title is given
25274 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25275 (setq title (replace-match
25276 (if org-export-with-tags
25277 (save-match-data
25278 (concat
25279 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25280 (mapconcat 'identity (org-split-string
25281 (match-string 1 title) ":")
25282 "&nbsp;")
25283 "</span>"))
25285 t t title)))
25286 (if (> level umax)
25287 (progn
25288 (if (aref org-levels-open (1- level))
25289 (progn
25290 (org-close-li)
25291 (insert "<li>" title "<br/>\n"))
25292 (aset org-levels-open (1- level) t)
25293 (org-close-par-maybe)
25294 (insert "<ul>\n<li>" title "<br/>\n")))
25295 (aset org-levels-open (1- level) t)
25296 (if (and org-export-with-section-numbers (not body-only))
25297 (setq title (concat (org-section-number level) " " title)))
25298 (setq level (+ level org-export-html-toplevel-hlevel -1))
25299 (if with-toc
25300 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25301 level level head-count title level))
25302 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25303 (org-open-par)))))
25305 (defun org-html-level-close (level max-outline-level)
25306 "Terminate one level in HTML export."
25307 (if (<= level max-outline-level)
25308 (insert "</div>\n")
25309 (org-close-li)
25310 (insert "</ul>\n")))
25312 ;;; iCalendar export
25314 ;;;###autoload
25315 (defun org-export-icalendar-this-file ()
25316 "Export current file as an iCalendar file.
25317 The iCalendar file will be located in the same directory as the Org-mode
25318 file, but with extension `.ics'."
25319 (interactive)
25320 (org-export-icalendar nil buffer-file-name))
25322 ;;;###autoload
25323 (defun org-export-icalendar-all-agenda-files ()
25324 "Export all files in `org-agenda-files' to iCalendar .ics files.
25325 Each iCalendar file will be located in the same directory as the Org-mode
25326 file, but with extension `.ics'."
25327 (interactive)
25328 (apply 'org-export-icalendar nil (org-agenda-files t)))
25330 ;;;###autoload
25331 (defun org-export-icalendar-combine-agenda-files ()
25332 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25333 The file is stored under the name `org-combined-agenda-icalendar-file'."
25334 (interactive)
25335 (apply 'org-export-icalendar t (org-agenda-files t)))
25337 (defun org-export-icalendar (combine &rest files)
25338 "Create iCalendar files for all elements of FILES.
25339 If COMBINE is non-nil, combine all calendar entries into a single large
25340 file and store it under the name `org-combined-agenda-icalendar-file'."
25341 (save-excursion
25342 (org-prepare-agenda-buffers files)
25343 (let* ((dir (org-export-directory
25344 :ical (list :publishing-directory
25345 org-export-publishing-directory)))
25346 file ical-file ical-buffer category started org-agenda-new-buffers)
25348 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25349 (when combine
25350 (setq ical-file
25351 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25352 org-combined-agenda-icalendar-file
25353 (expand-file-name org-combined-agenda-icalendar-file dir))
25354 ical-buffer (org-get-agenda-file-buffer ical-file))
25355 (set-buffer ical-buffer) (erase-buffer))
25356 (while (setq file (pop files))
25357 (catch 'nextfile
25358 (org-check-agenda-file file)
25359 (set-buffer (org-get-agenda-file-buffer file))
25360 (unless combine
25361 (setq ical-file (concat (file-name-as-directory dir)
25362 (file-name-sans-extension
25363 (file-name-nondirectory buffer-file-name))
25364 ".ics"))
25365 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25366 (with-current-buffer ical-buffer (erase-buffer)))
25367 (setq category (or org-category
25368 (file-name-sans-extension
25369 (file-name-nondirectory buffer-file-name))))
25370 (if (symbolp category) (setq category (symbol-name category)))
25371 (let ((standard-output ical-buffer))
25372 (if combine
25373 (and (not started) (setq started t)
25374 (org-start-icalendar-file org-icalendar-combined-name))
25375 (org-start-icalendar-file category))
25376 (org-print-icalendar-entries combine)
25377 (when (or (and combine (not files)) (not combine))
25378 (org-finish-icalendar-file)
25379 (set-buffer ical-buffer)
25380 (save-buffer)
25381 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25382 (org-release-buffers org-agenda-new-buffers))))
25384 (defvar org-after-save-iCalendar-file-hook nil
25385 "Hook run after an iCalendar file has been saved.
25386 The iCalendar buffer is still current when this hook is run.
25387 A good way to use this is to tell a desktop calenndar application to re-read
25388 the iCalendar file.")
25390 (defun org-print-icalendar-entries (&optional combine)
25391 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25392 When COMBINE is non nil, add the category to each line."
25393 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25394 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25395 (dts (org-ical-ts-to-string
25396 (format-time-string (cdr org-time-stamp-formats) (current-time))
25397 "DTSTART"))
25398 hd ts ts2 state status (inc t) pos b sexp rrule
25399 scheduledp deadlinep tmp pri category entry location summary desc
25400 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25401 (org-refresh-category-properties)
25402 (save-excursion
25403 (goto-char (point-min))
25404 (while (re-search-forward re1 nil t)
25405 (catch :skip
25406 (org-agenda-skip)
25407 (setq pos (match-beginning 0)
25408 ts (match-string 0)
25409 inc t
25410 hd (org-get-heading)
25411 summary (org-icalendar-cleanup-string
25412 (org-entry-get nil "SUMMARY"))
25413 desc (org-icalendar-cleanup-string
25414 (or (org-entry-get nil "DESCRIPTION")
25415 (and org-icalendar-include-body (org-get-entry)))
25416 t org-icalendar-include-body)
25417 location (org-icalendar-cleanup-string
25418 (org-entry-get nil "LOCATION"))
25419 category (org-get-category))
25420 (if (looking-at re2)
25421 (progn
25422 (goto-char (match-end 0))
25423 (setq ts2 (match-string 1) inc nil))
25424 (setq tmp (buffer-substring (max (point-min)
25425 (- pos org-ds-keyword-length))
25426 pos)
25427 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25428 (progn
25429 (setq inc nil)
25430 (replace-match "\\1" t nil ts))
25432 deadlinep (string-match org-deadline-regexp tmp)
25433 scheduledp (string-match org-scheduled-regexp tmp)
25434 ;; donep (org-entry-is-done-p)
25436 (if (or (string-match org-tr-regexp hd)
25437 (string-match org-ts-regexp hd))
25438 (setq hd (replace-match "" t t hd)))
25439 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25440 (setq rrule
25441 (concat "\nRRULE:FREQ="
25442 (cdr (assoc
25443 (match-string 2 ts)
25444 '(("d" . "DAILY")("w" . "WEEKLY")
25445 ("m" . "MONTHLY")("y" . "YEARLY"))))
25446 ";INTERVAL=" (match-string 1 ts)))
25447 (setq rrule ""))
25448 (setq summary (or summary hd))
25449 (if (string-match org-bracket-link-regexp summary)
25450 (setq summary
25451 (replace-match (if (match-end 3)
25452 (match-string 3 summary)
25453 (match-string 1 summary))
25454 t t summary)))
25455 (if deadlinep (setq summary (concat "DL: " summary)))
25456 (if scheduledp (setq summary (concat "S: " summary)))
25457 (if (string-match "\\`<%%" ts)
25458 (with-current-buffer sexp-buffer
25459 (insert (substring ts 1 -1) " " summary "\n"))
25460 (princ (format "BEGIN:VEVENT
25462 %s%s
25463 SUMMARY:%s%s%s
25464 CATEGORIES:%s
25465 END:VEVENT\n"
25466 (org-ical-ts-to-string ts "DTSTART")
25467 (org-ical-ts-to-string ts2 "DTEND" inc)
25468 rrule summary
25469 (if (and desc (string-match "\\S-" desc))
25470 (concat "\nDESCRIPTION: " desc) "")
25471 (if (and location (string-match "\\S-" location))
25472 (concat "\nLOCATION: " location) "")
25473 category)))))
25475 (when (and org-icalendar-include-sexps
25476 (condition-case nil (require 'icalendar) (error nil))
25477 (fboundp 'icalendar-export-region))
25478 ;; Get all the literal sexps
25479 (goto-char (point-min))
25480 (while (re-search-forward "^&?%%(" nil t)
25481 (catch :skip
25482 (org-agenda-skip)
25483 (setq b (match-beginning 0))
25484 (goto-char (1- (match-end 0)))
25485 (forward-sexp 1)
25486 (end-of-line 1)
25487 (setq sexp (buffer-substring b (point)))
25488 (with-current-buffer sexp-buffer
25489 (insert sexp "\n"))
25490 (princ (org-diary-to-ical-string sexp-buffer)))))
25492 (when org-icalendar-include-todo
25493 (goto-char (point-min))
25494 (while (re-search-forward org-todo-line-regexp nil t)
25495 (catch :skip
25496 (org-agenda-skip)
25497 (setq state (match-string 2))
25498 (setq status (if (member state org-done-keywords)
25499 "COMPLETED" "NEEDS-ACTION"))
25500 (when (and state
25501 (or (not (member state org-done-keywords))
25502 (eq org-icalendar-include-todo 'all))
25503 (not (member org-archive-tag (org-get-tags-at)))
25505 (setq hd (match-string 3)
25506 summary (org-icalendar-cleanup-string
25507 (org-entry-get nil "SUMMARY"))
25508 desc (org-icalendar-cleanup-string
25509 (or (org-entry-get nil "DESCRIPTION")
25510 (and org-icalendar-include-body (org-get-entry)))
25511 t org-icalendar-include-body)
25512 location (org-icalendar-cleanup-string
25513 (org-entry-get nil "LOCATION")))
25514 (if (string-match org-bracket-link-regexp hd)
25515 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25516 (match-string 1 hd))
25517 t t hd)))
25518 (if (string-match org-priority-regexp hd)
25519 (setq pri (string-to-char (match-string 2 hd))
25520 hd (concat (substring hd 0 (match-beginning 1))
25521 (substring hd (match-end 1))))
25522 (setq pri org-default-priority))
25523 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25524 (- org-lowest-priority org-highest-priority))))))
25526 (princ (format "BEGIN:VTODO
25528 SUMMARY:%s%s%s
25529 CATEGORIES:%s
25530 SEQUENCE:1
25531 PRIORITY:%d
25532 STATUS:%s
25533 END:VTODO\n"
25535 (or summary hd)
25536 (if (and location (string-match "\\S-" location))
25537 (concat "\nLOCATION: " location) "")
25538 (if (and desc (string-match "\\S-" desc))
25539 (concat "\nDESCRIPTION: " desc) "")
25540 category pri status)))))))))
25542 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25543 "Take out stuff and quote what needs to be quoted.
25544 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25545 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25546 characters."
25547 (if (not s)
25549 (when is-body
25550 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25551 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25552 (while (string-match re s) (setq s (replace-match "" t t s)))
25553 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25554 (let ((start 0))
25555 (while (string-match "\\([,;\\]\\)" s start)
25556 (setq start (+ (match-beginning 0) 2)
25557 s (replace-match "\\\\\\1" nil nil s))))
25558 (when is-body
25559 (while (string-match "[ \t]*\n[ \t]*" s)
25560 (setq s (replace-match "\\n" t t s))))
25561 (setq s (org-trim s))
25562 (if is-body
25563 (if maxlength
25564 (if (and (numberp maxlength)
25565 (> (length s) maxlength))
25566 (setq s (substring s 0 maxlength)))))
25569 (defun org-get-entry ()
25570 "Clean-up description string."
25571 (save-excursion
25572 (org-back-to-heading t)
25573 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25575 (defun org-start-icalendar-file (name)
25576 "Start an iCalendar file by inserting the header."
25577 (let ((user user-full-name)
25578 (name (or name "unknown"))
25579 (timezone (cadr (current-time-zone))))
25580 (princ
25581 (format "BEGIN:VCALENDAR
25582 VERSION:2.0
25583 X-WR-CALNAME:%s
25584 PRODID:-//%s//Emacs with Org-mode//EN
25585 X-WR-TIMEZONE:%s
25586 CALSCALE:GREGORIAN\n" name user timezone))))
25588 (defun org-finish-icalendar-file ()
25589 "Finish an iCalendar file by inserting the END statement."
25590 (princ "END:VCALENDAR\n"))
25592 (defun org-ical-ts-to-string (s keyword &optional inc)
25593 "Take a time string S and convert it to iCalendar format.
25594 KEYWORD is added in front, to make a complete line like DTSTART....
25595 When INC is non-nil, increase the hour by two (if time string contains
25596 a time), or the day by one (if it does not contain a time)."
25597 (let ((t1 (org-parse-time-string s 'nodefault))
25598 t2 fmt have-time time)
25599 (if (and (car t1) (nth 1 t1) (nth 2 t1))
25600 (setq t2 t1 have-time t)
25601 (setq t2 (org-parse-time-string s)))
25602 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
25603 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
25604 (when inc
25605 (if have-time
25606 (if org-agenda-default-appointment-duration
25607 (setq mi (+ org-agenda-default-appointment-duration mi))
25608 (setq h (+ 2 h)))
25609 (setq d (1+ d))))
25610 (setq time (encode-time s mi h d m y)))
25611 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
25612 (concat keyword (format-time-string fmt time))))
25614 ;;; XOXO export
25616 (defun org-export-as-xoxo-insert-into (buffer &rest output)
25617 (with-current-buffer buffer
25618 (apply 'insert output)))
25619 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
25621 (defun org-export-as-xoxo (&optional buffer)
25622 "Export the org buffer as XOXO.
25623 The XOXO buffer is named *xoxo-<source buffer name>*"
25624 (interactive (list (current-buffer)))
25625 ;; A quickie abstraction
25627 ;; Output everything as XOXO
25628 (with-current-buffer (get-buffer buffer)
25629 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
25630 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25631 (org-infile-export-plist)))
25632 (filename (concat (file-name-as-directory
25633 (org-export-directory :xoxo opt-plist))
25634 (file-name-sans-extension
25635 (file-name-nondirectory buffer-file-name))
25636 ".html"))
25637 (out (find-file-noselect filename))
25638 (last-level 1)
25639 (hanging-li nil))
25640 ;; Check the output buffer is empty.
25641 (with-current-buffer out (erase-buffer))
25642 ;; Kick off the output
25643 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
25644 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
25645 (let* ((hd (match-string-no-properties 1))
25646 (level (length hd))
25647 (text (concat
25648 (match-string-no-properties 2)
25649 (save-excursion
25650 (goto-char (match-end 0))
25651 (let ((str ""))
25652 (catch 'loop
25653 (while 't
25654 (forward-line)
25655 (if (looking-at "^[ \t]\\(.*\\)")
25656 (setq str (concat str (match-string-no-properties 1)))
25657 (throw 'loop str)))))))))
25659 ;; Handle level rendering
25660 (cond
25661 ((> level last-level)
25662 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
25664 ((< level last-level)
25665 (dotimes (- (- last-level level) 1)
25666 (if hanging-li
25667 (org-export-as-xoxo-insert-into out "</li>\n"))
25668 (org-export-as-xoxo-insert-into out "</ol>\n"))
25669 (when hanging-li
25670 (org-export-as-xoxo-insert-into out "</li>\n")
25671 (setq hanging-li nil)))
25673 ((equal level last-level)
25674 (if hanging-li
25675 (org-export-as-xoxo-insert-into out "</li>\n")))
25678 (setq last-level level)
25680 ;; And output the new li
25681 (setq hanging-li 't)
25682 (if (equal ?+ (elt text 0))
25683 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
25684 (org-export-as-xoxo-insert-into out "<li>" text))))
25686 ;; Finally finish off the ol
25687 (dotimes (- last-level 1)
25688 (if hanging-li
25689 (org-export-as-xoxo-insert-into out "</li>\n"))
25690 (org-export-as-xoxo-insert-into out "</ol>\n"))
25692 ;; Finish the buffer off and clean it up.
25693 (switch-to-buffer-other-window out)
25694 (indent-region (point-min) (point-max) nil)
25695 (save-buffer)
25696 (goto-char (point-min))
25700 ;;;; Key bindings
25702 ;; Make `C-c C-x' a prefix key
25703 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
25705 ;; TAB key with modifiers
25706 (org-defkey org-mode-map "\C-i" 'org-cycle)
25707 (org-defkey org-mode-map [(tab)] 'org-cycle)
25708 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
25709 (org-defkey org-mode-map [(meta tab)] 'org-complete)
25710 (org-defkey org-mode-map "\M-\t" 'org-complete)
25711 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
25712 ;; The following line is necessary under Suse GNU/Linux
25713 (unless (featurep 'xemacs)
25714 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
25715 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
25716 (define-key org-mode-map [backtab] 'org-shifttab)
25718 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
25719 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
25720 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
25722 ;; Cursor keys with modifiers
25723 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
25724 (org-defkey org-mode-map [(meta right)] 'org-metaright)
25725 (org-defkey org-mode-map [(meta up)] 'org-metaup)
25726 (org-defkey org-mode-map [(meta down)] 'org-metadown)
25728 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
25729 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
25730 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
25731 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
25733 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
25734 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
25735 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
25736 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
25738 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
25739 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
25741 ;;; Extra keys for tty access.
25742 ;; We only set them when really needed because otherwise the
25743 ;; menus don't show the simple keys
25745 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
25746 (not window-system))
25747 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
25748 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
25749 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
25750 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
25751 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
25752 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
25753 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
25754 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
25755 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
25756 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
25757 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
25758 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
25759 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
25760 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
25761 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
25762 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
25763 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
25764 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
25765 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
25766 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
25767 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
25768 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
25770 ;; All the other keys
25772 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
25773 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
25774 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
25775 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
25776 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
25777 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
25778 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
25779 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
25780 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
25781 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
25782 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
25783 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
25784 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
25785 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
25786 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
25787 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
25788 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
25789 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
25790 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
25791 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
25792 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
25793 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
25794 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
25795 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
25796 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
25797 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
25798 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
25799 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
25800 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
25801 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
25802 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
25803 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
25804 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
25805 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
25806 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
25807 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
25808 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
25809 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25810 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
25811 (org-defkey org-mode-map "\C-c^" 'org-sort)
25812 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
25813 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
25814 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
25815 (org-defkey org-mode-map "\C-m" 'org-return)
25816 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
25817 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
25818 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
25819 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
25820 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
25821 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
25822 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
25823 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
25824 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
25825 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
25826 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
25827 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
25828 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
25829 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
25830 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
25831 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
25833 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
25834 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
25835 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
25836 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
25838 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
25839 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
25840 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
25841 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
25842 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
25843 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
25844 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
25845 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
25846 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
25847 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
25848 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
25849 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
25851 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
25853 (when (featurep 'xemacs)
25854 (org-defkey org-mode-map 'button3 'popup-mode-menu))
25856 (defsubst org-table-p () (org-at-table-p))
25858 (defun org-self-insert-command (N)
25859 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
25860 If the cursor is in a table looking at whitespace, the whitespace is
25861 overwritten, and the table is not marked as requiring realignment."
25862 (interactive "p")
25863 (if (and (org-table-p)
25864 (progn
25865 ;; check if we blank the field, and if that triggers align
25866 (and org-table-auto-blank-field
25867 (member last-command
25868 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25869 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25870 ;; got extra space, this field does not determine column width
25871 (let (org-table-may-need-update) (org-table-blank-field))
25872 ;; no extra space, this field may determine column width
25873 (org-table-blank-field)))
25875 (eq N 1)
25876 (looking-at "[^|\n]* |"))
25877 (let (org-table-may-need-update)
25878 (goto-char (1- (match-end 0)))
25879 (delete-backward-char 1)
25880 (goto-char (match-beginning 0))
25881 (self-insert-command N))
25882 (setq org-table-may-need-update t)
25883 (self-insert-command N)
25884 (org-fix-tags-on-the-fly)))
25886 (defun org-fix-tags-on-the-fly ()
25887 (when (and (equal (char-after (point-at-bol)) ?*)
25888 (org-on-heading-p))
25889 (org-align-tags-here org-tags-column)))
25891 (defun org-delete-backward-char (N)
25892 "Like `delete-backward-char', insert whitespace at field end in tables.
25893 When deleting backwards, in tables this function will insert whitespace in
25894 front of the next \"|\" separator, to keep the table aligned. The table will
25895 still be marked for re-alignment if the field did fill the entire column,
25896 because, in this case the deletion might narrow the column."
25897 (interactive "p")
25898 (if (and (org-table-p)
25899 (eq N 1)
25900 (string-match "|" (buffer-substring (point-at-bol) (point)))
25901 (looking-at ".*?|"))
25902 (let ((pos (point))
25903 (noalign (looking-at "[^|\n\r]* |"))
25904 (c org-table-may-need-update))
25905 (backward-delete-char N)
25906 (skip-chars-forward "^|")
25907 (insert " ")
25908 (goto-char (1- pos))
25909 ;; noalign: if there were two spaces at the end, this field
25910 ;; does not determine the width of the column.
25911 (if noalign (setq org-table-may-need-update c)))
25912 (backward-delete-char N)
25913 (org-fix-tags-on-the-fly)))
25915 (defun org-delete-char (N)
25916 "Like `delete-char', but insert whitespace at field end in tables.
25917 When deleting characters, in tables this function will insert whitespace in
25918 front of the next \"|\" separator, to keep the table aligned. The table will
25919 still be marked for re-alignment if the field did fill the entire column,
25920 because, in this case the deletion might narrow the column."
25921 (interactive "p")
25922 (if (and (org-table-p)
25923 (not (bolp))
25924 (not (= (char-after) ?|))
25925 (eq N 1))
25926 (if (looking-at ".*?|")
25927 (let ((pos (point))
25928 (noalign (looking-at "[^|\n\r]* |"))
25929 (c org-table-may-need-update))
25930 (replace-match (concat
25931 (substring (match-string 0) 1 -1)
25932 " |"))
25933 (goto-char pos)
25934 ;; noalign: if there were two spaces at the end, this field
25935 ;; does not determine the width of the column.
25936 (if noalign (setq org-table-may-need-update c)))
25937 (delete-char N))
25938 (delete-char N)
25939 (org-fix-tags-on-the-fly)))
25941 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25942 (put 'org-self-insert-command 'delete-selection t)
25943 (put 'orgtbl-self-insert-command 'delete-selection t)
25944 (put 'org-delete-char 'delete-selection 'supersede)
25945 (put 'org-delete-backward-char 'delete-selection 'supersede)
25947 ;; Make `flyspell-mode' delay after some commands
25948 (put 'org-self-insert-command 'flyspell-delayed t)
25949 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25950 (put 'org-delete-char 'flyspell-delayed t)
25951 (put 'org-delete-backward-char 'flyspell-delayed t)
25953 ;; Make pabbrev-mode expand after org-mode commands
25954 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
25955 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
25957 ;; How to do this: Measure non-white length of current string
25958 ;; If equal to column width, we should realign.
25960 (defun org-remap (map &rest commands)
25961 "In MAP, remap the functions given in COMMANDS.
25962 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25963 (let (new old)
25964 (while commands
25965 (setq old (pop commands) new (pop commands))
25966 (if (fboundp 'command-remapping)
25967 (org-defkey map (vector 'remap old) new)
25968 (substitute-key-definition old new map global-map)))))
25970 (when (eq org-enable-table-editor 'optimized)
25971 ;; If the user wants maximum table support, we need to hijack
25972 ;; some standard editing functions
25973 (org-remap org-mode-map
25974 'self-insert-command 'org-self-insert-command
25975 'delete-char 'org-delete-char
25976 'delete-backward-char 'org-delete-backward-char)
25977 (org-defkey org-mode-map "|" 'org-force-self-insert))
25979 (defun org-shiftcursor-error ()
25980 "Throw an error because Shift-Cursor command was applied in wrong context."
25981 (error "This command is active in special context like tables, headlines or timestamps"))
25983 (defun org-shifttab (&optional arg)
25984 "Global visibility cycling or move to previous table field.
25985 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25986 on context.
25987 See the individual commands for more information."
25988 (interactive "P")
25989 (cond
25990 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25991 (arg (message "Content view to level: ")
25992 (org-content (prefix-numeric-value arg))
25993 (setq org-cycle-global-status 'overview))
25994 (t (call-interactively 'org-global-cycle))))
25996 (defun org-shiftmetaleft ()
25997 "Promote subtree or delete table column.
25998 Calls `org-promote-subtree', `org-outdent-item',
25999 or `org-table-delete-column', depending on context.
26000 See the individual commands for more information."
26001 (interactive)
26002 (cond
26003 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26004 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26005 ((org-at-item-p) (call-interactively 'org-outdent-item))
26006 (t (org-shiftcursor-error))))
26008 (defun org-shiftmetaright ()
26009 "Demote subtree or insert table column.
26010 Calls `org-demote-subtree', `org-indent-item',
26011 or `org-table-insert-column', depending on context.
26012 See the individual commands for more information."
26013 (interactive)
26014 (cond
26015 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26016 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26017 ((org-at-item-p) (call-interactively 'org-indent-item))
26018 (t (org-shiftcursor-error))))
26020 (defun org-shiftmetaup (&optional arg)
26021 "Move subtree up or kill table row.
26022 Calls `org-move-subtree-up' or `org-table-kill-row' or
26023 `org-move-item-up' depending on context. See the individual commands
26024 for more information."
26025 (interactive "P")
26026 (cond
26027 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26028 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26029 ((org-at-item-p) (call-interactively 'org-move-item-up))
26030 (t (org-shiftcursor-error))))
26031 (defun org-shiftmetadown (&optional arg)
26032 "Move subtree down or insert table row.
26033 Calls `org-move-subtree-down' or `org-table-insert-row' or
26034 `org-move-item-down', depending on context. See the individual
26035 commands for more information."
26036 (interactive "P")
26037 (cond
26038 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26039 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26040 ((org-at-item-p) (call-interactively 'org-move-item-down))
26041 (t (org-shiftcursor-error))))
26043 (defun org-metaleft (&optional arg)
26044 "Promote heading or move table column to left.
26045 Calls `org-do-promote' or `org-table-move-column', depending on context.
26046 With no specific context, calls the Emacs default `backward-word'.
26047 See the individual commands for more information."
26048 (interactive "P")
26049 (cond
26050 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26051 ((or (org-on-heading-p) (org-region-active-p))
26052 (call-interactively 'org-do-promote))
26053 ((org-at-item-p) (call-interactively 'org-outdent-item))
26054 (t (call-interactively 'backward-word))))
26056 (defun org-metaright (&optional arg)
26057 "Demote subtree or move table column to right.
26058 Calls `org-do-demote' or `org-table-move-column', depending on context.
26059 With no specific context, calls the Emacs default `forward-word'.
26060 See the individual commands for more information."
26061 (interactive "P")
26062 (cond
26063 ((org-at-table-p) (call-interactively 'org-table-move-column))
26064 ((or (org-on-heading-p) (org-region-active-p))
26065 (call-interactively 'org-do-demote))
26066 ((org-at-item-p) (call-interactively 'org-indent-item))
26067 (t (call-interactively 'forward-word))))
26069 (defun org-metaup (&optional arg)
26070 "Move subtree up or move table row up.
26071 Calls `org-move-subtree-up' or `org-table-move-row' or
26072 `org-move-item-up', depending on context. See the individual commands
26073 for more information."
26074 (interactive "P")
26075 (cond
26076 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26077 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26078 ((org-at-item-p) (call-interactively 'org-move-item-up))
26079 (t (transpose-lines 1) (beginning-of-line -1))))
26081 (defun org-metadown (&optional arg)
26082 "Move subtree down or move table row down.
26083 Calls `org-move-subtree-down' or `org-table-move-row' or
26084 `org-move-item-down', depending on context. See the individual
26085 commands for more information."
26086 (interactive "P")
26087 (cond
26088 ((org-at-table-p) (call-interactively 'org-table-move-row))
26089 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26090 ((org-at-item-p) (call-interactively 'org-move-item-down))
26091 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26093 (defun org-shiftup (&optional arg)
26094 "Increase item in timestamp or increase priority of current headline.
26095 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26096 depending on context. See the individual commands for more information."
26097 (interactive "P")
26098 (cond
26099 ((org-at-timestamp-p t)
26100 (call-interactively (if org-edit-timestamp-down-means-later
26101 'org-timestamp-down 'org-timestamp-up)))
26102 ((org-on-heading-p) (call-interactively 'org-priority-up))
26103 ((org-at-item-p) (call-interactively 'org-previous-item))
26104 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26106 (defun org-shiftdown (&optional arg)
26107 "Decrease item in timestamp or decrease priority of current headline.
26108 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26109 depending on context. See the individual commands for more information."
26110 (interactive "P")
26111 (cond
26112 ((org-at-timestamp-p t)
26113 (call-interactively (if org-edit-timestamp-down-means-later
26114 'org-timestamp-up 'org-timestamp-down)))
26115 ((org-on-heading-p) (call-interactively 'org-priority-down))
26116 (t (call-interactively 'org-next-item))))
26118 (defun org-shiftright ()
26119 "Next TODO keyword or timestamp one day later, depending on context."
26120 (interactive)
26121 (cond
26122 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26123 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26124 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26125 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26126 (t (org-shiftcursor-error))))
26128 (defun org-shiftleft ()
26129 "Previous TODO keyword or timestamp one day earlier, depending on context."
26130 (interactive)
26131 (cond
26132 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26133 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26134 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26135 ((org-at-property-p)
26136 (call-interactively 'org-property-previous-allowed-value))
26137 (t (org-shiftcursor-error))))
26139 (defun org-shiftcontrolright ()
26140 "Switch to next TODO set."
26141 (interactive)
26142 (cond
26143 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26144 (t (org-shiftcursor-error))))
26146 (defun org-shiftcontrolleft ()
26147 "Switch to previous TODO set."
26148 (interactive)
26149 (cond
26150 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26151 (t (org-shiftcursor-error))))
26153 (defun org-ctrl-c-ret ()
26154 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26155 (interactive)
26156 (cond
26157 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26158 (t (call-interactively 'org-insert-heading))))
26160 (defun org-copy-special ()
26161 "Copy region in table or copy current subtree.
26162 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26163 See the individual commands for more information."
26164 (interactive)
26165 (call-interactively
26166 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26168 (defun org-cut-special ()
26169 "Cut region in table or cut current subtree.
26170 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26171 See the individual commands for more information."
26172 (interactive)
26173 (call-interactively
26174 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26176 (defun org-paste-special (arg)
26177 "Paste rectangular region into table, or past subtree relative to level.
26178 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26179 See the individual commands for more information."
26180 (interactive "P")
26181 (if (org-at-table-p)
26182 (org-table-paste-rectangle)
26183 (org-paste-subtree arg)))
26185 (defun org-ctrl-c-ctrl-c (&optional arg)
26186 "Set tags in headline, or update according to changed information at point.
26188 This command does many different things, depending on context:
26190 - If the cursor is in a headline, prompt for tags and insert them
26191 into the current line, aligned to `org-tags-column'. When called
26192 with prefix arg, realign all tags in the current buffer.
26194 - If the cursor is in one of the special #+KEYWORD lines, this
26195 triggers scanning the buffer for these lines and updating the
26196 information.
26198 - If the cursor is inside a table, realign the table. This command
26199 works even if the automatic table editor has been turned off.
26201 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26202 the entire table.
26204 - If the cursor is a the beginning of a dynamic block, update it.
26206 - If the cursor is inside a table created by the table.el package,
26207 activate that table.
26209 - If the current buffer is a remember buffer, close note and file it.
26210 with a prefix argument, file it without further interaction to the default
26211 location.
26213 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26214 links in this buffer.
26216 - If the cursor is on a numbered item in a plain list, renumber the
26217 ordered list.
26219 - If the cursor is on a checkbox, toggle it."
26220 (interactive "P")
26221 (let ((org-enable-table-editor t))
26222 (cond
26223 ((or org-clock-overlays
26224 org-occur-highlights
26225 org-latex-fragment-image-overlays)
26226 (org-remove-clock-overlays)
26227 (org-remove-occur-highlights)
26228 (org-remove-latex-fragment-image-overlays)
26229 (message "Temporary highlights/overlays removed from current buffer"))
26230 ((and (local-variable-p 'org-finish-function (current-buffer))
26231 (fboundp org-finish-function))
26232 (funcall org-finish-function))
26233 ((org-at-property-p)
26234 (call-interactively 'org-property-action))
26235 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26236 ((org-on-heading-p) (call-interactively 'org-set-tags))
26237 ((org-at-table.el-p)
26238 (require 'table)
26239 (beginning-of-line 1)
26240 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26241 (call-interactively 'table-recognize-table))
26242 ((org-at-table-p)
26243 (org-table-maybe-eval-formula)
26244 (if arg
26245 (call-interactively 'org-table-recalculate)
26246 (org-table-maybe-recalculate-line))
26247 (call-interactively 'org-table-align))
26248 ((org-at-item-checkbox-p)
26249 (call-interactively 'org-toggle-checkbox))
26250 ((org-at-item-p)
26251 (call-interactively 'org-maybe-renumber-ordered-list))
26252 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26253 ;; Dynamic block
26254 (beginning-of-line 1)
26255 (org-update-dblock))
26256 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26257 (cond
26258 ((equal (match-string 1) "TBLFM")
26259 ;; Recalculate the table before this line
26260 (save-excursion
26261 (beginning-of-line 1)
26262 (skip-chars-backward " \r\n\t")
26263 (if (org-at-table-p)
26264 (org-call-with-arg 'org-table-recalculate t))))
26266 (call-interactively 'org-mode-restart))))
26267 (t (error "C-c C-c can do nothing useful at this location.")))))
26269 (defun org-mode-restart ()
26270 "Restart Org-mode, to scan again for special lines.
26271 Also updates the keyword regular expressions."
26272 (interactive)
26273 (let ((org-inhibit-startup t)) (org-mode))
26274 (message "Org-mode restarted to refresh keyword and special line setup"))
26276 (defun org-kill-note-or-show-branches ()
26277 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26278 (interactive)
26279 (if (not org-finish-function)
26280 (call-interactively 'show-branches)
26281 (let ((org-note-abort t))
26282 (funcall org-finish-function))))
26284 (defun org-return ()
26285 "Goto next table row or insert a newline.
26286 Calls `org-table-next-row' or `newline', depending on context.
26287 See the individual commands for more information."
26288 (interactive)
26289 (cond
26290 ((bobp) (newline))
26291 ((org-at-table-p)
26292 (org-table-justify-field-maybe)
26293 (call-interactively 'org-table-next-row))
26294 (t (newline))))
26297 (defun org-ctrl-c-minus ()
26298 "Insert separator line in table or modify bullet type in list.
26299 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26300 depending on context."
26301 (interactive)
26302 (cond
26303 ((org-at-table-p)
26304 (call-interactively 'org-table-insert-hline))
26305 ((org-on-heading-p)
26306 ;; Convert to item
26307 (save-excursion
26308 (beginning-of-line 1)
26309 (if (looking-at "\\*+ ")
26310 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26311 ((org-in-item-p)
26312 (call-interactively 'org-cycle-list-bullet))
26313 (t (error "`C-c -' does have no function here."))))
26315 (defun org-meta-return (&optional arg)
26316 "Insert a new heading or wrap a region in a table.
26317 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26318 See the individual commands for more information."
26319 (interactive "P")
26320 (cond
26321 ((org-at-table-p)
26322 (call-interactively 'org-table-wrap-region))
26323 (t (call-interactively 'org-insert-heading))))
26325 ;;; Menu entries
26327 ;; Define the Org-mode menus
26328 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26329 '("Tbl"
26330 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26331 ["Next Field" org-cycle (org-at-table-p)]
26332 ["Previous Field" org-shifttab (org-at-table-p)]
26333 ["Next Row" org-return (org-at-table-p)]
26334 "--"
26335 ["Blank Field" org-table-blank-field (org-at-table-p)]
26336 ["Edit Field" org-table-edit-field (org-at-table-p)]
26337 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26338 "--"
26339 ("Column"
26340 ["Move Column Left" org-metaleft (org-at-table-p)]
26341 ["Move Column Right" org-metaright (org-at-table-p)]
26342 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26343 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26344 ("Row"
26345 ["Move Row Up" org-metaup (org-at-table-p)]
26346 ["Move Row Down" org-metadown (org-at-table-p)]
26347 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26348 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26349 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26350 "--"
26351 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26352 ("Rectangle"
26353 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26354 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26355 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26356 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26357 "--"
26358 ("Calculate"
26359 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26360 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26361 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26362 "--"
26363 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26364 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26365 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26366 "--"
26367 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26368 "--"
26369 ["Sum Column/Rectangle" org-table-sum
26370 (or (org-at-table-p) (org-region-active-p))]
26371 ["Which Column?" org-table-current-column (org-at-table-p)])
26372 ["Debug Formulas"
26373 org-table-toggle-formula-debugger
26374 :style toggle :selected org-table-formula-debug]
26375 ["Show Col/Row Numbers"
26376 org-table-toggle-coordinate-overlays
26377 :style toggle :selected org-table-overlay-coordinates]
26378 "--"
26379 ["Create" org-table-create (and (not (org-at-table-p))
26380 org-enable-table-editor)]
26381 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26382 ["Import from File" org-table-import (not (org-at-table-p))]
26383 ["Export to File" org-table-export (org-at-table-p)]
26384 "--"
26385 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26387 (easy-menu-define org-org-menu org-mode-map "Org menu"
26388 '("Org"
26389 ("Show/Hide"
26390 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26391 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26392 ["Sparse Tree" org-occur t]
26393 ["Reveal Context" org-reveal t]
26394 ["Show All" show-all t]
26395 "--"
26396 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26397 "--"
26398 ["New Heading" org-insert-heading t]
26399 ("Navigate Headings"
26400 ["Up" outline-up-heading t]
26401 ["Next" outline-next-visible-heading t]
26402 ["Previous" outline-previous-visible-heading t]
26403 ["Next Same Level" outline-forward-same-level t]
26404 ["Previous Same Level" outline-backward-same-level t]
26405 "--"
26406 ["Jump" org-goto t])
26407 ("Edit Structure"
26408 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26409 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26410 "--"
26411 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26412 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26413 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26414 "--"
26415 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26416 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26417 ["Demote Heading" org-metaright (not (org-at-table-p))]
26418 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26419 "--"
26420 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26421 "--"
26422 ["Convert to odd levels" org-convert-to-odd-levels t]
26423 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26424 ("Editing"
26425 ["Emphasis..." org-emphasize t])
26426 ("Archive"
26427 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26428 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26429 ; :active t :keys "C-u C-c C-x C-a"]
26430 ["Sparse trees open ARCHIVE trees"
26431 (setq org-sparse-tree-open-archived-trees
26432 (not org-sparse-tree-open-archived-trees))
26433 :style toggle :selected org-sparse-tree-open-archived-trees]
26434 ["Cycling opens ARCHIVE trees"
26435 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26436 :style toggle :selected org-cycle-open-archived-trees]
26437 ["Agenda includes ARCHIVE trees"
26438 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26439 :style toggle :selected (not org-agenda-skip-archived-trees)]
26440 "--"
26441 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26442 ; ["Check and Move Children" (org-archive-subtree '(4))
26443 ; :active t :keys "C-u C-c C-x C-s"]
26445 "--"
26446 ("TODO Lists"
26447 ["TODO/DONE/-" org-todo t]
26448 ("Select keyword"
26449 ["Next keyword" org-shiftright (org-on-heading-p)]
26450 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26451 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26452 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26453 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26454 ["Show TODO Tree" org-show-todo-tree t]
26455 ["Global TODO list" org-todo-list t]
26456 "--"
26457 ["Set Priority" org-priority t]
26458 ["Priority Up" org-shiftup t]
26459 ["Priority Down" org-shiftdown t])
26460 ("TAGS and Properties"
26461 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26462 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26463 "--"
26464 ["Set property" 'org-set-property t]
26465 ["Column view of properties" org-columns t]
26466 ["Insert Column View DBlock" org-insert-columns-dblock t])
26467 ("Dates and Scheduling"
26468 ["Timestamp" org-time-stamp t]
26469 ["Timestamp (inactive)" org-time-stamp-inactive t]
26470 ("Change Date"
26471 ["1 Day Later" org-shiftright t]
26472 ["1 Day Earlier" org-shiftleft t]
26473 ["1 ... Later" org-shiftup t]
26474 ["1 ... Earlier" org-shiftdown t])
26475 ["Compute Time Range" org-evaluate-time-range t]
26476 ["Schedule Item" org-schedule t]
26477 ["Deadline" org-deadline t]
26478 "--"
26479 ["Custom time format" org-toggle-time-stamp-overlays
26480 :style radio :selected org-display-custom-times]
26481 "--"
26482 ["Goto Calendar" org-goto-calendar t]
26483 ["Date from Calendar" org-date-from-calendar t])
26484 ("Logging work"
26485 ["Clock in" org-clock-in t]
26486 ["Clock out" org-clock-out t]
26487 ["Clock cancel" org-clock-cancel t]
26488 ["Goto running clock" org-clock-goto t]
26489 ["Display times" org-clock-display t]
26490 ["Create clock table" org-clock-report t]
26491 "--"
26492 ["Record DONE time"
26493 (progn (setq org-log-done (not org-log-done))
26494 (message "Switching to %s will %s record a timestamp"
26495 (car org-done-keywords)
26496 (if org-log-done "automatically" "not")))
26497 :style toggle :selected org-log-done])
26498 "--"
26499 ["Agenda Command..." org-agenda t]
26500 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26501 ("File List for Agenda")
26502 ("Special views current file"
26503 ["TODO Tree" org-show-todo-tree t]
26504 ["Check Deadlines" org-check-deadlines t]
26505 ["Timeline" org-timeline t]
26506 ["Tags Tree" org-tags-sparse-tree t])
26507 "--"
26508 ("Hyperlinks"
26509 ["Store Link (Global)" org-store-link t]
26510 ["Insert Link" org-insert-link t]
26511 ["Follow Link" org-open-at-point t]
26512 "--"
26513 ["Next link" org-next-link t]
26514 ["Previous link" org-previous-link t]
26515 "--"
26516 ["Descriptive Links"
26517 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26518 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26519 ["Literal Links"
26520 (progn
26521 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26522 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26523 "--"
26524 ["Export/Publish..." org-export t]
26525 ("LaTeX"
26526 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26527 :selected org-cdlatex-mode]
26528 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26529 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26530 ["Modify math symbol" org-cdlatex-math-modify
26531 (org-inside-LaTeX-fragment-p)]
26532 ["Export LaTeX fragments as images"
26533 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26534 :style toggle :selected org-export-with-LaTeX-fragments])
26535 "--"
26536 ("Documentation"
26537 ["Show Version" org-version t]
26538 ["Info Documentation" org-info t])
26539 ("Customize"
26540 ["Browse Org Group" org-customize t]
26541 "--"
26542 ["Expand This Menu" org-create-customize-menu
26543 (fboundp 'customize-menu-create)])
26544 "--"
26545 ["Refresh setup" org-mode-restart t]
26548 (defun org-info (&optional node)
26549 "Read documentation for Org-mode in the info system.
26550 With optional NODE, go directly to that node."
26551 (interactive)
26552 (require 'info)
26553 (Info-goto-node (format "(org)%s" (or node ""))))
26555 (defun org-install-agenda-files-menu ()
26556 (let ((bl (buffer-list)))
26557 (save-excursion
26558 (while bl
26559 (set-buffer (pop bl))
26560 (if (org-mode-p) (setq bl nil)))
26561 (when (org-mode-p)
26562 (easy-menu-change
26563 '("Org") "File List for Agenda"
26564 (append
26565 (list
26566 ["Edit File List" (org-edit-agenda-file-list) t]
26567 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26568 ["Remove Current File from List" org-remove-file t]
26569 ["Cycle through agenda files" org-cycle-agenda-files t]
26570 ["Occur in all agenda files" org-occur-in-agenda-files t]
26571 "--")
26572 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
26574 ;;;; Documentation
26576 (defun org-customize ()
26577 "Call the customize function with org as argument."
26578 (interactive)
26579 (customize-browse 'org))
26581 (defun org-create-customize-menu ()
26582 "Create a full customization menu for Org-mode, insert it into the menu."
26583 (interactive)
26584 (if (fboundp 'customize-menu-create)
26585 (progn
26586 (easy-menu-change
26587 '("Org") "Customize"
26588 `(["Browse Org group" org-customize t]
26589 "--"
26590 ,(customize-menu-create 'org)
26591 ["Set" Custom-set t]
26592 ["Save" Custom-save t]
26593 ["Reset to Current" Custom-reset-current t]
26594 ["Reset to Saved" Custom-reset-saved t]
26595 ["Reset to Standard Settings" Custom-reset-standard t]))
26596 (message "\"Org\"-menu now contains full customization menu"))
26597 (error "Cannot expand menu (outdated version of cus-edit.el)")))
26599 ;;;; Miscellaneous stuff
26602 ;;; Generally useful functions
26604 (defun org-context ()
26605 "Return a list of contexts of the current cursor position.
26606 If several contexts apply, all are returned.
26607 Each context entry is a list with a symbol naming the context, and
26608 two positions indicating start and end of the context. Possible
26609 contexts are:
26611 :headline anywhere in a headline
26612 :headline-stars on the leading stars in a headline
26613 :todo-keyword on a TODO keyword (including DONE) in a headline
26614 :tags on the TAGS in a headline
26615 :priority on the priority cookie in a headline
26616 :item on the first line of a plain list item
26617 :item-bullet on the bullet/number of a plain list item
26618 :checkbox on the checkbox in a plain list item
26619 :table in an org-mode table
26620 :table-special on a special filed in a table
26621 :table-table in a table.el table
26622 :link on a hyperlink
26623 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
26624 :target on a <<target>>
26625 :radio-target on a <<<radio-target>>>
26626 :latex-fragment on a LaTeX fragment
26627 :latex-preview on a LaTeX fragment with overlayed preview image
26629 This function expects the position to be visible because it uses font-lock
26630 faces as a help to recognize the following contexts: :table-special, :link,
26631 and :keyword."
26632 (let* ((f (get-text-property (point) 'face))
26633 (faces (if (listp f) f (list f)))
26634 (p (point)) clist o)
26635 ;; First the large context
26636 (cond
26637 ((org-on-heading-p t)
26638 (push (list :headline (point-at-bol) (point-at-eol)) clist)
26639 (when (progn
26640 (beginning-of-line 1)
26641 (looking-at org-todo-line-tags-regexp))
26642 (push (org-point-in-group p 1 :headline-stars) clist)
26643 (push (org-point-in-group p 2 :todo-keyword) clist)
26644 (push (org-point-in-group p 4 :tags) clist))
26645 (goto-char p)
26646 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
26647 (if (looking-at "\\[#[A-Z0-9]\\]")
26648 (push (org-point-in-group p 0 :priority) clist)))
26650 ((org-at-item-p)
26651 (push (org-point-in-group p 2 :item-bullet) clist)
26652 (push (list :item (point-at-bol)
26653 (save-excursion (org-end-of-item) (point)))
26654 clist)
26655 (and (org-at-item-checkbox-p)
26656 (push (org-point-in-group p 0 :checkbox) clist)))
26658 ((org-at-table-p)
26659 (push (list :table (org-table-begin) (org-table-end)) clist)
26660 (if (memq 'org-formula faces)
26661 (push (list :table-special
26662 (previous-single-property-change p 'face)
26663 (next-single-property-change p 'face)) clist)))
26664 ((org-at-table-p 'any)
26665 (push (list :table-table) clist)))
26666 (goto-char p)
26668 ;; Now the small context
26669 (cond
26670 ((org-at-timestamp-p)
26671 (push (org-point-in-group p 0 :timestamp) clist))
26672 ((memq 'org-link faces)
26673 (push (list :link
26674 (previous-single-property-change p 'face)
26675 (next-single-property-change p 'face)) clist))
26676 ((memq 'org-special-keyword faces)
26677 (push (list :keyword
26678 (previous-single-property-change p 'face)
26679 (next-single-property-change p 'face)) clist))
26680 ((org-on-target-p)
26681 (push (org-point-in-group p 0 :target) clist)
26682 (goto-char (1- (match-beginning 0)))
26683 (if (looking-at org-radio-target-regexp)
26684 (push (org-point-in-group p 0 :radio-target) clist))
26685 (goto-char p))
26686 ((setq o (car (delq nil
26687 (mapcar
26688 (lambda (x)
26689 (if (memq x org-latex-fragment-image-overlays) x))
26690 (org-overlays-at (point))))))
26691 (push (list :latex-fragment
26692 (org-overlay-start o) (org-overlay-end o)) clist)
26693 (push (list :latex-preview
26694 (org-overlay-start o) (org-overlay-end o)) clist))
26695 ((org-inside-LaTeX-fragment-p)
26696 ;; FIXME: positions wrong.
26697 (push (list :latex-fragment (point) (point)) clist)))
26699 (setq clist (nreverse (delq nil clist)))
26700 clist))
26702 ;; FIXME: Compare with at-regexp-p Do we need both?
26703 (defun org-in-regexp (re &optional nlines visually)
26704 "Check if point is inside a match of regexp.
26705 Normally only the current line is checked, but you can include NLINES extra
26706 lines both before and after point into the search.
26707 If VISUALLY is set, require that the cursor is not after the match but
26708 really on, so that the block visually is on the match."
26709 (catch 'exit
26710 (let ((pos (point))
26711 (eol (point-at-eol (+ 1 (or nlines 0))))
26712 (inc (if visually 1 0)))
26713 (save-excursion
26714 (beginning-of-line (- 1 (or nlines 0)))
26715 (while (re-search-forward re eol t)
26716 (if (and (<= (match-beginning 0) pos)
26717 (>= (+ inc (match-end 0)) pos))
26718 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
26720 (defun org-at-regexp-p (regexp)
26721 "Is point inside a match of REGEXP in the current line?"
26722 (catch 'exit
26723 (save-excursion
26724 (let ((pos (point)) (end (point-at-eol)))
26725 (beginning-of-line 1)
26726 (while (re-search-forward regexp end t)
26727 (if (and (<= (match-beginning 0) pos)
26728 (>= (match-end 0) pos))
26729 (throw 'exit t)))
26730 nil))))
26732 (defun org-occur-in-agenda-files (regexp &optional nlines)
26733 "Call `multi-occur' with buffers for all agenda files."
26734 (interactive "sOrg-files matching: \np")
26735 (let* ((files (org-agenda-files))
26736 (tnames (mapcar 'file-truename files))
26737 (extra org-agenda-multi-occur-extra-files)
26739 (while (setq f (pop extra))
26740 (unless (member (file-truename f) tnames)
26741 (add-to-list 'files f 'append)
26742 (add-to-list 'tnames (file-truename f) 'append)))
26743 (multi-occur
26744 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
26745 regexp)))
26747 (defun org-uniquify (list)
26748 "Remove duplicate elements from LIST."
26749 (let (res)
26750 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
26751 res))
26753 (defun org-delete-all (elts list)
26754 "Remove all elements in ELTS from LIST."
26755 (while elts
26756 (setq list (delete (pop elts) list)))
26757 list)
26759 (defun org-point-in-group (point group &optional context)
26760 "Check if POINT is in match-group GROUP.
26761 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
26762 match. If the match group does ot exist or point is not inside it,
26763 return nil."
26764 (and (match-beginning group)
26765 (>= point (match-beginning group))
26766 (<= point (match-end group))
26767 (if context
26768 (list context (match-beginning group) (match-end group))
26769 t)))
26771 (defun org-switch-to-buffer-other-window (&rest args)
26772 "Switch to buffer in a second window on the current frame.
26773 In particular, do not allow pop-up frames."
26774 (let (pop-up-frames special-display-buffer-names special-display-regexps
26775 special-display-function)
26776 (apply 'switch-to-buffer-other-window args)))
26778 (defun org-combine-plists (&rest plists)
26779 "Create a single property list from all plists in PLISTS.
26780 The process starts by copying the first list, and then setting properties
26781 from the other lists. Settings in the last list are the most significant
26782 ones and overrule settings in the other lists."
26783 (let ((rtn (copy-sequence (pop plists)))
26784 p v ls)
26785 (while plists
26786 (setq ls (pop plists))
26787 (while ls
26788 (setq p (pop ls) v (pop ls))
26789 (setq rtn (plist-put rtn p v))))
26790 rtn))
26792 (defun org-move-line-down (arg)
26793 "Move the current line down. With prefix argument, move it past ARG lines."
26794 (interactive "p")
26795 (let ((col (current-column))
26796 beg end pos)
26797 (beginning-of-line 1) (setq beg (point))
26798 (beginning-of-line 2) (setq end (point))
26799 (beginning-of-line (+ 1 arg))
26800 (setq pos (move-marker (make-marker) (point)))
26801 (insert (delete-and-extract-region beg end))
26802 (goto-char pos)
26803 (move-to-column col)))
26805 (defun org-move-line-up (arg)
26806 "Move the current line up. With prefix argument, move it past ARG lines."
26807 (interactive "p")
26808 (let ((col (current-column))
26809 beg end pos)
26810 (beginning-of-line 1) (setq beg (point))
26811 (beginning-of-line 2) (setq end (point))
26812 (beginning-of-line (- arg))
26813 (setq pos (move-marker (make-marker) (point)))
26814 (insert (delete-and-extract-region beg end))
26815 (goto-char pos)
26816 (move-to-column col)))
26818 (defun org-replace-escapes (string table)
26819 "Replace %-escapes in STRING with values in TABLE.
26820 TABLE is an association list with keys like \"%a\" and string values.
26821 The sequences in STRING may contain normal field width and padding information,
26822 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
26823 so values can contain further %-escapes if they are define later in TABLE."
26824 (let ((case-fold-search nil)
26825 e re rpl)
26826 (while (setq e (pop table))
26827 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
26828 (while (string-match re string)
26829 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
26830 (cdr e)))
26831 (setq string (replace-match rpl t t string))))
26832 string))
26835 (defun org-sublist (list start end)
26836 "Return a section of LIST, from START to END.
26837 Counting starts at 1."
26838 (let (rtn (c start))
26839 (setq list (nthcdr (1- start) list))
26840 (while (and list (<= c end))
26841 (push (pop list) rtn)
26842 (setq c (1+ c)))
26843 (nreverse rtn)))
26845 (defun org-find-base-buffer-visiting (file)
26846 "Like `find-buffer-visiting' but alway return the base buffer and
26847 not an indirect buffer"
26848 (let ((buf (find-buffer-visiting file)))
26849 (if buf
26850 (or (buffer-base-buffer buf) buf)
26851 nil)))
26853 (defun org-image-file-name-regexp ()
26854 "Return regexp matching the file names of images."
26855 (if (fboundp 'image-file-name-regexp)
26856 (image-file-name-regexp)
26857 (let ((image-file-name-extensions
26858 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
26859 "xbm" "xpm" "pbm" "pgm" "ppm")))
26860 (concat "\\."
26861 (regexp-opt (nconc (mapcar 'upcase
26862 image-file-name-extensions)
26863 image-file-name-extensions)
26865 "\\'"))))
26867 (defun org-file-image-p (file)
26868 "Return non-nil if FILE is an image."
26869 (save-match-data
26870 (string-match (org-image-file-name-regexp) file)))
26872 ;;; Paragraph filling stuff.
26873 ;; We want this to be just right, so use the full arsenal.
26875 (defun org-indent-line-function ()
26876 "Indent line like previous, but further if previous was headline or item."
26877 (interactive)
26878 (let* ((pos (point))
26879 (itemp (org-at-item-p))
26880 column bpos bcol tpos tcol bullet btype bullet-type)
26881 ;; Find the previous relevant line
26882 (beginning-of-line 1)
26883 (cond
26884 ((looking-at "#") (setq column 0))
26885 ((looking-at "\\*+ ") (setq column 0))
26887 (beginning-of-line 0)
26888 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26889 (beginning-of-line 0))
26890 (cond
26891 ((looking-at "\\*+[ \t]+")
26892 (goto-char (match-end 0))
26893 (setq column (current-column)))
26894 ((org-in-item-p)
26895 (org-beginning-of-item)
26896 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26897 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26898 (setq bpos (match-beginning 1) tpos (match-end 0)
26899 bcol (progn (goto-char bpos) (current-column))
26900 tcol (progn (goto-char tpos) (current-column))
26901 bullet (match-string 1)
26902 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26903 (if (not itemp)
26904 (setq column tcol)
26905 (goto-char pos)
26906 (beginning-of-line 1)
26907 (if (looking-at "\\S-")
26908 (progn
26909 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26910 (setq bullet (match-string 1)
26911 btype (if (string-match "[0-9]" bullet) "n" bullet))
26912 (setq column (if (equal btype bullet-type) bcol tcol)))
26913 (setq column (org-get-indentation)))))
26914 (t (setq column (org-get-indentation))))))
26915 (goto-char pos)
26916 (if (<= (current-column) (current-indentation))
26917 (indent-line-to column)
26918 (save-excursion (indent-line-to column)))
26919 (setq column (current-column))
26920 (beginning-of-line 1)
26921 (if (looking-at
26922 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26923 (replace-match (concat "\\1" (format org-property-format
26924 (match-string 2) (match-string 3)))
26925 t nil))
26926 (move-to-column column)))
26928 (defun org-set-autofill-regexps ()
26929 (interactive)
26930 ;; In the paragraph separator we include headlines, because filling
26931 ;; text in a line directly attached to a headline would otherwise
26932 ;; fill the headline as well.
26933 (org-set-local 'comment-start-skip "^#+[ \t]*")
26934 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26935 ;; The paragraph starter includes hand-formatted lists.
26936 (org-set-local 'paragraph-start
26937 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26938 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26939 ;; But only if the user has not turned off tables or fixed-width regions
26940 (org-set-local
26941 'auto-fill-inhibit-regexp
26942 (concat "\\*+ \\|#\\+"
26943 "\\|[ \t]*" org-keyword-time-regexp
26944 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26945 (concat
26946 "\\|[ \t]*["
26947 (if org-enable-table-editor "|" "")
26948 (if org-enable-fixed-width-editor ":" "")
26949 "]"))))
26950 ;; We use our own fill-paragraph function, to make sure that tables
26951 ;; and fixed-width regions are not wrapped. That function will pass
26952 ;; through to `fill-paragraph' when appropriate.
26953 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26954 ; Adaptive filling: To get full control, first make sure that
26955 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26956 (org-set-local 'adaptive-fill-regexp "\000")
26957 (org-set-local 'adaptive-fill-function
26958 'org-adaptive-fill-function))
26960 (defun org-fill-paragraph (&optional justify)
26961 "Re-align a table, pass through to fill-paragraph if no table."
26962 (let ((table-p (org-at-table-p))
26963 (table.el-p (org-at-table.el-p)))
26964 (cond ((and (equal (char-after (point-at-bol)) ?*)
26965 (save-excursion (goto-char (point-at-bol))
26966 (looking-at outline-regexp)))
26967 t) ; skip headlines
26968 (table.el-p t) ; skip table.el tables
26969 (table-p (org-table-align) t) ; align org-mode tables
26970 (t nil)))) ; call paragraph-fill
26972 ;; For reference, this is the default value of adaptive-fill-regexp
26973 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26975 (defun org-adaptive-fill-function ()
26976 "Return a fill prefix for org-mode files.
26977 In particular, this makes sure hanging paragraphs for hand-formatted lists
26978 work correctly."
26979 (cond ((looking-at "#[ \t]+")
26980 (match-string 0))
26981 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26982 (save-excursion
26983 (goto-char (match-end 0))
26984 (make-string (current-column) ?\ )))
26985 (t nil)))
26987 ;;;; Functions extending outline functionality
26989 (defun org-beginning-of-line (&optional arg)
26990 "Go to the beginning of the current line. If that is invisible, continue
26991 to a visible line beginning. This makes the function of C-a more intuitive.
26992 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26993 first attempt, and only move to after the tags when the cursor is already
26994 beyond the end of the headline."
26995 (interactive "P")
26996 (let ((pos (point)))
26997 (beginning-of-line 1)
26998 (if (bobp)
27000 (backward-char 1)
27001 (if (org-invisible-p)
27002 (while (and (not (bobp)) (org-invisible-p))
27003 (backward-char 1)
27004 (beginning-of-line 1))
27005 (forward-char 1)))
27006 (when org-special-ctrl-a/e
27007 (cond
27008 ((and (looking-at org-todo-line-regexp)
27009 (= (char-after (match-end 1)) ?\ ))
27010 (goto-char
27011 (if (eq org-special-ctrl-a/e t)
27012 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27013 ((= pos (point)) (match-beginning 3))
27014 (t (point)))
27015 (cond ((> pos (point)) (point))
27016 ((not (eq last-command this-command)) (point))
27017 (t (match-beginning 3))))))
27018 ((org-at-item-p)
27019 (goto-char
27020 (if (eq org-special-ctrl-a/e t)
27021 (cond ((> pos (match-end 4)) (match-end 4))
27022 ((= pos (point)) (match-end 4))
27023 (t (point)))
27024 (cond ((> pos (point)) (point))
27025 ((not (eq last-command this-command)) (point))
27026 (t (match-end 4))))))))))
27028 (defun org-end-of-line (&optional arg)
27029 "Go to the end of the line.
27030 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27031 first attempt, and only move to after the tags when the cursor is already
27032 beyond the end of the headline."
27033 (interactive "P")
27034 (if (or (not org-special-ctrl-a/e)
27035 (not (org-on-heading-p)))
27036 (end-of-line arg)
27037 (let ((pos (point)))
27038 (beginning-of-line 1)
27039 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27040 (if (eq org-special-ctrl-a/e t)
27041 (if (or (< pos (match-beginning 1))
27042 (= pos (match-end 0)))
27043 (goto-char (match-beginning 1))
27044 (goto-char (match-end 0)))
27045 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27046 (goto-char (match-end 0))
27047 (goto-char (match-beginning 1))))
27048 (end-of-line arg)))))
27050 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27051 (define-key org-mode-map "\C-e" 'org-end-of-line)
27053 (defun org-invisible-p ()
27054 "Check if point is at a character currently not visible."
27055 ;; Early versions of noutline don't have `outline-invisible-p'.
27056 (if (fboundp 'outline-invisible-p)
27057 (outline-invisible-p)
27058 (get-char-property (point) 'invisible)))
27060 (defun org-invisible-p2 ()
27061 "Check if point is at a character currently not visible."
27062 (save-excursion
27063 (if (and (eolp) (not (bobp))) (backward-char 1))
27064 ;; Early versions of noutline don't have `outline-invisible-p'.
27065 (if (fboundp 'outline-invisible-p)
27066 (outline-invisible-p)
27067 (get-char-property (point) 'invisible))))
27069 (defalias 'org-back-to-heading 'outline-back-to-heading)
27070 (defalias 'org-on-heading-p 'outline-on-heading-p)
27071 (defalias 'org-at-heading-p 'outline-on-heading-p)
27072 (defun org-at-heading-or-item-p ()
27073 (or (org-on-heading-p) (org-at-item-p)))
27075 (defun org-on-target-p ()
27076 (or (org-in-regexp org-radio-target-regexp)
27077 (org-in-regexp org-target-regexp)))
27079 (defun org-up-heading-all (arg)
27080 "Move to the heading line of which the present line is a subheading.
27081 This function considers both visible and invisible heading lines.
27082 With argument, move up ARG levels."
27083 (if (fboundp 'outline-up-heading-all)
27084 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27085 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27087 (defun org-up-heading-safe ()
27088 "Move to the heading line of which the present line is a subheading.
27089 This version will not throw an error. It will return the level of the
27090 headline found, or nil if no higher level is found."
27091 (let ((pos (point)) start-level level
27092 (re (concat "^" outline-regexp)))
27093 (catch 'exit
27094 (outline-back-to-heading t)
27095 (setq start-level (funcall outline-level))
27096 (if (equal start-level 1) (throw 'exit nil))
27097 (while (re-search-backward re nil t)
27098 (setq level (funcall outline-level))
27099 (if (< level start-level) (throw 'exit level)))
27100 nil)))
27102 (defun org-goto-sibling (&optional previous)
27103 "Goto the next sibling, even if it is invisible.
27104 When PREVIOUS is set, go to the previous sibling instead. Returns t
27105 when a sibling was found. When none is found, return nil and don't
27106 move point."
27107 (let ((fun (if previous 're-search-backward 're-search-forward))
27108 (pos (point))
27109 (re (concat "^" outline-regexp))
27110 level l)
27111 (when (condition-case nil (org-back-to-heading t) (error nil))
27112 (setq level (funcall outline-level))
27113 (catch 'exit
27114 (or previous (forward-char 1))
27115 (while (funcall fun re nil t)
27116 (setq l (funcall outline-level))
27117 (when (< l level) (goto-char pos) (throw 'exit nil))
27118 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27119 (goto-char pos)
27120 nil))))
27122 (defun org-show-siblings ()
27123 "Show all siblings of the current headline."
27124 (save-excursion
27125 (while (org-goto-sibling) (org-flag-heading nil)))
27126 (save-excursion
27127 (while (org-goto-sibling 'previous)
27128 (org-flag-heading nil))))
27130 (defun org-show-hidden-entry ()
27131 "Show an entry where even the heading is hidden."
27132 (save-excursion
27133 (org-show-entry)))
27135 (defun org-flag-heading (flag &optional entry)
27136 "Flag the current heading. FLAG non-nil means make invisible.
27137 When ENTRY is non-nil, show the entire entry."
27138 (save-excursion
27139 (org-back-to-heading t)
27140 ;; Check if we should show the entire entry
27141 (if entry
27142 (progn
27143 (org-show-entry)
27144 (save-excursion
27145 (and (outline-next-heading)
27146 (org-flag-heading nil))))
27147 (outline-flag-region (max (point-min) (1- (point)))
27148 (save-excursion (outline-end-of-heading) (point))
27149 flag))))
27151 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27152 ;; This is an exact copy of the original function, but it uses
27153 ;; `org-back-to-heading', to make it work also in invisible
27154 ;; trees. And is uses an invisible-OK argument.
27155 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27156 (org-back-to-heading invisible-OK)
27157 (let ((first t)
27158 (level (funcall outline-level)))
27159 (while (and (not (eobp))
27160 (or first (> (funcall outline-level) level)))
27161 (setq first nil)
27162 (outline-next-heading))
27163 (unless to-heading
27164 (if (memq (preceding-char) '(?\n ?\^M))
27165 (progn
27166 ;; Go to end of line before heading
27167 (forward-char -1)
27168 (if (memq (preceding-char) '(?\n ?\^M))
27169 ;; leave blank line before heading
27170 (forward-char -1))))))
27171 (point))
27173 (defun org-show-subtree ()
27174 "Show everything after this heading at deeper levels."
27175 (outline-flag-region
27176 (point)
27177 (save-excursion
27178 (outline-end-of-subtree) (outline-next-heading) (point))
27179 nil))
27181 (defun org-show-entry ()
27182 "Show the body directly following this heading.
27183 Show the heading too, if it is currently invisible."
27184 (interactive)
27185 (save-excursion
27186 (condition-case nil
27187 (progn
27188 (org-back-to-heading t)
27189 (outline-flag-region
27190 (max (point-min) (1- (point)))
27191 (save-excursion
27192 (re-search-forward
27193 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27194 (or (match-beginning 1) (point-max)))
27195 nil))
27196 (error nil))))
27198 (defun org-make-options-regexp (kwds)
27199 "Make a regular expression for keyword lines."
27200 (concat
27202 "#?[ \t]*\\+\\("
27203 (mapconcat 'regexp-quote kwds "\\|")
27204 "\\):[ \t]*"
27205 "\\(.+\\)"))
27207 ;; Make isearch reveal the necessary context
27208 (defun org-isearch-end ()
27209 "Reveal context after isearch exits."
27210 (when isearch-success ; only if search was successful
27211 (if (featurep 'xemacs)
27212 ;; Under XEmacs, the hook is run in the correct place,
27213 ;; we directly show the context.
27214 (org-show-context 'isearch)
27215 ;; In Emacs the hook runs *before* restoring the overlays.
27216 ;; So we have to use a one-time post-command-hook to do this.
27217 ;; (Emacs 22 has a special variable, see function `org-mode')
27218 (unless (and (boundp 'isearch-mode-end-hook-quit)
27219 isearch-mode-end-hook-quit)
27220 ;; Only when the isearch was not quitted.
27221 (org-add-hook 'post-command-hook 'org-isearch-post-command
27222 'append 'local)))))
27224 (defun org-isearch-post-command ()
27225 "Remove self from hook, and show context."
27226 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27227 (org-show-context 'isearch))
27230 ;;;; Integration with and fixes for other packages
27232 ;;; Imenu support
27234 (defvar org-imenu-markers nil
27235 "All markers currently used by Imenu.")
27236 (make-variable-buffer-local 'org-imenu-markers)
27238 (defun org-imenu-new-marker (&optional pos)
27239 "Return a new marker for use by Imenu, and remember the marker."
27240 (let ((m (make-marker)))
27241 (move-marker m (or pos (point)))
27242 (push m org-imenu-markers)
27245 (defun org-imenu-get-tree ()
27246 "Produce the index for Imenu."
27247 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27248 (setq org-imenu-markers nil)
27249 (let* ((n org-imenu-depth)
27250 (re (concat "^" outline-regexp))
27251 (subs (make-vector (1+ n) nil))
27252 (last-level 0)
27253 m tree level head)
27254 (save-excursion
27255 (save-restriction
27256 (widen)
27257 (goto-char (point-max))
27258 (while (re-search-backward re nil t)
27259 (setq level (org-reduced-level (funcall outline-level)))
27260 (when (<= level n)
27261 (looking-at org-complex-heading-regexp)
27262 (setq head (org-match-string-no-properties 4)
27263 m (org-imenu-new-marker))
27264 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27265 (if (>= level last-level)
27266 (push (cons head m) (aref subs level))
27267 (push (cons head (aref subs (1+ level))) (aref subs level))
27268 (loop for i from (1+ level) to n do (aset subs i nil)))
27269 (setq last-level level)))))
27270 (aref subs 1)))
27272 (eval-after-load "imenu"
27273 '(progn
27274 (add-hook 'imenu-after-jump-hook
27275 (lambda () (org-show-context 'org-goto)))))
27277 ;; Speedbar support
27279 (defun org-speedbar-set-agenda-restriction ()
27280 "Restrict future agenda commands to the location at point in speedbar.
27281 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27282 (interactive)
27283 (let (p m tp np dir txt w)
27284 (cond
27285 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27286 'org-imenu t))
27287 (setq m (get-text-property p 'org-imenu-marker))
27288 (save-excursion
27289 (save-restriction
27290 (set-buffer (marker-buffer m))
27291 (goto-char m)
27292 (org-agenda-set-restriction-lock 'subtree))))
27293 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27294 'speedbar-function 'speedbar-find-file))
27295 (setq tp (previous-single-property-change
27296 (1+ p) 'speedbar-function)
27297 np (next-single-property-change
27298 tp 'speedbar-function)
27299 dir (speedbar-line-directory)
27300 txt (buffer-substring-no-properties (or tp (point-min))
27301 (or np (point-max))))
27302 (save-excursion
27303 (save-restriction
27304 (set-buffer (find-file-noselect
27305 (let ((default-directory dir))
27306 (expand-file-name txt))))
27307 (unless (org-mode-p)
27308 (error "Cannot restrict to non-Org-mode file"))
27309 (org-agenda-set-restriction-lock 'file))))
27310 (t (error "Don't know how to restrict Org-mode's agenda")))
27311 (org-move-overlay org-speedbar-restriction-lock-overlay
27312 (point-at-bol) (point-at-eol))
27313 (setq current-prefix-arg nil)
27314 (org-agenda-maybe-redo)))
27316 (eval-after-load "speedbar"
27317 '(progn
27318 (speedbar-add-supported-extension ".org")
27319 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27320 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27321 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27322 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27323 (add-hook 'speedbar-visiting-tag-hook
27324 (lambda () (org-show-context 'org-goto)))))
27327 ;;; Fixes and Hacks
27329 ;; Make flyspell not check words in links, to not mess up our keymap
27330 (defun org-mode-flyspell-verify ()
27331 "Don't let flyspell put overlays at active buttons."
27332 (not (get-text-property (point) 'keymap)))
27334 ;; Make `bookmark-jump' show the jump location if it was hidden.
27335 (eval-after-load "bookmark"
27336 '(if (boundp 'bookmark-after-jump-hook)
27337 ;; We can use the hook
27338 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27339 ;; Hook not available, use advice
27340 (defadvice bookmark-jump (after org-make-visible activate)
27341 "Make the position visible."
27342 (org-bookmark-jump-unhide))))
27344 (defun org-bookmark-jump-unhide ()
27345 "Unhide the current position, to show the bookmark location."
27346 (and (org-mode-p)
27347 (or (org-invisible-p)
27348 (save-excursion (goto-char (max (point-min) (1- (point))))
27349 (org-invisible-p)))
27350 (org-show-context 'bookmark-jump)))
27352 ;; Fix a bug in htmlize where there are text properties (face nil)
27353 (eval-after-load "htmlize"
27354 '(progn
27355 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
27356 "Make sure there are no nil faces"
27357 (setq ad-return-value (delq nil ad-return-value)))))
27359 ;; Make session.el ignore our circular variable
27360 (eval-after-load "session"
27361 '(add-to-list 'session-globals-exclude 'org-mark-ring))
27363 ;;;; Experimental code
27365 (defun org-closed-in-range ()
27366 "Sparse tree of items closed in a certain time range.
27367 Still experimental, may disappear in the future."
27368 (interactive)
27369 ;; Get the time interval from the user.
27370 (let* ((time1 (time-to-seconds
27371 (org-read-date nil 'to-time nil "Starting date: ")))
27372 (time2 (time-to-seconds
27373 (org-read-date nil 'to-time nil "End date:")))
27374 ;; callback function
27375 (callback (lambda ()
27376 (let ((time
27377 (time-to-seconds
27378 (apply 'encode-time
27379 (org-parse-time-string
27380 (match-string 1))))))
27381 ;; check if time in interval
27382 (and (>= time time1) (<= time time2))))))
27383 ;; make tree, check each match with the callback
27384 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
27386 ;;;; Finish up
27388 (provide 'org)
27390 (run-hooks 'org-load-hook)
27392 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27393 ;;; org.el ends here