*** empty log message ***
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile 
33   (require 'cl))
34 (require 'mail-header)
35 (require 'nnheader)
36 (require 'timezone)
37
38 ;;;###autoload
39 (defvar message-fcc-handler-function 'rmail-output
40   "*A function called to save outgoing articles.
41 This function will be called with the name of the file to store the
42 article in. The default function is `rmail-output' which saves in Unix
43 mailbox format.")
44
45 ;;;###autoload
46 (defvar message-courtesy-message
47   "The following message is a courtesy copy of an article\nthat has been posted as well.\n\n"
48   "*This is inserted at the start of a mailed copy of a posted message.
49 If this variable is nil, no such courtesy message will be added.")
50
51 ;;;###autoload
52 (defvar message-ignored-bounced-headers "^\\(Received\\):"
53   "*Regexp that matches headers to be removed in resent bounced mail.")
54
55 ;;;###autoload
56 (defvar message-from-style 'default
57   "*Specifies how \"From\" headers look.
58
59 If `nil', they contain just the return address like:
60         king@grassland.com
61 If `parens', they look like:
62         king@grassland.com (Elvis Parsley)
63 If `angles', they look like:
64         Elvis Parsley <king@grassland.com>
65
66 Otherwise, most addresses look like `angles', but they look like
67 `parens' if `angles' would need quoting and `parens' would not.")
68
69 ;;;###autoload
70 (defvar message-syntax-checks
71   '(subject-cmsg multiple-headers sendsys message-id from
72                  long-lines control-chars size new-text
73                  redirected-followup signature approved sender 
74                  empty empty-headers message-id from subject)
75   "In non-nil, message will attempt to run some checks on outgoing posts.
76 If this variable is t, message will check everything it can.  If it is
77 a list, then those elements in that list will be checked.")
78
79 ;;;###autoload
80 (defvar message-required-news-headers
81   '(From Date Newsgroups Subject Message-ID 
82          (optional . Organization) Lines 
83          (optional . X-Newsreader))
84   "*Headers to be generated or prompted for when posting an article.
85 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
86 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
87 X-Newsreader are optional.  If don't you want message to insert some
88 header, remove it from this list.")
89
90 ;;;###autoload
91 (defvar message-required-mail-headers 
92   '(From Date Subject (optional . In-Reply-To) Message-ID Lines
93          (optional . X-Mailer))
94   "*Headers to be generated or prompted for when mailing a message.
95 RFC822 required that From, Date, To, Subject and Message-ID be
96 included.  Organization, Lines and X-Mailer are optional.")
97
98 ;;;###autoload
99 (defvar message-deletable-headers '(Message-ID Date)
100   "*Headers to be deleted if they already exist and were generated by message previously.")
101
102 ;;;###autoload
103 (defvar message-ignored-news-headers 
104   "^NNTP-Posting-Host:\\|^Xref:\\|^Bcc:\\|^Gcc:\\|^Fcc:"
105   "*Regexp of headers to be removed unconditionally before posting.")
106
107 ;;;###autoload
108 (defvar message-ignored-mail-headers "^Gcc:\\|^Fcc:"
109   "*Regexp of headers to be removed unconditionally before mailing.")
110
111 ;;;###autoload
112 (defvar message-ignored-supersedes-headers
113   "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|Return-Path:"
114   "*Header lines matching this regexp will be deleted before posting.
115 It's best to delete old Path and Date headers before posting to avoid
116 any confusion.")
117
118 ;;;###autoload
119 (defvar message-signature-separator "^-- *$"
120   "Regexp matching the signature separator.")
121
122 ;;;###autoload
123 (defvar message-interactive nil 
124   "Non-nil means when sending a message wait for and display errors.
125 nil means let mailer mail back a message to report errors.")
126
127 (defvar gnus-local-organization)
128 ;;;###autoload
129 (defvar message-user-organization 
130   (or (and (boundp 'gnus-local-organization)
131            gnus-local-organization)
132       (getenv "ORGANIZATION")
133       t)
134   "*String to be used as an Organization header.
135 If t, use `message-user-organization-file'.")
136
137 ;;;###autoload
138 (defvar message-user-organization-file "/usr/lib/news/organization"
139   "*Local news organization file.")
140
141 ;;;###autoload
142 (defvar message-autosave-directory "~/Mail/drafts/"
143   "*Directory where message autosaves buffers.
144 If nil, message won't autosave.")
145
146 (defvar message-forward-start-separator 
147   "------- Start of forwarded message -------\n"
148   "*Delimiter inserted before forwarded messages.")
149
150 (defvar message-forward-end-separator
151   "------- End of forwarded message -------\n"
152   "*Delimiter inserted after forwarded messages.")
153
154 ;;;###autoload
155 (defvar message-signature-before-forwarded-message t
156   "*If non-nil, put the signature before any included forwarded message.")
157
158 ;;;###autoload
159 (defvar message-included-forward-headers 
160   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^Followup-To:\\|^Reply-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Mail-Copies-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:"
161   "*Regexp matching headers to be included in forwarded messages.")
162
163 ;;;###autoload
164 (defvar message-ignored-resent-headers "^Return-receipt"
165   "*All headers that match this regexp will be deleted when resending a message.")
166
167 ;;;###autoload
168 (defvar message-ignored-cited-headers "."
169   "Delete these headers from the messages you yank.")
170
171 ;; Useful to set in site-init.el
172 ;;;###autoload
173 (defvar message-send-mail-function 'message-send-mail 
174   "Function to call to send the current buffer as mail.
175 The headers should be delimited by a line whose contents match the
176 variable `mail-header-separator'.")
177
178 ;;;###autoload
179 (defvar message-send-news-function 'message-send-news
180   "Function to call to send the current buffer as news.
181 The headers should be delimited by a line whose contents match the
182 variable `message-header-separator'.")
183
184 ;;;###autoload
185 (defvar message-reply-to-function nil
186   "Function that should return a list of headers.")
187
188 ;;;###autoload
189 (defvar message-wide-reply-to-function nil
190   "Function that should return a list of headers.")
191
192 ;;;###autoload
193 (defvar message-followup-to-function nil
194   "Function that should return a list of headers.")
195
196 ;;;###autoload
197 (defvar message-use-followup-to 'ask
198   "*Specifies what to do with Followup-To header.
199 If nil, ignore the header. If it is t, use its value, but ignore
200 \"poster\".  If it is the symbol `ask', query the user whether to
201 ignore the \"poster\" value.  If it is the symbol `use', always use
202 the value.")
203
204 (defvar gnus-post-method)
205 (defvar gnus-select-method)
206 ;;;###autoload
207 (defvar message-post-method 
208   (cond ((boundp 'gnus-post-method)
209          gnus-post-method)
210         ((boundp 'gnus-select-method)
211          gnus-select-method)
212         (t '(nnspool "")))
213   "Method used to post news.")
214
215 ;;;###autoload
216 (defvar message-generate-headers-first nil
217   "*If non-nil, generate all possible headers before composing.")
218
219 ;;;###autoload
220 (defvar message-header-separator "--text follows this line--" 
221   "*Line used to separate headers from text in messages being composed.")
222
223 (defvar message-setup-hook nil
224   "Normal hook, run each time a new outgoing message is initialized.
225 The function `message-setup' runs this hook.")
226
227 (defvar message-header-setup-hook nil
228   "Hook called narrowed to the headers when setting up a message buffer.")
229
230 ;;;###autoload
231 (defvar message-citation-line-function 'message-insert-citation-line
232   "*Function called to insert the \"Whomever writes:\" line.")
233
234 ;;;###autoload
235 (defvar message-yank-prefix "> "
236   "*Prefix inserted on the lines of yanked messages.
237 nil means use indentation.")
238
239 (defvar message-indentation-spaces 3
240   "*Number of spaces to insert at the beginning of each cited line.
241 Used by `message-yank-original' via `message-yank-cite'.")
242
243 ;;;###autoload
244 (defvar message-cite-function 'message-cite-original
245   "*Function for citing an original message.")
246
247 ;;;###autoload
248 (defvar message-indent-citation-function 'message-indent-citation
249   "*Function for modifying a citation just inserted in the mail buffer.
250 This can also be a list of functions.  Each function can find the
251 citation between (point) and (mark t).  And each function should leave
252 point and mark around the citation text as modified.")
253
254 (defvar message-abbrevs-loaded nil)
255
256 ;;;###autoload
257 (defvar message-signature t
258   "*String to be inserted at the end of the message buffer.
259 If t, the `message-signature-file' file will be inserted instead.
260 If a function, the result from the function will be used instead.
261 If a form, the result from the form will be used instead.")
262
263 ;;;###autoload
264 (defvar message-signature-file "~/.signature"
265   "*File containing the text inserted at end of message. buffer.")
266
267 (defvar message-distribution-function nil
268   "*Function called to return a Distribution header.")
269
270 (defvar message-expires 14
271   "*Number of days before your article expires.")
272
273 (defvar message-user-path nil
274   "If nil, use the NNTP server name in the Path header.
275 If stringp, use this; if non-nil, use no host name (user name only).")
276
277 (defvar message-reply-buffer nil)
278 (defvar message-reply-headers nil)
279 (defvar message-newsreader nil)
280 (defvar message-mailer nil)
281 (defvar message-sent-message-via nil)
282 (defvar message-checksum nil)
283 (defvar message-send-actions nil
284   "A list of actions to be performed upon successful sending of a message.")
285
286 ;;;###autoload
287 (defvar message-default-headers nil
288   "*A string containing header lines to be inserted in outgoing messages.
289 It is inserted before you edit the message, so you can edit or delete
290 these lines.")
291
292 ;;;###autoload
293 (defvar message-default-mail-headers nil
294   "*A string of header lines to be inserted in outgoing mails.")
295
296 ;;;###autoload
297 (defvar message-default-news-headers nil
298   "*A string of header lines to be inserted in outgoing news articles.")
299
300 ;; Note: could use /usr/ucb/mail instead of sendmail;
301 ;; options -t, and -v if not interactive.
302 (defvar message-mailer-swallows-blank-line
303   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)" 
304                          system-configuration)
305            (file-readable-p "/etc/sendmail.cf")
306            (let ((buffer (get-buffer-create " *temp*")))
307              (unwind-protect
308                  (save-excursion
309                    (set-buffer buffer)
310                    (insert-file-contents "/etc/sendmail.cf")
311                    (goto-char (point-min))
312                    (let ((case-fold-search nil))
313                      (re-search-forward "^OR\\>" nil t)))
314                (kill-buffer buffer))))
315       ;; According to RFC822, "The field-name must be composed of printable
316       ;; ASCII characters (i.e. characters that have decimal values between
317       ;; 33 and 126, except colon)", i.e. any chars except ctl chars,
318       ;; space, or colon.
319       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
320   "Set this non-nil if the system's mailer runs the header and body together.
321 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
322 The value should be an expression to test whether the problem will
323 actually occur.")
324
325 (defvar message-mode-syntax-table 
326   (let ((table (copy-syntax-table text-mode-syntax-table)))
327     (modify-syntax-entry ?% ". " table)
328     table)
329   "Syntax table used while in Message mode.")
330
331 (defvar message-font-lock-keywords
332   (let* ((cite-prefix "A-Za-z") (cite-suffix (concat cite-prefix "0-9_.@-")))
333     (list '("^To:" . font-lock-function-name-face)
334           '("^B?CC:\\|^Reply-To:" . font-lock-keyword-face)
335           '("^\\(Subject:\\)[ \t]*\\(.+\\)?"
336             (1 font-lock-comment-face) (2 font-lock-type-face nil t))
337           (list (concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
338                 1 'font-lock-comment-face)
339           (cons (concat "^[ \t]*"
340                         "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
341                         "[>|}].*")
342                 'font-lock-reference-face)
343           '("^\\(X-[A-Za-z0-9-]+\\|In-reply-to\\):.*"
344             . font-lock-string-face)))
345   "Additional expressions to highlight in Message mode.")
346
347 (defvar message-face-alist
348   '((bold . bold-region)
349     (underline . underline-region)
350     (default . (lambda (b e) 
351                  (unbold-region b e)
352                  (ununderline-region b e))))
353   "Alist of mail and news faces for facemenu.
354 The cdr of ech entry is a function for applying the face to a region.")
355
356 (defvar message-send-hook nil
357   "Hook run before sending messages.")
358
359 (defvar message-sent-hook nil
360   "Hook run after sending messages.")
361
362 ;;; Internal variables.
363
364 (defvar message-header-format-alist 
365   `((Newsgroups)
366     (To . message-fill-header) 
367     (Cc . message-fill-header)
368     (Subject)
369     (In-Reply-To)
370     (Fcc)
371     (Bcc)
372     (Date)
373     (Organization)
374     (Distribution)
375     (Lines)
376     (Expires)
377     (Message-ID)
378     (References . message-fill-header)
379     (X-Mailer)
380     (X-Newsreader))
381   "Alist used for formatting headers.")
382
383 \f
384
385 ;;; 
386 ;;; Utility functions.
387 ;;;
388
389 (defun message-point-at-bol ()
390   "Return point at the beginning of the line."
391   (let ((p (point)))
392     (beginning-of-line)
393     (prog1
394         (point)
395       (goto-char p))))
396
397 (defun message-point-at-eol ()
398   "Return point at the end of the line."
399   (let ((p (point)))
400     (end-of-line)
401     (prog1
402         (point)
403       (goto-char p))))
404
405 ;; Delete the current line (and the next N lines.);
406 (defmacro message-delete-line (&optional n)
407   `(delete-region (progn (beginning-of-line) (point))
408                   (progn (forward-line ,(or n 1)) (point))))
409
410 (defun message-tokenize-header (header &optional separator)
411   "Split HEADER into a list of header elements.
412 \",\" is used as the separator."
413   (let* ((beg 0)
414          (separator (or separator ","))
415          (regexp
416           (format "[ \t]*\\([^%s]+\\)?\\([%s]+\\|\\'\\)" separator separator))
417          elems)
418     (while (and (string-match regexp header beg)
419                 (< beg (length header)))
420       (when (match-beginning 1)
421         (push (match-string 1 header) elems))
422       (setq beg (match-end 0)))
423     (nreverse elems)))
424
425 (defun message-fetch-reply-field (header)
426   "Fetch FIELD from the message we're replying to."
427   (when (and message-reply-buffer
428              (buffer-name message-reply-buffer))
429     (save-excursion
430       (set-buffer message-reply-buffer)
431       (mail-fetch-field header))))
432
433 (defun message-set-work-buffer ()
434   (if (get-buffer " *message work*")
435       (progn
436         (set-buffer " *message work*")
437         (erase-buffer))
438     (set-buffer (get-buffer-create " *message work*"))
439     (kill-all-local-variables)
440     (buffer-disable-undo (current-buffer))))
441
442 (defun message-functionp (form)
443   "Return non-nil if FORM is funcallable."
444   (or (and (symbolp form) (fboundp form))
445       (and (listp form) (eq (car form) 'lambda))))
446
447 (defun message-strip-subject-re (subject)
448   "Remove \"Re:\" from subject lines."
449   (if (string-match "^[Rr][Ee]: *" subject)
450       (substring subject (match-end 0))
451     subject))
452
453 (defun message-remove-header (header &optional is-regexp first reverse)
454   "Remove HEADER in the narrowed buffer.
455 If REGEXP, HEADER is a regular expression.
456 If FIRST, only remove the first instance of the header.
457 Return the number of headers removed."
458   (goto-char (point-min))
459   (let ((regexp (if is-regexp header (concat "^" header ":")))
460         (number 0)
461         (case-fold-search t)
462         last)
463     (while (and (not (eobp))
464                 (not last))
465       (if (if reverse
466               (not (looking-at regexp))
467             (looking-at regexp))
468           (progn
469             (incf number)
470             (when first
471               (setq last t))
472             (delete-region
473              (point)
474              ;; There might be a continuation header, so we have to search
475              ;; until we find a new non-continuation line.
476              (progn
477                (forward-line 1)
478                (if (re-search-forward "^[^ \t]" nil t)
479                    (goto-char (match-beginning 0))
480                  (point-max)))))
481         (forward-line 1)
482         (if (re-search-forward "^[^ \t]" nil t)
483             (goto-char (match-beginning 0))
484           (point-max))))
485     number))
486
487 (defun message-narrow-to-headers ()
488   "Narrow the buffer to the head of the message."
489   (widen)
490   (narrow-to-region
491    (goto-char (point-min))
492    (if (re-search-forward
493         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
494        (match-beginning 0)
495      (point-max)))
496   (goto-char (point-min)))
497
498 (defun message-narrow-to-head ()
499   "Narrow the buffer to the head of the message."
500   (widen)
501   (narrow-to-region
502    (goto-char (point-min))
503    (if (search-forward "\n\n" nil 1)
504        (1- (point))
505      (point-max)))
506   (goto-char (point-min)))
507
508 (defun message-news-p ()
509   "Say whether the current buffer contains a news message."
510   (save-excursion
511     (save-restriction
512       (message-narrow-to-headers)
513       (mail-fetch-field "newsgroups"))))
514
515 (defun message-mail-p ()
516   "Say whether the current buffer contains a mail message."
517   (save-excursion
518     (save-restriction
519       (message-narrow-to-headers)
520       (or (mail-fetch-field "to")
521           (mail-fetch-field "cc")
522           (mail-fetch-field "bcc")))))
523     
524 \f
525
526 ;;;
527 ;;; Message mode
528 ;;;
529
530 ;;; Set up keymap.
531
532 (defvar message-mode-map nil)
533
534 (unless message-mode-map
535   (setq message-mode-map (copy-keymap text-mode-map))
536   (define-key message-mode-map "\C-c?" 'describe-mode)
537
538   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
539   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
540   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
541   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
542   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
543   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
544   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
545   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
546   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
547   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
548   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
549   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
550   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
551
552   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
553   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
554   
555   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
556   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
557   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
558   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
559
560   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
561   (define-key message-mode-map "\C-c\C-s" 'message-send))
562
563 (defun message-make-menu-bar ()
564   (unless (boundp 'message-menu)
565     (easy-menu-define
566      message-menu message-mode-map ""
567      '("Message"
568        ["Fill Citation" message-fill-yanked-message t]))))
569
570 ;;;###autoload
571 (defun message-mode ()
572   "Major mode for editing mail and news to be sent.
573 Like Text Mode but with these additional commands:
574 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
575 C-c C-f  move to a header field (and create it if there isn't):
576          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
577          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
578          C-c C-f C-f  move to Fcc       C-c C-f C-r  move to Reply-To
579          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
580          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
581          C-c C-f C-o  move to Followup-To
582 C-c C-t  message-insert-to (add a To header to a news followup)
583 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
584 C-c C-b  message-goto-body (move to beginning of message text).
585 C-c C-i  message-goto-signature (move to the beginning of the signature).
586 C-c C-w  message-insert-signature (insert `message-signature-file' file).
587 C-c C-y  message-yank-original (insert current message, if any).
588 C-c C-q  message-fill-yanked-message (fill what was yanked).
589 C-c C-r  message-ceasar-buffer-body (rot13 the message body)."
590   (interactive)
591   (kill-all-local-variables)
592   (make-local-variable 'message-reply-buffer)
593   (setq message-reply-buffer nil)
594   (make-local-variable 'message-send-actions)
595   (set-syntax-table message-mode-syntax-table)
596   (use-local-map message-mode-map)
597   (setq local-abbrev-table text-mode-abbrev-table)
598   (setq major-mode 'message-mode)
599   (setq mode-name "Message")
600   (setq buffer-offer-save t)
601   (make-local-variable 'font-lock-defaults)
602   (setq font-lock-defaults '(message-font-lock-keywords t))
603   (make-local-variable 'facemenu-add-face-function)
604   (make-local-variable 'facemenu-remove-face-function)
605   (setq facemenu-add-face-function
606         (lambda (face end)
607           (let ((face-fun (cdr (assq face message-face-alist))))
608             (if face-fun
609                 (funcall face-fun (point) end)
610               (error "Face %s not configured for %s mode" face mode-name)))
611           "")
612         facemenu-remove-face-function t)
613   (make-local-variable 'paragraph-separate)
614   (make-local-variable 'paragraph-start)
615   (setq paragraph-start (concat (regexp-quote mail-header-separator)
616                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
617                                 paragraph-start))
618   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
619                                    "$\\|[ \t]*[-_][-_][-_]+$\\|"
620                                    paragraph-separate))
621   (make-local-variable 'message-reply-headers)
622   (setq message-reply-headers nil)
623   (make-local-variable 'message-newsreader)
624   (make-local-variable 'message-mailer)
625   (make-local-variable 'message-post-method)
626   (make-local-variable 'message-sent-message-via)
627   (setq message-sent-message-via nil)
628   (make-local-variable 'message-checksum)
629   (setq message-checksum nil)
630   (when (fboundp 'mail-hist-define-keys)
631     (mail-hist-define-keys))
632   (run-hooks 'text-mode-hook 'message-mode-hook))
633
634 \f
635
636 ;;;
637 ;;; Message mode commands
638 ;;;
639
640 ;;; Movement commands
641
642 (defun message-goto-to ()
643   "Move point to the To header."
644   (interactive)
645   (message-position-on-field "To"))
646
647 (defun message-goto-subject ()
648   "Move point to the Subject header."
649   (interactive)
650   (message-position-on-field "Subject"))
651
652 (defun message-goto-cc ()
653   "Move point to the Cc header."
654   (interactive)
655   (message-position-on-field "Cc" "To"))
656
657 (defun message-goto-bcc ()
658   "Move point to the Bcc  header."
659   (interactive)
660   (message-position-on-field "Bcc" "Cc" "To"))
661
662 (defun message-goto-fcc ()
663   "Move point to the Fcc header."
664   (interactive)
665   (message-position-on-field "Fcc" "To" "Newsgroups"))
666
667 (defun message-goto-reply-to ()
668   "Move point to the Reply-To header."
669   (interactive)
670   (message-position-on-field "Reply-To" "Subject"))
671
672 (defun message-goto-newsgroups ()
673   "Move point to the Newsgroups header."
674   (interactive)
675   (message-position-on-field "Newsgroups"))
676
677 (defun message-goto-distribution ()
678   "Move point to the Distribution header."
679   (interactive)
680   (message-position-on-field "Distribution"))
681
682 (defun message-goto-followup-to ()
683   "Move point to the Followup-To header."
684   (interactive)
685   (message-position-on-field "Followup-To" "Newsgroups"))
686
687 (defun message-goto-keywords ()
688   "Move point to the Keywords header."
689   (interactive)
690   (message-position-on-field "Keywords" "Subject"))
691
692 (defun message-goto-summary ()
693   "Move point to the Summary header."
694   (interactive)
695   (message-position-on-field "Summary" "Subject"))
696
697 (defun message-goto-body ()
698   "Move point to the beginning of the message body."
699   (interactive)
700   (goto-char (point-min))
701   (search-forward (concat "\n" mail-header-separator "\n") nil t))
702
703 (defun message-goto-signature ()
704   "Move point to the beginning of the message signature."
705   (interactive)
706   (goto-char (point-min))
707   (or (re-search-forward message-signature-separator nil t)
708       (goto-char (point-max))))
709
710 \f
711
712 (defun message-insert-to ()
713   "Insert a To header that points to the author of the article being replied to."
714   (interactive)
715   (when (message-position-on-field "To")
716     (insert ", "))
717   (insert (or (message-fetch-reply-field "reply-to")
718               (message-fetch-reply-field "from") "")))
719
720 (defun message-insert-newsgroups ()
721   "Insert the Newsgroups header from the article being replied to."
722   (interactive)
723   (when (message-position-on-field "Newsgroups")
724     (insert ","))
725   (insert (or (message-fetch-reply-field "newsgroups") "")))
726
727 \f
728
729 ;;; Various commands
730
731 (defun message-insert-signature (&optional force)
732   "Insert a signature.  See documentation for the `message-signature' variable."
733   (interactive (list t))
734   (let* ((signature 
735           (cond ((and (null message-signature)
736                       force)
737                  t)
738                 ((message-functionp message-signature)
739                  (funcall message-signature))
740                 ((listp message-signature)
741                  (eval message-signature))
742                 (t message-signature)))
743          (signature
744           (cond ((stringp signature)
745                  signature)
746                 ((and (eq t signature)
747                       message-signature-file
748                       (file-exists-p message-signature-file))
749                  signature))))
750     (when signature
751       ;; Remove blank lines at the end of the message.
752       (goto-char (point-max))
753       (skip-chars-backward " \t\n")
754       (end-of-line)
755       (delete-region (point) (point-max))
756       ;; Insert the signature.
757       (insert "\n\n-- \n")
758       (if (eq signature t)
759           (insert-file-contents message-signature-file)
760         (insert signature))
761       (goto-char (point-max))
762       (or (bolp) (insert "\n")))))
763
764 (defvar message-caesar-translation-table nil)
765
766 (defun message-caesar-region (b e &optional n)
767   "Caesar rotation of region by N, default 13, for decrypting netnews."
768   (interactive
769    (list
770     (min (point) (or (mark t) (point)))
771     (max (point) (or (mark t) (point)))
772     (when current-prefix-arg
773       (prefix-numeric-value current-prefix-arg))))
774
775   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
776   (unless (or (zerop n)                 ; no action needed for a rot of 0
777               (= b e))                  ; no region to rotate
778     ;; We build the table, if necessary.
779     (when (or (not message-caesar-translation-table)
780               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
781       (let ((i -1) 
782             (table (make-string 256 0)))
783         (while (< (incf i) 256)
784           (aset table i i))
785         (setq table
786               (concat
787                (substring table 0 ?A)
788                (substring table (+ ?A n) (+ ?A n (- 26 n)))
789                (substring table ?A (+ ?A n))
790                (substring table (+ ?A 26) ?a)
791                (substring table (+ ?a n) (+ ?a n (- 26 n)))
792                (substring table ?a (+ ?a n))
793                (substring table (+ ?a 26) 255)))
794         (setq message-caesar-translation-table table)))
795     ;; Then we translate the region.  Do it this way to retain 
796     ;; text properties.
797     (while (< b e)
798       (subst-char-in-region 
799        b (1+ b) (char-after b)
800        (aref message-caesar-translation-table (char-after b)))
801       (incf b))))
802
803 (defun message-caesar-buffer-body (&optional rotnum)
804   "Caesar rotates all letters in the current buffer by 13 places.
805 Used to encode/decode possibly offensive messages (commonly in net.jokes).
806 With prefix arg, specifies the number of places to rotate each letter forward.
807 Mail and USENET news headers are not rotated."
808   (interactive (if current-prefix-arg
809                    (list (prefix-numeric-value current-prefix-arg))
810                  (list nil)))
811   (save-excursion
812     (save-restriction
813       (when (message-goto-body)
814         (narrow-to-region (point) (point-max)))
815       (message-caesar-region (point-min) (point-max) rotnum))))
816
817 (defun message-fill-yanked-message (&optional justifyp)
818   "Fill the paragraphs of a message yanked into this one.
819 Numeric argument means justify as well."
820   (interactive "P")
821   (save-excursion
822     (goto-char (point-min))
823     (search-forward (concat "\n" mail-header-separator "\n") nil t)
824     (fill-individual-paragraphs (point)
825                                 (point-max)
826                                 justifyp
827                                 t)))
828
829 (defun message-indent-citation ()
830   "Modify text just inserted from a message to be cited.
831 The inserted text should be the region.
832 When this function returns, the region is again around the modified text.
833
834 Normally, indent each nonblank line `message-indentation-spaces' spaces.
835 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
836   (let ((start (point)))
837     ;; Remove unwanted headers.
838     (when message-ignored-cited-headers
839       (save-restriction
840         (narrow-to-region 
841          (goto-char start)
842          (if (search-forward "\n\n" nil t)
843              (1- (point))
844            (point)))
845         (message-remove-header message-ignored-cited-headers t)))
846     ;; Do the indentation.
847     (if (null message-yank-prefix)
848         (indent-rigidly start (mark t) message-indentation-spaces)
849       (save-excursion
850         (goto-char start)
851         (while (< (point) (mark t))
852           (insert message-yank-prefix)
853           (forward-line 1)))
854       (goto-char start))))
855
856 (defun message-yank-original (&optional arg)
857   "Insert the message being replied to, if any.
858 Puts point before the text and mark after.
859 Normally indents each nonblank line ARG spaces (default 3).  However,
860 if `message-yank-prefix' is non-nil, insert that prefix on each line.
861
862 Just \\[universal-argument] as argument means don't indent, insert no
863 prefix, and don't delete any headers."
864   (interactive "P")
865   (let ((modified (buffer-modified-p)))
866     (when (and message-reply-buffer
867                message-cite-function)
868       (delete-windows-on message-reply-buffer t)
869       (insert-buffer message-reply-buffer)
870       (funcall message-cite-function)
871       (exchange-point-and-mark)
872       (unless (bolp)
873         (insert ?\n))
874       (unless modified
875         (setq message-checksum (message-checksum))))))
876
877 (defun message-cite-original ()    
878   (let ((start (point))
879         (functions 
880          (when message-indent-citation-function
881            (if (listp message-indent-citation-function)
882                message-indent-citation-function
883              (list message-indent-citation-function)))))
884     (goto-char start)
885     (while functions
886       (funcall (pop functions)))
887     (when message-citation-line-function
888       (unless (bolp)
889         (insert "\n"))
890       (funcall message-citation-line-function))))
891
892 (defun message-insert-citation-line ()
893   "Function that inserts a simple citation line."
894   (when message-reply-headers
895     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
896
897 (defun message-position-on-field (header &rest afters)
898   (let ((case-fold-search t))
899     (save-restriction
900       (narrow-to-region
901        (goto-char (point-min))
902        (progn
903          (re-search-forward 
904           (concat "^" (regexp-quote mail-header-separator) "$"))
905          (match-beginning 0)))
906       (goto-char (point-min))
907       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
908           (progn
909             (re-search-forward "^[^ \t]" nil 'move)
910             (beginning-of-line)
911             (skip-chars-backward "\n")
912             t)
913         (while (and afters
914                     (not (re-search-forward 
915                           (concat "^" (regexp-quote (car afters)) ":")
916                           nil t)))
917           (pop afters))
918         (when afters
919           (re-search-forward "^[^ \t]" nil 'move)
920           (beginning-of-line))
921         (insert header ": \n")
922         (forward-char -1)
923         nil))))
924
925 (defun message-remove-signature ()
926   "Remove the signature from the text between point and mark.
927 The text will also be indented the normal way."
928   (save-excursion
929     (let ((start (point))
930           mark)
931     (if (not (re-search-forward message-signature-separator (mark t) t))
932         ;; No signature here, so we just indent the cited text.
933         (message-indent-citation)
934       ;; Find the last non-empty line.
935       (forward-line -1)
936       (while (looking-at "[ \t]*$")
937         (forward-line -1))
938       (forward-line 1)
939       (setq mark (set-marker (make-marker) (point)))
940       (goto-char start)
941       (message-indent-citation)
942       ;; Enable undoing the deletion.
943       (undo-boundary)
944       (delete-region mark (mark t))
945       (set-marker mark nil)))))
946
947 \f
948
949 ;;;
950 ;;; Sending messages
951 ;;;
952
953 (defun message-send-and-exit (&optional arg)
954   "Send message like `message-send', then, if no errors, exit from mail buffer."
955   (interactive "P")
956   (let ((buf (current-buffer)))
957     (when (and (message-send arg)
958                (buffer-name buf))
959       (bury-buffer buf)
960       (when (eq buf (current-buffer))
961         (message-bury buf)))))
962
963 (defun message-dont-send ()
964   "Don't send the message you have been editing."
965   (interactive)
966   (message-bury (current-buffer)))
967
968 (defun message-bury (buffer)
969   "Bury this mail buffer."
970   (let ((newbuf (other-buffer buffer)))
971     (bury-buffer buffer)
972     (if (and (fboundp 'frame-parameters)
973              (cdr (assq 'dedicated (frame-parameters)))
974              (not (null (delq (selected-frame) (visible-frame-list)))))
975         (delete-frame (selected-frame))
976       (switch-to-buffer newbuf))))
977
978 (defun message-send (&optional arg)
979   "Send the message in the current buffer.
980 If `message-interactive' is non-nil, wait for success indication
981 or error messages, and inform user.
982 Otherwise any failure is reported in a message back to
983 the user from the mailer."
984   (interactive "P")
985   (when (if buffer-file-name
986             (y-or-n-p (format "Send buffer contents as %s message? "
987                               (if (message-mail-p)
988                                   (if (message-news-p) "mail and news" "mail")
989                                 "news")))
990           (or (buffer-modified-p)
991               (y-or-n-p "No changes in the buffer; really send? ")))
992     ;; Make it possible to undo the coming changes.
993     (undo-boundary)
994     (run-hooks 'message-send-hook)
995     (message "Sending...")
996     (when (and (or (not (message-news-p))
997                    (and (or (not (memq 'news message-sent-message-via))
998                             (y-or-n-p
999                              "Already sent message via news; resend? "))
1000                         (funcall message-send-news-function arg)))
1001                (or (not (message-mail-p))
1002                    (and (or (not (memq 'mail message-sent-message-via))
1003                             (y-or-n-p
1004                              "Already sent message via mail; resend? "))
1005                         (funcall message-send-mail-function arg))))
1006       (message-do-fcc)
1007       (when (fboundp 'mail-hist-put-headers-into-history)
1008         (mail-hist-put-headers-into-history))
1009       (run-hooks 'message-sent-hook)
1010       (message "Sending...done")
1011       ;; If buffer has no file, mark it as unmodified and delete autosave.
1012       (unless buffer-file-name
1013         (set-buffer-modified-p nil)
1014         (delete-auto-save-file-if-necessary t))
1015       ;; Now perform actions on successful sending.
1016       (let ((actions message-send-actions))
1017         (while actions
1018           (condition-case nil
1019               (apply (caar actions) (cdar actions))
1020             (error))
1021           (pop actions)))
1022       ;; Return success.
1023       t)))
1024
1025 (defun message-send-mail (&optional arg)
1026   (require 'mail-utils)
1027   (let ((errbuf (if message-interactive
1028                     (generate-new-buffer " sendmail errors")
1029                   0))
1030         (tembuf (generate-new-buffer " message temp"))
1031         (case-fold-search nil)
1032         (news (message-news-p))
1033         (resend-to-addresses (mail-fetch-field "resent-to"))
1034         delimline
1035         (mailbuf (current-buffer)))
1036     (save-restriction
1037       (message-narrow-to-headers)
1038       ;; Insert some headers.
1039       (message-generate-headers message-required-mail-headers)
1040       ;; Let the user do all of the above.
1041       (run-hooks 'message-header-hook))
1042     (unwind-protect
1043         (save-excursion
1044           (set-buffer tembuf)
1045           (erase-buffer)
1046           (insert-buffer-substring mailbuf)
1047           ;; Remove some headers.
1048           (save-restriction
1049             (message-narrow-to-headers)
1050             ;; Remove some headers.
1051             (message-remove-header message-ignored-mail-headers t))
1052           (goto-char (point-max))
1053           ;; require one newline at the end.
1054           (or (= (preceding-char) ?\n)
1055               (insert ?\n))
1056           (when (and news
1057                      (or (mail-fetch-field "cc")
1058                          (mail-fetch-field "to")))
1059             (message-insert-courtesy-copy))
1060           (let ((case-fold-search t))
1061             ;; Change header-delimiter to be what sendmail expects.
1062             (goto-char (point-min))
1063             (re-search-forward
1064              (concat "^" (regexp-quote mail-header-separator) "\n"))
1065             (replace-match "\n")
1066             (backward-char 1)
1067             (setq delimline (point-marker))
1068             ;; Insert an extra newline if we need it to work around
1069             ;; Sun's bug that swallows newlines.
1070             (goto-char (1+ delimline))
1071             (when (eval message-mailer-swallows-blank-line)
1072               (newline))
1073             (when message-interactive
1074               (save-excursion
1075                 (set-buffer errbuf)
1076                 (erase-buffer))))
1077           (let ((default-directory "/"))
1078             (apply 'call-process-region
1079                    (append (list (point-min) (point-max)
1080                                  (if (boundp 'sendmail-program)
1081                                      sendmail-program
1082                                    "/usr/lib/sendmail")
1083                                  nil errbuf nil "-oi")
1084                            ;; Always specify who from,
1085                            ;; since some systems have broken sendmails.
1086                            (list "-f" (user-login-name))
1087                            ;; These mean "report errors by mail"
1088                            ;; and "deliver in background".
1089                            (if (null message-interactive) '("-oem" "-odb"))
1090                            ;; Get the addresses from the message
1091                            ;; unless this is a resend.
1092                            ;; We must not do that for a resend
1093                            ;; because we would find the original addresses.
1094                            ;; For a resend, include the specific addresses.
1095                            (or resend-to-addresses
1096                                '("-t")))))
1097           (when message-interactive
1098             (save-excursion
1099               (set-buffer errbuf)
1100               (goto-char (point-min))
1101               (while (re-search-forward "\n\n* *" nil t)
1102                 (replace-match "; "))
1103               (if (not (zerop (buffer-size)))
1104                   (error "Sending...failed to %s"
1105                          (buffer-substring (point-min) (point-max)))))))
1106       (kill-buffer tembuf)
1107       (when (bufferp errbuf)
1108         (kill-buffer errbuf)))
1109     (set-buffer mailbuf)
1110     (push 'mail message-sent-message-via)))
1111
1112 (defun message-send-news (&optional arg)
1113   (let ((tembuf (generate-new-buffer " *message temp*"))
1114         (case-fold-search nil)
1115         (method (if (message-functionp message-post-method)
1116                     (funcall message-post-method arg)
1117                   message-post-method))
1118         (messbuf (current-buffer)))
1119     (save-restriction
1120       (message-narrow-to-headers)
1121       ;; Insert some headers.
1122       (message-generate-headers message-required-news-headers)
1123       ;; Let the user do all of the above.
1124       (run-hooks 'message-header-hook))
1125     (when (message-check-news-syntax)
1126       (unwind-protect
1127           (save-excursion
1128             (set-buffer tembuf)
1129             (buffer-disable-undo (current-buffer))
1130             (erase-buffer) 
1131             (insert-buffer-substring messbuf)
1132             ;; Remove some headers.
1133             (save-restriction
1134               (message-narrow-to-headers)
1135               ;; Remove some headers.
1136               (message-remove-header message-ignored-news-headers t))
1137             (goto-char (point-max))
1138             ;; require one newline at the end.
1139             (or (= (preceding-char) ?\n)
1140                 (insert ?\n))
1141             (let ((case-fold-search t))
1142               ;; Remove the delimeter.
1143               (goto-char (point-min))
1144               (re-search-forward
1145                (concat "^" (regexp-quote mail-header-separator) "\n"))
1146               (replace-match "\n")
1147               (backward-char 1))
1148             (require (car method))
1149             (funcall (intern (format "%s-open-server" (car method)))
1150                      (cadr method) (cddr method))
1151             (funcall (intern (format "%s-request-post"
1152                                      (car method)))))
1153         (kill-buffer tembuf))
1154       (set-buffer messbuf)
1155       (push 'news message-sent-message-via))))
1156
1157 ;;;
1158 ;;; Header generation & syntax checking.
1159 ;;;
1160
1161 (defun message-check-news-syntax ()
1162   "Check the syntax of the message."
1163   (or
1164    (not message-syntax-checks)
1165    (and 
1166     ;; We narrow to the headers and check them first.
1167     (save-excursion
1168       (save-restriction
1169         (message-narrow-to-headers)
1170         (and 
1171          ;; Check for commands in Subject.
1172          (or 
1173           (message-check-element 'subject-cmsg)
1174           (save-excursion
1175             (if (string-match "^cmsg " (mail-fetch-field "subject"))
1176                 (y-or-n-p
1177                  "The control code \"cmsg \" is in the subject. Really post? ")
1178               t)))
1179          ;; Check for multiple identical headers.
1180          (or (message-check-element 'multiple-headers)
1181              (save-excursion
1182                (let (found)
1183                  (while (and (not found) 
1184                              (re-search-forward "^[^ \t:]+: " nil t))
1185                    (save-excursion
1186                      (or (re-search-forward 
1187                           (concat "^" (setq found
1188                                             (buffer-substring 
1189                                              (match-beginning 0) 
1190                                              (- (match-end 0) 2))))
1191                           nil t)
1192                          (setq found nil))))
1193                  (if found
1194                      (y-or-n-p 
1195                       (format "Multiple %s headers. Really post? " found))
1196                    t))))
1197          ;; Check for Version and Sendsys.
1198          (or (message-check-element 'sendsys)
1199              (save-excursion
1200                (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1201                    (y-or-n-p
1202                     (format "The article contains a %s command. Really post? "
1203                             (buffer-substring (match-beginning 0) 
1204                                               (1- (match-end 0)))))
1205                  t)))
1206          ;; See whether we can shorten Followup-To.
1207          (or (message-check-element 'shorten-followup-to)
1208              (let ((newsgroups (mail-fetch-field "newsgroups"))
1209                    (followup-to (mail-fetch-field "followup-to"))
1210                    to)
1211                (when (and newsgroups (string-match "," newsgroups)
1212                           (not followup-to)
1213                           (not
1214                            (zerop
1215                             (length
1216                              (setq to (completing-read 
1217                                        "Followups to: (default all groups) " 
1218                                        (mapcar (lambda (g) (list g))
1219                                                (cons "poster" 
1220                                                      (message-tokenize-header 
1221                                                       newsgroups)))))))))
1222                  (goto-char (point-min))
1223                  (insert "Followup-To: " to "\n"))))
1224
1225          ;; Check for Approved.
1226          (or (message-check-element 'approved)
1227              (save-excursion
1228                (if (re-search-forward "^Approved:" nil t)
1229                    (y-or-n-p
1230                     "The article contains an Approved header. Really post? ")
1231                  t)))
1232          ;; Check the Message-Id header.
1233          (or (message-check-element 'message-id)
1234              (save-excursion
1235                (let* ((case-fold-search t)
1236                       (message-id (mail-fetch-field "message-id")))
1237                  (or (not message-id)
1238                      (and (string-match "@" message-id)
1239                           (string-match "@[^\\.]*\\." message-id))
1240                      (y-or-n-p
1241                       (format 
1242                        "The Message-ID looks strange: \"%s\". Really post? "
1243                        message-id))))))
1244          ;; Check the Subject header.
1245          (or 
1246           (message-check-element 'subject)
1247           (save-excursion
1248             (let* ((case-fold-search t)
1249                    (subject (mail-fetch-field "subject")))
1250               (or
1251                (and subject
1252                     (not (string-match "\\`[ \t]*\\'" subject)))
1253                (progn
1254                  (message 
1255                   "The subject field is empty or missing.  Posting is denied.")
1256                  nil)))))
1257          ;; Check the From header.
1258          (or (message-check-element 'from)
1259              (save-excursion
1260                (let* ((case-fold-search t)
1261                       (from (mail-fetch-field "from")))
1262                  (cond
1263                   ((not from)
1264                    (message "There is no From line.  Posting is denied.")
1265                    nil)
1266                   ((not (string-match "@[^\\.]*\\." from))
1267                    (message
1268                     "Denied posting -- the From looks strange: \"%s\"." from)
1269                    nil)
1270                   ((string-match "@[^@]*@" from)
1271                    (message 
1272                     "Denied posting -- two \"@\"'s in the From header: %s."
1273                     from)
1274                    nil)
1275                   ((string-match "(.*).*(.*)" from)
1276                    (message
1277                     "Denied posting -- the From header looks strange: \"%s\"." 
1278                     from)
1279                    nil)
1280                   (t t))))))))
1281     ;; Check for long lines.
1282     (or (message-check-element 'long-lines)
1283         (save-excursion
1284           (goto-char (point-min))
1285           (re-search-forward
1286            (concat "^" (regexp-quote mail-header-separator) "$"))
1287           (while (and
1288                   (progn
1289                     (end-of-line)
1290                     (< (current-column) 80))
1291                   (zerop (forward-line 1))))
1292           (or (bolp)
1293               (eobp)
1294               (y-or-n-p
1295                "You have lines longer than 79 characters.  Really post? "))))
1296     ;; Check whether the article is empty.
1297     (or (message-check-element 'empty)
1298         (save-excursion
1299           (goto-char (point-min))
1300           (re-search-forward
1301            (concat "^" (regexp-quote mail-header-separator) "$"))
1302           (forward-line 1)
1303           (or (re-search-forward "[^ \n\t]" nil t)
1304               (y-or-n-p "Empty article.  Really post?"))))
1305     ;; Check for control characters.
1306     (or (message-check-element 'control-chars)
1307         (save-excursion
1308           (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
1309               (y-or-n-p 
1310                "The article contains control characters. Really post? ")
1311             t)))
1312     ;; Check excessive size.
1313     (or (message-check-element 'size)
1314         (if (> (buffer-size) 60000)
1315             (y-or-n-p
1316              (format "The article is %d octets long. Really post? "
1317                      (buffer-size)))
1318           t))
1319     ;; Check whether any new text has been added.
1320     (or (message-check-element 'new-text)
1321         (not message-checksum)
1322         (not (eq (message-checksum) message-checksum))
1323         (y-or-n-p
1324          "It looks like no new text has been added.  Really post? "))
1325     ;; Check the length of the signature.
1326     (or (message-check-element 'signature)
1327         (progn
1328           (goto-char (point-max))
1329           (if (not (re-search-backward "^-- $" nil t))
1330               t
1331             (if (> (count-lines (point) (point-max)) 5)
1332                 (y-or-n-p
1333                  (format
1334                   "Your .sig is %d lines; it should be max 4.  Really post? "
1335                   (count-lines (point) (point-max))))
1336               t)))))))
1337
1338 ;; Returns non-nil if this type is not to be checked.
1339 (defun message-check-element (type)
1340   (not 
1341    (or (not message-syntax-checks)
1342        (if (listp message-syntax-checks)
1343            (memq type message-syntax-checks)
1344          t))))
1345
1346 (defun message-checksum ()
1347   "Return a \"checksum\" for the current buffer."
1348   (let ((sum 0))
1349     (save-excursion
1350       (while (not (eobp))
1351         (setq sum (logxor sum (following-char)))
1352         (forward-char 1)))
1353     sum))
1354
1355 (defun message-do-fcc ()
1356   "Process Fcc headers in the current buffer."
1357   (let ((case-fold-search t)
1358         (buf (current-buffer))
1359         list file)
1360     (save-excursion
1361       (set-buffer (get-buffer-create " *message temp*"))
1362       (buffer-disable-undo (current-buffer))
1363       (erase-buffer)
1364       (insert-buffer-substring buf)
1365       (save-restriction
1366         (message-narrow-to-headers)
1367         (while (setq file (mail-fetch-field "fcc"))
1368           (push file list)
1369           (message-remove-header "fcc" nil t)))
1370       (goto-char (point-min))
1371       (re-search-forward (concat "^" mail-header-separator "$"))
1372       (replace-match "" t t)
1373       ;; Process FCC operations.
1374       (while list
1375         (setq file (pop list))
1376         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
1377             ;; Pipe the article to the program in question.
1378             (call-process-region (point-min) (point-max) shell-file-name
1379                                  nil nil nil "-c" (match-string 1 file))
1380           ;; Save the article.
1381           (setq file (expand-file-name file))
1382           (unless (file-exists-p (file-name-directory file))
1383             (make-directory (file-name-directory file) t))
1384           (if (and message-fcc-handler-function
1385                    (not (eq message-fcc-handler-function 'rmail-output)))
1386               (funcall message-fcc-handler-function file)
1387             (if (and (file-readable-p file) (mail-file-babyl-p file))
1388                 (rmail-output file 1)
1389               (let ((mail-use-rfc822 t))
1390                 (rmail-output file 1 t t))))))
1391       (kill-buffer (current-buffer)))))
1392
1393 (defun message-cleanup-headers ()
1394   "Do various automatic cleanups of the headers."
1395   ;; Remove empty lines in the header.
1396   (save-restriction
1397     (message-narrow-to-headers)
1398     (while (re-search-forward "^[ \t]*\n" nil t)
1399       (replace-match "" t t)))
1400
1401   ;; Correct Newsgroups and Followup-To headers: change sequence of
1402   ;; spaces to comma and eliminate spaces around commas.  Eliminate
1403   ;; embedded line breaks.
1404   (goto-char (point-min))
1405   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
1406     (save-restriction
1407       (narrow-to-region
1408        (point)
1409        (if (re-search-forward "^[^ \t]" nil t)
1410            (match-beginning 0)
1411          (forward-line 1)
1412          (point)))
1413       (goto-char (point-min))
1414       (while (re-search-forward "\n[ \t]+" nil t)
1415         (replace-match " " t t))        ;No line breaks (too confusing)
1416       (goto-char (point-min))
1417       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
1418         (replace-match "," t t))
1419       (goto-char (point-min))
1420       ;; Remove trailing commas.
1421       (when (re-search-forward ",+$" nil t)
1422         (replace-match "" t t)))))
1423
1424 (defun message-make-date ()
1425   "Make a valid data header."
1426   (let ((now (current-time)))
1427     (timezone-make-date-arpa-standard 
1428      (current-time-string now) (current-time-zone now))))
1429
1430 (defun message-make-message-id ()
1431   "Make a unique Message-ID."
1432   (concat "<" (message-unique-id) 
1433           (let ((psubject (save-excursion (mail-fetch-field "subject"))))
1434             (if (and message-reply-headers
1435                      (mail-header-references message-reply-headers)
1436                      (mail-header-subject message-reply-headers)
1437                      psubject
1438                      (mail-header-subject message-reply-headers)
1439                      (not (string= 
1440                            (message-strip-subject-re
1441                             (mail-header-subject message-reply-headers))
1442                            (message-strip-subject-re psubject))))
1443                 "_-_" ""))
1444           "@" (message-make-fqdm) ">"))
1445
1446 (defvar message-unique-id-char nil)
1447
1448 ;; If you ever change this function, make sure the new version
1449 ;; cannot generate IDs that the old version could.
1450 ;; You might for example insert a "." somewhere (not next to another dot
1451 ;; or string boundary), or modify the "fsf" string.
1452 (defun message-unique-id ()
1453   ;; Don't use microseconds from (current-time), they may be unsupported.
1454   ;; Instead we use this randomly inited counter.
1455   (setq message-unique-id-char
1456         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
1457            ;; (current-time) returns 16-bit ints,
1458            ;; and 2^16*25 just fits into 4 digits i base 36.
1459            (* 25 25)))
1460   (let ((tm (current-time)))
1461     (concat
1462      (if (memq system-type '(ms-dos emx vax-vms))
1463          (let ((user (downcase (user-login-name))))
1464            (while (string-match "[^a-z0-9_]" user)
1465              (aset user (match-beginning 0) ?_))
1466            user)
1467        (message-number-base36 (user-uid) -1))
1468      (message-number-base36 (+ (car   tm) 
1469                                (lsh (% message-unique-id-char 25) 16)) 4)
1470      (message-number-base36 (+ (nth 1 tm)
1471                                (lsh (/ message-unique-id-char 25) 16)) 4)
1472      ;; Append the newsreader name, because while the generated
1473      ;; ID is unique to this newsreader, other newsreaders might
1474      ;; otherwise generate the same ID via another algorithm.
1475      ".fsf")))
1476
1477 (defun message-number-base36 (num len)
1478   (if (if (< len 0) (<= num 0) (= len 0))
1479       ""
1480     (concat (message-number-base36 (/ num 36) (1- len))
1481             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
1482                                   (% num 36))))))
1483
1484 (defun message-make-organization ()
1485   "Make an Organization header."
1486   (let* ((organization 
1487           (or (getenv "ORGANIZATION")
1488               (when message-user-organization
1489                 (if (message-functionp message-user-organization)
1490                     (funcall message-user-organization)
1491                   message-user-organization)))))
1492     (save-excursion
1493       (message-set-work-buffer)
1494       (cond ((stringp message-user-organization)
1495              (insert message-user-organization))
1496             ((and (eq t message-user-organization)
1497                   message-user-organization-file
1498                   (file-exists-p message-user-organization-file))
1499              (insert-file-contents message-user-organization-file)))
1500       (goto-char (point-min))
1501       (while (re-search-forward "[\t\n]+" nil t)
1502         (replace-match "" t t))
1503       (unless (zerop (buffer-size))
1504         (buffer-string)))))
1505
1506 (defun message-make-lines ()
1507   "Count the number of lines and return numeric string."
1508   (save-excursion
1509     (save-restriction
1510       (widen)
1511       (goto-char (point-min))
1512       (re-search-forward 
1513        (concat "^" (regexp-quote mail-header-separator) "$"))
1514       (forward-line 1)
1515       (int-to-string (count-lines (point) (point-max))))))
1516
1517 (defun message-make-in-reply-to ()
1518   "Return the In-Reply-To header for this message."
1519   (when message-reply-headers
1520     (let ((from (mail-header-from message-reply-headers))
1521           (date (mail-header-date message-reply-headers)))
1522       (when from
1523         (let ((stop-pos 
1524                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
1525           (concat (if stop-pos (substring from 0 stop-pos) from)
1526                   "'s message of " 
1527                   (if (or (not date) (string= date ""))
1528                       "(unknown date)" date)))))))
1529
1530 (defun message-make-distribution ()
1531   "Make a Distribution header."
1532   (let ((orig-distribution (message-fetch-reply-field "distribution")))
1533     (cond ((message-functionp message-distribution-function)
1534            (funcall message-distribution-function))
1535           (t orig-distribution))))
1536
1537 (defun message-make-expires ()
1538   "Return an Expires header based on `message-expires'."
1539   (let ((current (current-time))
1540         (future (* 1.0 message-expires 60 60 24)))
1541     ;; Add the future to current.
1542     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
1543     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
1544     ;; Return the date in the future in UT.
1545     (timezone-make-date-arpa-standard 
1546      (current-time-string current) (current-time-zone current) '(0 "UT"))))
1547
1548 (defun message-make-path ()
1549   "Return uucp path."
1550   (let ((login-name (user-login-name)))
1551     (cond ((null message-user-path)
1552            (concat (system-name) "!" login-name))
1553           ((stringp message-user-path)
1554            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
1555            (concat message-user-path "!" login-name))
1556           (t login-name))))
1557
1558 (defun message-make-from ()
1559   "Make a From header."
1560   (let* ((login (message-make-address))
1561          (fullname (user-full-name)))
1562     (when (string= fullname "&")
1563       (setq fullname (user-login-name)))
1564     (save-excursion
1565       (message-set-work-buffer)
1566       (cond 
1567        ((or (null message-from-style)
1568             (equal fullname ""))
1569         (insert login))
1570        ((or (eq message-from-style 'angles)
1571             (and (not (eq message-from-style 'parens))
1572                  ;; Use angles if no quoting is needed, or if parens would
1573                  ;; need quoting too.
1574                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
1575                      (let ((tmp (concat fullname nil)))
1576                        (while (string-match "([^()]*)" tmp)
1577                          (aset tmp (match-beginning 0) ?-)
1578                          (aset tmp (1- (match-end 0)) ?-))
1579                        (string-match "[\\()]" tmp)))))
1580         (insert fullname)
1581         (goto-char (point-min))
1582         ;; Look for a character that cannot appear unquoted
1583         ;; according to RFC 822.
1584         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
1585           ;; Quote fullname, escaping specials.
1586           (goto-char (point-min))
1587           (insert "\"")
1588           (while (re-search-forward "[\"\\]" nil 1)
1589             (replace-match "\\\\\\&" t))
1590           (insert "\""))
1591         (insert " <" login ">"))
1592        (t                               ; 'parens or default
1593         (insert login " (")
1594         (let ((fullname-start (point)))
1595           (insert fullname)
1596           (goto-char fullname-start)
1597           ;; RFC 822 says \ and nonmatching parentheses
1598           ;; must be escaped in comments.
1599           ;; Escape every instance of ()\ ...
1600           (while (re-search-forward "[()\\]" nil 1)
1601             (replace-match "\\\\\\&" t))
1602           ;; ... then undo escaping of matching parentheses,
1603           ;; including matching nested parentheses.
1604           (goto-char fullname-start)
1605           (while (re-search-forward 
1606                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
1607                     nil 1)
1608             (replace-match "\\1(\\3)" t)
1609             (goto-char fullname-start)))
1610         (insert ")")))
1611       (buffer-string))))
1612
1613 (defun message-make-sender ()
1614   "Return the \"real\" user address.
1615 This function tries to ignore all user modifications, and 
1616 give as trustworthy answer as possible."
1617   (concat (user-login-name) "@" (system-name)))
1618
1619 (defun message-make-address ()
1620   "Make the address of the user."
1621   (or (message-user-mail-address)
1622       (concat (user-login-name) "@" (message-make-domain))))
1623
1624 (defun message-user-mail-address ()
1625   "Return the pertinent part of `user-mail-address'."
1626   (when (string-match
1627          "\\(\\`\\|[ <\t]\\)\\([^ \t@]+@[^ \t]+\\)\\(\\'\\|[> \t]\\)" 
1628          user-mail-address)
1629     (match-string 2 user-mail-address)))
1630
1631 (defun message-make-fqdm ()
1632   "Return user's fully qualified domain name."
1633   (let ((system-name (system-name)))
1634     (cond 
1635      ((string-match "[^.]\\.[^.]" system-name)
1636       ;; `system-name' returned the right result.
1637       system-name)
1638      ;; We try `user-mail-address' as a backup.
1639      ((string-match "@\\(.*\\)\\'" (message-user-mail-address))
1640       (match-string 1 user-mail-address))
1641      ;; Try `mail-host-address'.
1642      ((and (boundp 'mail-host-address)
1643            mail-host-address)
1644       mail-host-address)
1645      ;; Default to this bogus thing.
1646      (t
1647       (concat system-name ".i-have-a-misconfigured-system-so-shoot-me")))))
1648
1649 (defun message-make-host-name ()
1650   "Return the name of the host."
1651   (let ((fqdm (message-make-fqdm)))
1652     (string-match "^[^.]+\\." fqdm)
1653     (substring fqdm 0 (1- (match-end 0)))))
1654
1655 (defun message-make-domain ()
1656   "Return the domain name."
1657   (or mail-host-address
1658       (message-make-fqdm)))
1659
1660 (defun message-generate-headers (headers)
1661   "Prepare article HEADERS.
1662 Headers already prepared in the buffer are not modified."
1663   (save-restriction
1664     (message-narrow-to-headers)
1665     (let* ((Date (message-make-date))
1666            (Message-ID (message-make-message-id))
1667            (Organization (message-make-organization))
1668            (From (message-make-from))
1669            (Path (message-make-path))
1670            (Subject nil)
1671            (Newsgroups nil)
1672            (In-Reply-To (message-make-in-reply-to))
1673            (To nil)
1674            (Distribution (message-make-distribution))
1675            (Lines (message-make-lines))
1676            (X-Newsreader message-newsreader)
1677            (X-Mailer (and (not (mail-fetch-field "X-Newsreader"))
1678                           message-mailer))
1679            (Expires (message-make-expires))
1680            (case-fold-search t)
1681            header value elem)
1682       ;; First we remove any old generated headers.
1683       (let ((headers message-deletable-headers))
1684         (while headers
1685           (goto-char (point-min))
1686           (and (re-search-forward 
1687                 (concat "^" (symbol-name (car headers)) ": *") nil t)
1688                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
1689                (message-delete-line))
1690           (pop headers)))
1691       ;; Go through all the required headers and see if they are in the
1692       ;; articles already. If they are not, or are empty, they are
1693       ;; inserted automatically - except for Subject, Newsgroups and
1694       ;; Distribution. 
1695       (while headers
1696         (goto-char (point-min))
1697         (setq elem (pop headers))
1698         (if (consp elem)
1699             (if (eq (car elem) 'optional)
1700                 (setq header (cdr elem))
1701               (setq header (car elem)))
1702           (setq header elem))
1703         (when (or (not (re-search-forward 
1704                         (concat "^" (downcase (symbol-name header)) ":") 
1705                         nil t))
1706                   (progn
1707                     ;; The header was found. We insert a space after the
1708                     ;; colon, if there is none.
1709                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
1710                     ;; Find out whether the header is empty...
1711                     (looking-at "[ \t]*$")))
1712           ;; So we find out what value we should insert.
1713           (setq value
1714                 (cond 
1715                  ((and (consp elem) (eq (car elem) 'optional))
1716                   ;; This is an optional header.  If the cdr of this
1717                   ;; is something that is nil, then we do not insert
1718                   ;; this header.
1719                   (setq header (cdr elem))
1720                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
1721                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
1722                  ((consp elem)
1723                   ;; The element is a cons.  Either the cdr is a
1724                   ;; string to be inserted verbatim, or it is a
1725                   ;; function, and we insert the value returned from
1726                   ;; this function.
1727                   (or (and (stringp (cdr elem)) (cdr elem))
1728                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
1729                  ((and (boundp header) (symbol-value header))
1730                   ;; The element is a symbol.  We insert the value
1731                   ;; of this symbol, if any.
1732                   (symbol-value header))
1733                  (t
1734                   ;; We couldn't generate a value for this header,
1735                   ;; so we just ask the user.
1736                   (read-from-minibuffer
1737                    (format "Empty header for %s; enter value: " header)))))
1738           ;; Finally insert the header.
1739           (when (and value 
1740                      (not (equal value "")))
1741             (save-excursion
1742               (if (bolp)
1743                   (progn
1744                     ;; This header didn't exist, so we insert it.
1745                     (goto-char (point-max))
1746                     (insert (symbol-name header) ": " value "\n")
1747                     (forward-line -1))
1748                 ;; The value of this header was empty, so we clear
1749                 ;; totally and insert the new value.
1750                 (delete-region (point) (message-point-at-eol))
1751                 (insert value))
1752               ;; Add the deletable property to the headers that require it.
1753               (and (memq header message-deletable-headers)
1754                    (progn (beginning-of-line) (looking-at "[^:]+: "))
1755                    (add-text-properties 
1756                     (point) (match-end 0)
1757                     '(message-deletable t face italic) (current-buffer)))))))
1758       ;; Insert new Sender if the From is strange. 
1759       (let ((from (mail-fetch-field "from"))
1760             (sender (mail-fetch-field "sender"))
1761             (secure-sender (message-make-sender)))
1762         (when (and from 
1763                    (not (message-check-element 'sender))
1764                    (not (string=
1765                          (downcase
1766                           (cadr (mail-extract-address-components from)))
1767                          (downcase secure-sender)))
1768                    (or (null sender)
1769                        (not 
1770                         (string=
1771                          (downcase
1772                           (cadr (mail-extract-address-components sender)))
1773                          (downcase secure-sender)))))
1774           (goto-char (point-min))    
1775           ;; Rename any old Sender headers to Original-Sender.
1776           (when (re-search-forward "^Sender:" nil t)
1777             (beginning-of-line)
1778             (insert "Original-")
1779             (beginning-of-line))
1780           (insert "Sender: " secure-sender "\n"))))))
1781
1782 (defun message-insert-courtesy-copy ()
1783   "Insert a courtesy message in mail copies of combined messages."
1784   (save-excursion
1785     (save-restriction
1786       (message-narrow-to-headers)
1787       (let ((newsgroups (mail-fetch-field "newsgroups")))
1788         (when newsgroups
1789           (goto-char (point-max))
1790           (insert "Posted-To: " newsgroups "\n"))))
1791     (forward-line 1)
1792     (insert message-courtesy-message)))
1793     
1794 ;;;
1795 ;;; Setting up a message buffer
1796 ;;;
1797
1798 (defun message-fill-header (header value)
1799   (let ((begin (point))
1800         (fill-column 78)
1801         (fill-prefix "\t")
1802         end)
1803     (insert (capitalize (symbol-name header))
1804             ": "
1805             (if (consp value) (car value) value)
1806             "\n")
1807     (save-restriction
1808       (narrow-to-region begin (point))
1809       (fill-region-as-paragraph begin (point))
1810       ;; Tapdance around looong Message-IDs.
1811       (forward-line -1)
1812       (when (looking-at "[ \t]*$")
1813         (message-delete-line))
1814       (goto-char begin)
1815       (re-search-forward ":" nil t)
1816       (when (looking-at "\n[ \t]+")
1817         (replace-match " " t t))
1818       (goto-char (point-max)))))
1819
1820 (defun message-position-point ()
1821   "Move point to where the user probably wants to find it."
1822   (message-narrow-to-headers)
1823   (cond 
1824    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
1825     (search-backward ":" )
1826     (widen)
1827     (forward-char 1)
1828     (if (= (following-char) ? )
1829         (forward-char 1)
1830       (insert " ")))
1831    (t
1832     (goto-char (point-max))
1833     (widen)
1834     (forward-line 1)
1835     (unless (looking-at "$")
1836       (forward-line 2)))
1837    (sit-for 0)))
1838
1839 (defun message-pop-to-buffer (name)
1840   "Pop to buffer NAME, and warn if it already exists and is modified."
1841   (let ((buffer (get-buffer name)))
1842     (if (and buffer
1843              (buffer-name buffer))
1844         (progn
1845           (set-buffer (pop-to-buffer buffer))
1846           (when (and (buffer-modified-p)
1847                      (not (y-or-n-p
1848                            "Message already being composed; erase? ")))
1849             (error "Message being composed")))
1850       (set-buffer (pop-to-buffer name)))
1851     (erase-buffer)
1852     (message-mode)))
1853
1854 (defun message-setup (headers &optional replybuffer actions)
1855   (setq message-send-actions actions)
1856   (setq message-reply-buffer replybuffer)
1857   (goto-char (point-min))
1858   ;; Insert all the headers.
1859   (mail-header-format 
1860    (let ((h headers)
1861          (alist message-header-format-alist))
1862      (while h
1863        (unless (assq (caar h) message-header-format-alist)
1864          (push (list (caar h)) alist))
1865        (pop h))
1866      alist)
1867    headers)
1868   (forward-line -1)
1869   (when message-default-headers
1870     (insert message-default-headers))
1871   (insert mail-header-separator "\n")
1872   (forward-line -1)
1873   (when (message-news-p)
1874     (when message-default-news-headers
1875       (insert message-default-news-headers))
1876     (when message-generate-headers-first
1877       (message-generate-headers message-required-news-headers)))
1878   (when (message-mail-p)
1879     (when message-default-mail-headers
1880       (insert message-default-mail-headers))
1881     (when message-generate-headers-first
1882       (message-generate-headers message-required-mail-headers)))
1883   (message-insert-signature)
1884   (message-set-auto-save-file-name)
1885   (save-restriction
1886     (message-narrow-to-headers)
1887     (run-hooks 'message-header-setup-hook))
1888   ;; Allow mail alias things.
1889   (if (fboundp 'mail-abbrevs-setup)
1890       (mail-abbrevs-setup)
1891     (mail-aliases-setup))
1892   (set-buffer-modified-p nil)
1893   (run-hooks 'message-setup-hook)
1894   (message-position-point)
1895   (undo-boundary))
1896
1897 (defun message-set-auto-save-file-name ()
1898   "Associate the message buffer with a file in the drafts directory."
1899   (when message-autosave-directory
1900     (unless (file-exists-p message-autosave-directory)
1901       (make-directory message-autosave-directory t))
1902     (let ((name (make-temp-name
1903                  (concat (file-name-as-directory message-autosave-directory)
1904                          "msg."))))
1905       (setq buffer-auto-save-file-name
1906             (save-excursion
1907               (prog1
1908                   (progn
1909                     (set-buffer (get-buffer-create " *draft tmp*"))
1910                     (setq buffer-file-name name)
1911                     (make-auto-save-file-name))
1912                 (kill-buffer (current-buffer)))))
1913       (clear-visited-file-modtime))))
1914
1915 \f
1916
1917 ;;;
1918 ;;; Commands for interfacing with message
1919 ;;;
1920
1921 ;;;###autoload
1922 (defun message-mail (&optional to subject)
1923   "Start editing a mail message to be sent."
1924   (interactive)
1925   (message-pop-to-buffer "*mail message*")
1926   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
1927
1928 ;;;###autoload
1929 (defun message-news (&optional newsgroups subject)
1930   "Start editing a news article to be sent."
1931   (interactive)
1932   (message-pop-to-buffer "*news message*")
1933   (message-setup `((Newsgroups . ,(or newsgroups "")) 
1934                    (Subject . ,(or subject "")))))
1935
1936 ;;;###autoload
1937 (defun message-reply (&optional to-address wide)
1938   "Start editing a reply to the article in the current buffer."
1939   (interactive)
1940   (let ((cur (current-buffer))
1941         from subject date reply-to message-of to cc
1942         references message-id sender follow-to sendto elt new-cc new-to
1943         mct never-mct gnus-warning)
1944     (save-restriction
1945       (narrow-to-region
1946        (goto-char (point-min))
1947        (if (search-forward "\n\n" nil t)
1948            (1- (point))
1949          (point-max)))
1950       ;; Allow customizations to have their say.
1951       (if (not wide)
1952           ;; This is a regular reply.
1953           (if (message-functionp message-reply-to-function)
1954               (setq follow-to (funcall message-reply-to-function)))
1955         ;; This is a followup.
1956         (if (message-functionp message-wide-reply-to-function)
1957             (save-excursion
1958               (setq follow-to
1959                     (funcall message-wide-reply-to-function)))))
1960       ;; Find all relevant headers we need.
1961       (setq from (mail-fetch-field "from")
1962             date (mail-fetch-field "date") 
1963             sender (mail-fetch-field "sender")
1964             subject (or (mail-fetch-field "subject") "none")
1965             to (mail-fetch-field "to")
1966             cc (mail-fetch-field "cc")
1967             mct (mail-fetch-field "mail-copies-to")
1968             reply-to (mail-fetch-field "reply-to")
1969             references (mail-fetch-field "references")
1970             message-id (mail-fetch-field "message-id"))
1971       ;; Remove any (buggy) Re:'s that are present and make a
1972       ;; proper one.
1973       (when (string-match "^[ \t]*[Re][Ee]:[ \t]*" subject)
1974         (setq subject (substring subject (match-end 0))))
1975       (setq subject (concat "Re: " subject))
1976
1977       (when (and (setq gnus-warning (mail-fetch-field "gnus-warning"))
1978                  (string-match "<[^>]+>" gnus-warning))
1979         (setq message-id (match-string 0 gnus-warning)))
1980             
1981       ;; Handle special values of Mail-Copies-To.
1982       (when mct
1983         (cond ((equal (downcase mct) "never")
1984                (setq never-mct t)
1985                (setq mct nil))
1986               ((equal (downcase mct) "always")
1987                (setq mct (or reply-to from)))))
1988
1989       (unless follow-to
1990         (if (or (not wide)
1991                 to-address)
1992             (setq follow-to (list (cons 'To (or to-address reply-to from))))
1993           (let (ccalist)
1994             (save-excursion
1995               (message-set-work-buffer)
1996               (unless never-mct
1997                 (insert (or reply-to from "")))
1998               (insert 
1999                (if (bolp) "" ", ") (or to "")
2000                (if mct (concat (if (bolp) "" ", ") mct) "")
2001                (if cc (concat (if (bolp) "" ", ") cc) ""))
2002               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2003               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2004                         (erase-buffer)))
2005               (goto-char (point-min))
2006               (setq ccalist
2007                     (mapcar
2008                      (lambda (addr)
2009                        (cons (mail-strip-quoted-names addr) addr))
2010                      (nreverse (mail-parse-comma-list))))
2011               (let ((s ccalist))
2012                 (while s
2013                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2014             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2015             (when ccalist
2016               (push (cons 'Cc
2017                           (mapconcat (lambda (addr) (cdr addr)) ccalist ", "))
2018                     follow-to)))))
2019       (widen))
2020
2021     (message-pop-to-buffer "*mail message*")
2022
2023     (setq message-reply-headers
2024           (vector 0 subject from date message-id references 0 0 ""))
2025
2026     (message-setup
2027      `((Subject . ,subject)
2028        ,@follow-to 
2029        (References . ,(concat (or references "") (and references " ")
2030                               (or message-id ""))))
2031      cur)))
2032
2033 ;;;###autoload
2034 (defun message-wide-reply (&optional to-address)
2035   (interactive)
2036   (message-reply to-address t))
2037
2038 ;;;###autoload
2039 (defun message-followup ()
2040   (interactive)
2041   (let ((cur (current-buffer))
2042         from subject date message-of reply-to mct
2043         references message-id follow-to sendto elt 
2044         followup-to distribution newsgroups gnus-warning)
2045     (save-restriction
2046       (narrow-to-region
2047        (goto-char (point-min))
2048        (if (search-forward "\n\n" nil t)
2049            (1- (point))
2050          (point-max)))
2051       (when (message-functionp message-followup-to-function)
2052         (setq follow-to
2053               (funcall message-followup-to-function)))
2054       (setq from (mail-fetch-field "from")
2055             date (mail-fetch-field "date") 
2056             subject (or (mail-fetch-field "subject") "none")
2057             references (mail-fetch-field "references")
2058             message-id (mail-fetch-field "message-id")
2059             followup-to (mail-fetch-field "followup-to")
2060             newsgroups (mail-fetch-field "newsgroups")
2061             reply-to (mail-fetch-field "reply-to")
2062             distribution (mail-fetch-field "distribution")
2063             mct (mail-fetch-field "mail-copies-to"))
2064       (when (and (setq gnus-warning (mail-fetch-field "gnus-warning"))
2065                  (string-match "<[^>]+>" gnus-warning))
2066         (setq message-id (match-string 0 gnus-warning)))
2067       ;; Remove bogus distribution.
2068       (and (stringp distribution)
2069            (string-match "world" distribution)
2070            (setq distribution nil))
2071       ;; Remove any (buggy) Re:'s that are present and make a
2072       ;; proper one.
2073       (when (string-match "^[ \t]*[Re][Ee]:[ \t]*" subject)
2074         (setq subject (substring subject (match-end 0))))
2075       (setq subject (concat "Re: " subject))
2076       (widen))
2077
2078     (message-pop-to-buffer "*news message*")
2079
2080     (message-setup
2081      `((Subject . ,subject)
2082        ,@(cond 
2083           (follow-to follow-to)
2084           ((and followup-to message-use-followup-to)
2085            (list
2086             (cond 
2087              ((equal (downcase followup-to) "poster")
2088               (if (or (eq message-use-followup-to 'use)
2089                       (y-or-n-p "Use Followup-To \"poster\"? "))
2090                   (cons 'To (or reply-to from ""))
2091                 (cons 'Newsgroups newsgroups)))
2092              (t
2093               (if (or (equal followup-to newsgroups)
2094                       (not (eq message-use-followup-to 'ask))
2095                       (y-or-n-p (format "Use Followup-To %s? " followup-to)))
2096                   (cons 'Newsgroups followup-to)
2097                 (cons 'Newsgroups newsgroups))))))
2098           (t
2099            `((Newsgroups . ,newsgroups))))
2100        ,@(and distribution (list (cons 'Distribution distribution)))
2101        (References . ,(concat (or references "") (and references " ")
2102                               (or message-id "")))
2103        ,@(when (and mct
2104                     (not (equal (downcase mct) "never")))
2105            (list (cons 'Cc (if (equal (downcase mct) "always")
2106                                (or reply-to from "")
2107                              mct)))))
2108
2109      cur)
2110
2111     (setq message-reply-headers
2112           (vector 0 subject from date message-id references 0 0 ""))))
2113
2114
2115 ;;;###autoload
2116 (defun message-cancel-news ()
2117   "Cancel an article you posted."
2118   (interactive)
2119   (unless (message-news-p)
2120     (error "This is not a news article; canceling is impossible"))
2121   (when (yes-or-no-p "Do you really want to cancel this article? "))
2122   (let (from newsgroups message-id distribution buf)
2123     (save-excursion
2124       ;; Get header info. from original article.
2125       (save-restriction
2126         (message-narrow-to-head)
2127         (setq from (mail-fetch-field "from")
2128               newsgroups (mail-fetch-field "newsgroups")
2129               message-id (mail-fetch-field "message-id")
2130               distribution (mail-fetch-field "distribution")))
2131       ;; Make sure that this article was written by the user.
2132       (unless (string-equal
2133                (downcase (mail-strip-quoted-names from))
2134                (downcase (message-make-address)))
2135         (error "This article is not yours"))
2136       ;; Make control message.
2137       (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2138       (buffer-disable-undo (current-buffer))
2139       (erase-buffer)
2140       (insert "Newsgroups: " newsgroups "\n"
2141               "From: " (message-make-from) "\n"
2142               "Subject: cmsg cancel " message-id "\n"
2143               "Control: cancel " message-id "\n"
2144               (if distribution
2145                   (concat "Distribution: " distribution "\n")
2146                 "")
2147               mail-header-separator "\n"
2148               "This is a cancel message from " from ".\n")
2149       (message "Canceling your article...")
2150       (let (message-syntax-checks)
2151         (funcall message-send-news-function))
2152       (message "Canceling your article...done")
2153       (kill-buffer buf))))
2154
2155 ;;;###autoload
2156 (defun message-supersede ()
2157   "Start composing a message to supersede the current message.
2158 This is done simply by taking the old article and adding a Supersedes
2159 header line with the old Message-ID."
2160   (interactive)
2161   (let ((cur (current-buffer)))
2162     ;; Check whether the user owns the article that is to be superseded. 
2163     (unless (string-equal
2164              (downcase (mail-strip-quoted-names (mail-fetch-field "from")))
2165              (downcase (mail-strip-quoted-names (message-make-address))))
2166       (error "This article is not yours"))
2167     ;; Get a normal message buffer.
2168     (message-pop-to-buffer "*supersede message*")
2169     (insert-buffer-substring cur)
2170     (message-narrow-to-head)
2171     ;; Remove unwanted headers.
2172     (when message-ignored-supersedes-headers
2173       (message-remove-header message-ignored-supersedes-headers t))
2174     (goto-char (point-min))
2175     (if (not (re-search-forward "^Message-ID: " nil t))
2176         (error "No Message-ID in this article")
2177       (replace-match "Supersedes: " t t))
2178     (goto-char (point-max))
2179     (insert mail-header-separator)
2180     (widen)
2181     (forward-line 1)))
2182
2183 ;;;###autoload
2184 (defun message-recover ()
2185   "Reread contents of current buffer from its last auto-save file."
2186   (interactive)
2187   (let ((file-name (make-auto-save-file-name)))
2188     (cond ((save-window-excursion
2189              (if (not (eq system-type 'vax-vms))
2190                  (with-output-to-temp-buffer "*Directory*"
2191                    (buffer-disable-undo standard-output)
2192                    (let ((default-directory "/"))
2193                      (call-process
2194                       "ls" nil standard-output nil "-l" file-name))))
2195              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2196            (let ((buffer-read-only nil))
2197              (erase-buffer)
2198              (insert-file-contents file-name nil)))
2199           (t (error "message-recover cancelled")))))
2200
2201 ;;; Forwarding messages.
2202
2203 (defun message-make-forward-subject ()
2204   "Return a Subject header suitable for the message in the current buffer."
2205   (concat "[" (mail-fetch-field (if (message-news-p) "newsgroups" "from"))
2206           "] " (or (mail-fetch-field "Subject") "")))
2207
2208 ;;;###autoload
2209 (defun message-forward (&optional news)
2210   "Forward the current message via mail.  
2211 Optional NEWS will use news to forward instead of mail."
2212   (interactive "P")
2213   (let ((cur (current-buffer))
2214         (subject (message-make-forward-subject)))
2215     (if news (message-news nil subject) (message-mail nil subject))
2216     ;; Put point where we want it before inserting the forwarded
2217     ;; message. 
2218     (if message-signature-before-forwarded-message
2219         (goto-char (point-max))
2220       (message-goto-body))
2221     ;; Narrow to the area we are to insert.
2222     (narrow-to-region (point) (point))
2223     ;; Insert the separators and the forwarded buffer.
2224     (insert message-forward-start-separator)
2225     (insert-buffer-substring cur)
2226     (goto-char (point-max))
2227     (insert message-forward-end-separator)
2228     (set-text-properties (point-min) (point-max) nil)
2229     ;; Remove all unwanted headers.
2230     (goto-char (point-min))
2231     (forward-line 1)
2232     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
2233                                   (1- (point))
2234                                 (point)))
2235     (goto-char (point-min))
2236     (message-remove-header message-included-forward-headers t nil t)
2237     (widen)
2238     (message-position-point)))
2239
2240 ;;;###autoload
2241 (defun message-resend (address)
2242   "Resend the current article to ADDRESS."
2243   (interactive "sResend message to: ")
2244   (save-excursion
2245     (let ((cur (current-buffer))
2246           beg)
2247       ;; We first set up a normal mail buffer.
2248       (set-buffer (get-buffer-create " *message resend*"))
2249       (buffer-disable-undo (current-buffer))
2250       (erase-buffer)
2251       (message-setup `((To . ,address)))
2252       ;; Insert our usual headers.
2253       (message-generate-headers '(From Date To))
2254       (message-narrow-to-headers)
2255       ;; Rename them all to "Resent-*".
2256       (while (re-search-forward "^[A-Za-z]" nil t)
2257         (forward-char -1)
2258         (insert "Resent-"))
2259       (widen)
2260       (forward-line)
2261       (delete-region (point) (point-max))
2262       (setq beg (point))
2263       ;; Insert the message to be resent.
2264       (insert-buffer-substring cur)
2265       (goto-char (point-min))
2266       (search-forward "\n\n")
2267       (forward-char -1)
2268       (save-restriction
2269         (narrow-to-region beg (point))
2270         (message-remove-header message-ignored-resent-headers t)
2271         (goto-char (point-max)))
2272       (insert mail-header-separator)
2273       ;; Rename all old ("Also-")Resent headers.
2274       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
2275         (beginning-of-line)
2276         (insert "Also-"))
2277       ;; Send it.
2278       (funcall message-send-mail-function)
2279       (kill-buffer (current-buffer)))))
2280
2281 ;;;###autoload
2282 (defun message-bounce ()
2283   "Re-mail the current message.
2284 This only makes sense if the current message is a bounce message than
2285 contains some mail you have written which has been bounced back to
2286 you."
2287   (interactive "P")
2288   (let ((cur (current-buffer)))
2289     (message-pop-to-buffer "*mail message*")
2290     (insert-buffer-substring cur)
2291     (undo-boundary)
2292     (goto-char (point-min))
2293     (or (and (re-search-forward mail-unsent-separator nil t)
2294              (forward-line 1))
2295         (and (search-forward "\n\n" nil t)
2296              (re-search-forward "^Return-Path:.*\n" nil t)))
2297     ;; We remove everything before the bounced mail.
2298     (delete-region 
2299      (point-min)
2300      (if (re-search-forward "[^ \t]*:" nil t)
2301          (match-beginning 0)
2302        (point)))
2303     (save-restriction
2304       (message-narrow-to-head)
2305       (message-remove-header message-ignored-bounced-headers t)
2306       (goto-char (point-max))
2307       (insert mail-header-separator))
2308     (message-position-point)))
2309
2310 ;;;
2311 ;;; Interactive entry points for new message buffers.
2312 ;;;
2313
2314 ;;;###autoload
2315 (defun message-mail-other-window (&optional to subject)
2316   "Like `message-mail' command, but display mail buffer in another window."
2317   (interactive)
2318   (let ((pop-up-windows t)
2319         (special-display-buffer-names nil)
2320         (special-display-regexps nil)
2321         (same-window-buffer-names nil)
2322         (same-window-regexps nil))
2323     (message-pop-to-buffer "*mail message*"))
2324   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2325
2326 ;;;###autoload
2327 (defun message-mail-other-frame (&optional to subject)
2328   "Like `message-mail' command, but display mail buffer in another frame."
2329   (interactive)
2330   (let ((pop-up-frames t)
2331         (special-display-buffer-names nil)
2332         (special-display-regexps nil)
2333         (same-window-buffer-names nil)
2334         (same-window-regexps nil))
2335     (message-pop-to-buffer "*mail message*"))
2336   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2337
2338 ;;;###autoload
2339 (defun message-news-other-window (&optional newsgroups subject)
2340   "Start editing a news article to be sent."
2341   (interactive)
2342   (let ((pop-up-windows t)
2343         (special-display-buffer-names nil)
2344         (special-display-regexps nil)
2345         (same-window-buffer-names nil)
2346         (same-window-regexps nil))
2347     (message-pop-to-buffer "*news message*"))
2348   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2349                    (Subject . ,(or subject "")))))
2350
2351 ;;;###autoload
2352 (defun message-news-other-frame (&optional newsgroups subject)
2353   "Start editing a news article to be sent."
2354   (interactive)
2355   (let ((pop-up-frames t)
2356         (special-display-buffer-names nil)
2357         (special-display-regexps nil)
2358         (same-window-buffer-names nil)
2359         (same-window-regexps nil))
2360     (message-pop-to-buffer "*news message*"))
2361   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2362                    (Subject . ,(or subject "")))))
2363
2364 ;;; underline.el
2365
2366 ;; This code should be moved to underline.el (from which it is stolen). 
2367
2368 ;;;###autoload
2369 (defun bold-region (start end)
2370   "Bold all nonblank characters in the region.
2371 Works by overstriking characters.
2372 Called from program, takes two arguments START and END
2373 which specify the range to operate on."
2374   (interactive "r")
2375   (save-excursion
2376    (let ((end1 (make-marker)))
2377      (move-marker end1 (max start end))
2378      (goto-char (min start end))
2379      (while (< (point) end1)
2380        (or (looking-at "[_\^@- ]")
2381            (insert (following-char) "\b"))
2382        (forward-char 1)))))
2383
2384 ;;;###autoload
2385 (defun unbold-region (start end)
2386   "Remove all boldness (overstruck characters) in the region.
2387 Called from program, takes two arguments START and END
2388 which specify the range to operate on."
2389   (interactive "r")
2390   (save-excursion
2391    (let ((end1 (make-marker)))
2392      (move-marker end1 (max start end))
2393      (goto-char (min start end)) 
2394      (while (re-search-forward "\b" end1 t)
2395        (if (eq (following-char) (char-after (- (point) 2)))
2396            (delete-char -2))))))
2397
2398 (provide 'message)
2399
2400 ;;; message.el ends here