1;;; mail-hist.el --- headers and message body history for outgoing mail
2
3;; Copyright (C) 1994, 2001, 2002, 2003, 2004, 2005,
4;;   2006, 2007 Free Software Foundation, Inc.
5
6;; Author: Karl Fogel <kfogel@red-bean.com>
7;; Created: March, 1994
8;; Keywords: mail, history
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 2, or (at your option)
15;; any later version.
16
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.
21
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
27;;; Commentary:
28
29;; Thanks to Jim Blandy for mentioning ring.el.  It saved a lot of
30;; time.
31;;
32;; To use this package, put it in a directory in your load-path, and
33;; put this in your .emacs file:
34;;
35;; (load "mail-hist" nil t)
36;;
37;; Or you could do it with autoloads and hooks in your .emacs:
38;;
39;; (add-hook 'mail-mode-hook 'mail-hist-define-keys)
40;; (add-hook 'mail-send-hook 'mail-hist-put-headers-into-history)
41;; (add-hook 'vm-mail-mode-hook 'mail-hist-define-keys) ;or rmail, etc
42;; (autoload 'mail-hist-define-keys "mail-hist")
43;; (autoload 'mail-hist-put-headers-into-history "mail-hist")
44;;
45;; Once it's installed, use M-p and M-n from mail headers to recover
46;; previous/next contents in the history for that header, or, in the
47;; body of the message, to recover previous/next text of the message.
48;; This only applies to outgoing mail -- mail-hist ignores received
49;; messages.
50;;
51;; Although repeated history requests do clear out the text from the
52;; previous request, an isolated request just inserts its text at
53;; point, so that you can mix the histories of different messages
54;; easily.  This might be confusing at times, but there should be no
55;; problems that undo can't handle.
56
57;;; Code:
58(require 'ring)
59(require 'sendmail)
60
61(defgroup mail-hist nil
62  "Headers and message body history for outgoing mail."
63  :prefix "mail-hist-"
64  :group 'mail)
65
66;;;###autoload
67(defun mail-hist-define-keys ()
68  "Define keys for accessing mail header history.  For use in hooks."
69  (local-set-key "\M-p" 'mail-hist-previous-input)
70  (local-set-key "\M-n" 'mail-hist-next-input))
71
72;;;###autoload
73(defun mail-hist-enable ()
74  (add-hook 'mail-mode-hook 'mail-hist-define-keys)
75  (add-hook 'mail-send-hook 'mail-hist-put-headers-into-history))
76
77(defvar mail-hist-header-ring-alist nil
78  "Alist of form (header-name . history-ring).
79Used for knowing which history list to look in when the user asks for
80previous/next input.")
81
82(defcustom mail-hist-history-size (or kill-ring-max 1729)
83  "*The maximum number of elements in a mail field's history.
84Oldest elements are dumped first."
85  :type 'integer
86  :group 'mail-hist)
87
88;;;###autoload
89(defcustom mail-hist-keep-history t
90  "*Non-nil means keep a history for headers and text of outgoing mail."
91  :type 'boolean
92  :group 'mail-hist)
93
94;; For handling repeated history requests
95(defvar mail-hist-access-count 0)
96
97(defvar mail-hist-last-bounds nil)
98;; (start . end) A pair indicating the buffer positions delimiting the
99;; last inserted history, so it can be replaced by a new input if the
100;; command is repeated.
101
102(defvar mail-hist-header-regexp "^[^:]*:"
103  "Regular expression for matching headers in a mail message.")
104
105(defsubst mail-hist-current-header-name ()
106  "Get name of mail header point is currently in, without the colon.
107Returns nil if not in a header, implying that point is in the body of
108the message."
109  (if (>= (point) (mail-text-start))
110      nil ; then we are in the body of the message
111    (save-excursion
112      (let* ((body-start
113	      (mail-text-start))
114             (name-start
115              (re-search-backward mail-hist-header-regexp nil t))
116             (name-end
117              (prog2 (search-forward ":" body-start t) (1- (point)))))
118        (and
119         name-start
120         name-end
121         (downcase (buffer-substring-no-properties name-start name-end)))))))
122
123(defsubst mail-hist-forward-header (count)
124  "Move forward COUNT headers (backward if COUNT is negative).
125If last/first header is encountered first, stop there and returns
126nil.
127
128Places point on the first non-whitespace on the line following the
129colon after the header name, or on the second space following that if
130the header is empty."
131  (let ((boundary (mail-header-end)))
132    (and
133     (> boundary 0)
134     (let ((unstopped t))
135       (setq boundary (save-excursion
136                    (goto-char boundary)
137                    (beginning-of-line)
138                    (1- (point))))
139       (if (> count 0)
140           (while (> count 0)
141             (setq
142              unstopped
143              (re-search-forward mail-hist-header-regexp boundary t))
144             (setq count (1- count)))
145         ;; because the current header will match too.
146         (setq count (1- count))
147         ;; count is negative
148         (while (< count 0)
149           (setq
150            unstopped
151            (re-search-backward mail-hist-header-regexp nil t))
152           (setq count (1+ count)))
153         ;; we end up behind the header, so must move to the front
154         (re-search-forward mail-hist-header-regexp boundary t))
155       ;; Now we are right after the colon
156       (and (looking-at "\\s-") (forward-char 1))
157       ;; return nil if didn't go as far as asked, otherwise point
158       unstopped))))
159
160(defsubst mail-hist-beginning-of-header ()
161  "Move to the start of the current header.
162The start of the current header is defined as one space after the
163colon, or just after the colon if it is not followed by whitespace."
164  ;; this is slick as all heck:
165  (if (mail-hist-forward-header -1)
166      (mail-hist-forward-header 1)
167    (mail-hist-forward-header 1)
168    (mail-hist-forward-header -1)))
169
170(defsubst mail-hist-current-header-contents ()
171  "Get the contents of the mail header in which point is located."
172  (save-excursion
173    (mail-hist-beginning-of-header)
174    (let ((start (point)))
175      (or (mail-hist-forward-header 1)
176          (goto-char (mail-header-end)))
177      (beginning-of-line)
178      (buffer-substring start (1- (point))))))
179
180(defsubst mail-hist-get-header-ring (header)
181  "Get HEADER's history ring, or nil if none.
182HEADER is a string without the colon."
183  (setq header (downcase header))
184  (cdr (assoc header mail-hist-header-ring-alist)))
185
186(defcustom mail-hist-text-size-limit nil
187  "*Don't store any header or body with more than this many characters.
188If the value is nil, that means no limit on text size."
189  :type '(choice (const nil) integer)
190  :group 'mail-hist)
191
192(defun mail-hist-text-too-long-p (text)
193  "Return non-nil if TEXT's length exceeds `mail-hist-text-size-limit'."
194  (if mail-hist-text-size-limit
195      (> (length text) mail-hist-text-size-limit)))
196
197(defsubst mail-hist-add-header-contents-to-ring (header &optional contents)
198  "Add the contents of HEADER to the header history ring.
199Optional argument CONTENTS is a string which will be the contents
200\(instead of whatever's found in the header)."
201  (setq header (downcase header))
202  (let ((ctnts (or contents (mail-hist-current-header-contents)))
203        (ring  (cdr (assoc header mail-hist-header-ring-alist))))
204    (if (mail-hist-text-too-long-p ctnts) (setq ctnts ""))
205    (or ring
206        ;; If the ring doesn't exist, we'll have to make it and add it
207        ;; to the mail-header-ring-alist:
208        (prog1
209            (setq ring (make-ring mail-hist-history-size))
210          (setq mail-hist-header-ring-alist
211                (cons (cons header ring) mail-hist-header-ring-alist))))
212    (ring-insert ring ctnts)))
213
214;;;###autoload
215(defun mail-hist-put-headers-into-history ()
216  "Put headers and contents of this message into mail header history.
217Each header has its own independent history, as does the body of the
218message.
219
220This function normally would be called when the message is sent."
221  (and
222   mail-hist-keep-history
223   (save-excursion
224     (goto-char (point-min))
225     (while (mail-hist-forward-header 1)
226       (mail-hist-add-header-contents-to-ring
227        (mail-hist-current-header-name)))
228     (let ((body-contents
229	    (buffer-substring (mail-text-start) (point-max))))
230       (mail-hist-add-header-contents-to-ring "body" body-contents)))))
231
232
233
234(defun mail-hist-retrieve-and-insert (header access-func)
235  "Helper for `mail-hist-previous-input' and `mail-hist-next-input'."
236  (setq header (downcase header))
237  (let* ((ring (cdr (assoc header mail-hist-header-ring-alist)))
238         (len (ring-length ring))
239         (repeat (eq last-command 'mail-hist-input-access)))
240    (if repeat
241        (setq mail-hist-access-count
242              (funcall access-func mail-hist-access-count len))
243      (setq mail-hist-access-count 0))
244    (if (null ring)
245        (progn
246          (ding)
247          (message "No history for \"%s\"." header))
248      (if (ring-empty-p ring)
249          (error "\"%s\" ring is empty" header)
250        (and repeat
251             (delete-region (car mail-hist-last-bounds)
252                            (cdr mail-hist-last-bounds)))
253        (let ((start (point)))
254          (insert (ring-ref ring mail-hist-access-count))
255          (setq mail-hist-last-bounds (cons start (point)))
256          (setq this-command 'mail-hist-input-access)
257          ;; Special case: when flipping through message bodies, it's
258          ;; usually most useful for point to stay at the top.  This
259          ;; is because the unique part of a message in a thread is
260          ;; more likely to be at the top than the bottom, as the
261          ;; bottom is often just the same quoted history for every
262          ;; message in the thread, differing only in indentation
263          ;; level.
264          (if (string-equal header "body")
265              (goto-char start)))
266        ))))
267
268
269(defun mail-hist-previous-input (header)
270  "Insert the previous contents of this mail header or message body.
271Moves back through the history of sent mail messages.  Each header has
272its own independent history, as does the body of the message.
273
274The history only contains the contents of outgoing messages, not
275received mail."
276  (interactive (list (or (mail-hist-current-header-name) "body")))
277  (mail-hist-retrieve-and-insert header 'ring-plus1))
278
279
280(defun mail-hist-next-input (header)
281  "Insert next contents of this mail header or message body.
282Moves back through the history of sent mail messages.  Each header has
283its own independent history, as does the body of the message.
284
285Although you can do so, it does not make much sense to call this
286without having called `mail-hist-previous-header' first
287\(\\[mail-hist-previous-header]).
288
289The history only contains the contents of outgoing messages, not
290received mail."
291  (interactive (list (or (mail-hist-current-header-name) "body")))
292  (mail-hist-retrieve-and-insert header 'ring-minus1))
293
294
295(provide 'mail-hist)
296
297;;; arch-tag: 9ff9a07c-9dca-482d-ba87-54f42778559d
298;;; mail-hist.el ends here
299