Indent.
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers)) ; gnus-sum is required where necessary
36 (require 'canlock)
37 (require 'mailheader)
38 (require 'nnheader)
39 ;; This is apparently necessary even though things are autoloaded.
40 ;; Because we dynamically bind mail-abbrev-mode-regexp, we'd better
41 ;; require mailabbrev here.
42 (if (featurep 'xemacs)
43     (require 'mail-abbrevs)
44   (require 'mailabbrev))
45 (require 'mail-parse)
46 (require 'mml)
47 (require 'rfc822)
48 (eval-and-compile
49   (autoload 'sha1 "sha1-el"))
50
51 (defgroup message '((user-mail-address custom-variable)
52                     (user-full-name custom-variable))
53   "Mail and news message composing."
54   :link '(custom-manual "(message)Top")
55   :group 'mail
56   :group 'news)
57
58 (put 'user-mail-address 'custom-type 'string)
59 (put 'user-full-name 'custom-type 'string)
60
61 (defgroup message-various nil
62   "Various Message Variables"
63   :link '(custom-manual "(message)Various Message Variables")
64   :group 'message)
65
66 (defgroup message-buffers nil
67   "Message Buffers"
68   :link '(custom-manual "(message)Message Buffers")
69   :group 'message)
70
71 (defgroup message-sending nil
72   "Message Sending"
73   :link '(custom-manual "(message)Sending Variables")
74   :group 'message)
75
76 (defgroup message-interface nil
77   "Message Interface"
78   :link '(custom-manual "(message)Interface")
79   :group 'message)
80
81 (defgroup message-forwarding nil
82   "Message Forwarding"
83   :link '(custom-manual "(message)Forwarding")
84   :group 'message-interface)
85
86 (defgroup message-insertion nil
87   "Message Insertion"
88   :link '(custom-manual "(message)Insertion")
89   :group 'message)
90
91 (defgroup message-headers nil
92   "Message Headers"
93   :link '(custom-manual "(message)Message Headers")
94   :group 'message)
95
96 (defgroup message-news nil
97   "Composing News Messages"
98   :group 'message)
99
100 (defgroup message-mail nil
101   "Composing Mail Messages"
102   :group 'message)
103
104 (defgroup message-faces nil
105   "Faces used for message composing."
106   :group 'message
107   :group 'faces)
108
109 (defcustom message-directory "~/Mail/"
110   "*Directory from which all other mail file variables are derived."
111   :group 'message-various
112   :type 'directory)
113
114 (defcustom message-max-buffers 10
115   "*How many buffers to keep before starting to kill them off."
116   :group 'message-buffers
117   :type 'integer)
118
119 (defcustom message-send-rename-function nil
120   "Function called to rename the buffer after sending it."
121   :group 'message-buffers
122   :type '(choice function (const nil)))
123
124 (defcustom message-fcc-handler-function 'message-output
125   "*A function called to save outgoing articles.
126 This function will be called with the name of the file to store the
127 article in.  The default function is `message-output' which saves in Unix
128 mailbox format."
129   :type '(radio (function-item message-output)
130                 (function :tag "Other"))
131   :group 'message-sending)
132
133 (defcustom message-fcc-externalize-attachments nil
134   "If non-nil, attachments are included as external parts in Fcc copies."
135   :type 'boolean
136   :group 'message-sending)
137
138 (defcustom message-courtesy-message
139   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
140   "*This is inserted at the start of a mailed copy of a posted message.
141 If the string contains the format spec \"%s\", the Newsgroups
142 the article has been posted to will be inserted there.
143 If this variable is nil, no such courtesy message will be added."
144   :group 'message-sending
145   :type 'string)
146
147 (defcustom message-ignored-bounced-headers
148   "^\\(Received\\|Return-Path\\|Delivered-To\\):"
149   "*Regexp that matches headers to be removed in resent bounced mail."
150   :group 'message-interface
151   :type 'regexp)
152
153 ;;;###autoload
154 (defcustom message-from-style 'default
155   "*Specifies how \"From\" headers look.
156
157 If nil, they contain just the return address like:
158         king@grassland.com
159 If `parens', they look like:
160         king@grassland.com (Elvis Parsley)
161 If `angles', they look like:
162         Elvis Parsley <king@grassland.com>
163
164 Otherwise, most addresses look like `angles', but they look like
165 `parens' if `angles' would need quoting and `parens' would not."
166   :type '(choice (const :tag "simple" nil)
167                  (const parens)
168                  (const angles)
169                  (const default))
170   :group 'message-headers)
171
172 (defcustom message-insert-canlock t
173   "Whether to insert a Cancel-Lock header in news postings."
174   :version "21.3"
175   :group 'message-headers
176   :type 'boolean)
177
178 (defcustom message-syntax-checks
179   (if message-insert-canlock '((sender . disabled)) nil)
180   ;; Guess this one shouldn't be easy to customize...
181   "*Controls what syntax checks should not be performed on outgoing posts.
182 To disable checking of long signatures, for instance, add
183  `(signature . disabled)' to this list.
184
185 Don't touch this variable unless you really know what you're doing.
186
187 Checks include `subject-cmsg', `multiple-headers', `sendsys',
188 `message-id', `from', `long-lines', `control-chars', `size',
189 `new-text', `quoting-style', `redirected-followup', `signature',
190 `approved', `sender', `empty', `empty-headers', `message-id', `from',
191 `subject', `shorten-followup-to', `existing-newsgroups',
192 `buffer-file-name', `unchanged', `newsgroups', `reply-to',
193 'continuation-headers', and `long-header-lines'."
194   :group 'message-news
195   :type '(repeat sexp))                 ; Fixme: improve this
196
197 (defcustom message-required-headers '((optional . References)
198                                       From)
199   "*Headers to be generated or prompted for when sending a message.
200 Also see `message-required-news-headers' and
201 `message-required-mail-headers'."
202   :group 'message-news
203   :group 'message-headers
204   :type '(repeat sexp))
205
206 (defcustom message-draft-headers '(References From)
207   "*Headers to be generated when saving a draft message."
208   :group 'message-news
209   :group 'message-headers
210   :type '(repeat sexp))
211
212 (defcustom message-required-news-headers
213   '(From Newsgroups Subject Date Message-ID
214          (optional . Organization)
215          (optional . User-Agent))
216   "*Headers to be generated or prompted for when posting an article.
217 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
218 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
219 User-Agent are optional.  If don't you want message to insert some
220 header, remove it from this list."
221   :group 'message-news
222   :group 'message-headers
223   :type '(repeat sexp))
224
225 (defcustom message-required-mail-headers
226   '(From Subject Date (optional . In-Reply-To) Message-ID
227          (optional . User-Agent))
228   "*Headers to be generated or prompted for when mailing a message.
229 It is recommended that From, Date, To, Subject and Message-ID be
230 included.  Organization and User-Agent are optional."
231   :group 'message-mail
232   :group 'message-headers
233   :type '(repeat sexp))
234
235 (defcustom message-deletable-headers '(Message-ID Date Lines)
236   "Headers to be deleted if they already exist and were generated by message previously."
237   :group 'message-headers
238   :type 'sexp)
239
240 (defcustom message-ignored-news-headers
241   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
242   "*Regexp of headers to be removed unconditionally before posting."
243   :group 'message-news
244   :group 'message-headers
245   :type 'regexp)
246
247 (defcustom message-ignored-mail-headers
248   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
249   "*Regexp of headers to be removed unconditionally before mailing."
250   :group 'message-mail
251   :group 'message-headers
252   :type 'regexp)
253
254 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:\\|^X-Hashcash:"
255   "*Header lines matching this regexp will be deleted before posting.
256 It's best to delete old Path and Date headers before posting to avoid
257 any confusion."
258   :group 'message-interface
259   :type 'regexp)
260
261 (defcustom message-subject-re-regexp
262   "^[ \t]*\\([Rr][Ee]\\(\\[[0-9]*\\]\\)*:[ \t]*\\)*[ \t]*"
263   "*Regexp matching \"Re: \" in the subject line."
264   :group 'message-various
265   :type 'regexp)
266
267 ;;; Start of variables adopted from `message-utils.el'.
268
269 (defcustom message-subject-trailing-was-query 'ask
270   ;; should it default to nil or ask?
271   "*What to do with trailing \"(was: <old subject>)\" in subject lines.
272 If nil, leave the subject unchanged.  If it is the symbol `ask', query
273 the user what do do.  In this case, the subject is matched against
274 `message-subject-trailing-was-ask-regexp'.  If
275 `message-subject-trailing-was-query' is t, always strip the trailing
276 old subject.  In this case, `message-subject-trailing-was-regexp' is
277 used."
278   :type '(choice (const :tag "never" nil)
279                  (const :tag "always strip" t)
280                  (const ask))
281   :group 'message-various)
282
283 (defcustom message-subject-trailing-was-ask-regexp
284   "[ \t]*\\([[(]+[Ww][Aa][Ss][ \t]*.*[\])]+\\)"
285   "*Regexp matching \"(was: <old subject>)\" in the subject line.
286
287 The function `message-strip-subject-trailing-was' uses this regexp if
288 `message-subject-trailing-was-query' is set to the symbol `ask'.  If
289 the variable is t instead of `ask', use
290 `message-subject-trailing-was-regexp' instead.
291
292 It is okay to create some false positives here, as the user is asked."
293   :group 'message-various
294   :type 'regexp)
295
296 (defcustom message-subject-trailing-was-regexp
297   "[ \t]*\\((*[Ww][Aa][Ss]:[ \t]*.*)\\)"
298   "*Regexp matching \"(was: <old subject>)\" in the subject line.
299
300 If `message-subject-trailing-was-query' is set to t, the subject is
301 matched against `message-subject-trailing-was-regexp' in
302 `message-strip-subject-trailing-was'.  You should use a regexp creating very
303 few false positives here."
304   :group 'message-various
305   :type 'regexp)
306
307 ;; Fixme: Why are all these things autoloaded?
308
309 ;;; marking inserted text
310
311 ;;;###autoload
312 (defcustom message-mark-insert-begin
313   "--8<---------------cut here---------------start------------->8---\n"
314   "How to mark the beginning of some inserted text."
315   :type 'string
316   :group 'message-various)
317
318 ;;;###autoload
319 (defcustom message-mark-insert-end
320   "--8<---------------cut here---------------end--------------->8---\n"
321   "How to mark the end of some inserted text."
322   :type 'string
323   :group 'message-various)
324
325 ;;;###autoload
326 (defcustom message-archive-header
327   "X-No-Archive: Yes\n"
328   "Header to insert when you don't want your article to be archived.
329 Archives \(such as groups.googgle.com\) respect this header."
330   :type 'string
331   :group 'message-various)
332
333 ;;;###autoload
334 (defcustom message-archive-note
335   "X-No-Archive: Yes - save http://groups.google.com/"
336   "Note to insert why you wouldn't want this posting archived.
337 If nil, don't insert any text in the body."
338   :type 'string
339   :group 'message-various)
340
341 ;;; Crossposts and Followups
342 ;; inspired by JoH-followup-to by Jochem Huhman <joh  at gmx.de>
343 ;; new suggestions by R. Weikusat <rw at another.de>
344
345 (defvar message-cross-post-old-target nil
346   "Old target for cross-posts or follow-ups.")
347 (make-variable-buffer-local 'message-cross-post-old-target)
348
349 ;;;###autoload
350 (defcustom message-cross-post-default t
351   "When non-nil `message-cross-post-followup-to' will perform a crosspost.
352 If nil, `message-cross-post-followup-to' will only do a followup.  Note that
353 you can explicitly override this setting by calling
354 `message-cross-post-followup-to' with a prefix."
355   :type 'boolean
356   :group 'message-various)
357
358 ;;;###autoload
359 (defcustom message-cross-post-note
360   "Crosspost & Followup-To: "
361   "Note to insert before signature to notify of cross-post and follow-up."
362   :type 'string
363   :group 'message-various)
364
365 ;;;###autoload
366 (defcustom message-followup-to-note
367   "Followup-To: "
368   "Note to insert before signature to notify of follow-up only."
369   :type 'string
370   :group 'message-various)
371
372 ;;;###autoload
373 (defcustom message-cross-post-note-function
374   'message-cross-post-insert-note
375   "Function to use to insert note about Crosspost or Followup-To.
376 The function will be called with four arguments.  The function should not only
377 insert a note, but also ensure old notes are deleted.  See the documentation
378 for `message-cross-post-insert-note'."
379   :type 'function
380   :group 'message-various)
381
382 ;;; End of variables adopted from `message-utils.el'.
383
384 ;;;###autoload
385 (defcustom message-signature-separator "^-- *$"
386   "Regexp matching the signature separator."
387   :type 'regexp
388   :group 'message-various)
389
390 (defcustom message-elide-ellipsis "\n[...]\n\n"
391   "*The string which is inserted for elided text."
392   :type 'string
393   :group 'message-various)
394
395 (defcustom message-interactive t
396   "Non-nil means when sending a message wait for and display errors.
397 nil means let mailer mail back a message to report errors."
398   :group 'message-sending
399   :group 'message-mail
400   :type 'boolean)
401
402 (defcustom message-generate-new-buffers 'unique
403   "*Non-nil means create a new message buffer whenever `message-setup' is called.
404 If this is a function, call that function with three parameters:  The type,
405 the to address and the group name.  (Any of these may be nil.)  The function
406 should return the new buffer name."
407   :group 'message-buffers
408   :type '(choice (const :tag "off" nil)
409                  (const :tag "unique" unique)
410                  (const :tag "unsent" unsent)
411                  (function fun)))
412
413 (defcustom message-kill-buffer-on-exit nil
414   "*Non-nil means that the message buffer will be killed after sending a message."
415   :group 'message-buffers
416   :type 'boolean)
417
418 (eval-when-compile
419   (defvar gnus-local-organization))
420 (defcustom message-user-organization
421   (or (and (boundp 'gnus-local-organization)
422            (stringp gnus-local-organization)
423            gnus-local-organization)
424       (getenv "ORGANIZATION")
425       t)
426   "*String to be used as an Organization header.
427 If t, use `message-user-organization-file'."
428   :group 'message-headers
429   :type '(choice string
430                  (const :tag "consult file" t)))
431
432 ;;;###autoload
433 (defcustom message-user-organization-file "/usr/lib/news/organization"
434   "*Local news organization file."
435   :type 'file
436   :group 'message-headers)
437
438 (defcustom message-make-forward-subject-function
439   'message-forward-subject-name-subject
440   "*List of functions called to generate subject headers for forwarded messages.
441 The subject generated by the previous function is passed into each
442 successive function.
443
444 The provided functions are:
445
446 * `message-forward-subject-author-subject' (Source of article (author or
447       newsgroup)), in brackets followed by the subject
448 * `message-forward-subject-name-subject' (Source of article (name of author
449       or newsgroup)), in brackets followed by the subject
450 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
451       to it."
452   :group 'message-forwarding
453   :type '(radio (function-item message-forward-subject-author-subject)
454                 (function-item message-forward-subject-fwd)
455                 (repeat :tag "List of functions" function)))
456
457 (defcustom message-forward-as-mime t
458   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
459   :version "21.1"
460   :group 'message-forwarding
461   :type 'boolean)
462
463 (defcustom message-forward-show-mml t
464   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
465   :version "21.1"
466   :group 'message-forwarding
467   :type 'boolean)
468
469 (defcustom message-forward-before-signature t
470   "*If non-nil, put forwarded message before signature, else after."
471   :group 'message-forwarding
472   :type 'boolean)
473
474 (defcustom message-wash-forwarded-subjects nil
475   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
476   :group 'message-forwarding
477   :type 'boolean)
478
479 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:\\|^>?From "
480   "*All headers that match this regexp will be deleted when resending a message."
481   :group 'message-interface
482   :type 'regexp)
483
484 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
485   "*All headers that match this regexp will be deleted when forwarding a message."
486   :version "21.1"
487   :group 'message-forwarding
488   :type '(choice (const :tag "None" nil)
489                  regexp))
490
491 (defcustom message-ignored-cited-headers "."
492   "*Delete these headers from the messages you yank."
493   :group 'message-insertion
494   :type 'regexp)
495
496 (defcustom message-cite-prefix-regexp
497   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
498       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>|}+]\\)+"
499     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
500     (let ((old-table (syntax-table))
501           non-word-constituents)
502       (set-syntax-table text-mode-syntax-table)
503       (setq non-word-constituents
504             (concat
505              (if (string-match "\\w" "-")  "" "-")
506              (if (string-match "\\w" "_")  "" "_")
507              (if (string-match "\\w" ".")  "" ".")))
508       (set-syntax-table old-table)
509       (if (equal non-word-constituents "")
510           "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>|}+]\\)+"
511         (concat "\\([ \t]*\\(\\w\\|["
512                 non-word-constituents
513                 "]\\)+>+\\|[ \t]*[]>|}+]\\)+"))))
514   "*Regexp matching the longest possible citation prefix on a line."
515   :group 'message-insertion
516   :type 'regexp)
517
518 (defcustom message-cancel-message "I am canceling my own article.\n"
519   "Message to be inserted in the cancel message."
520   :group 'message-interface
521   :type 'string)
522
523 ;; Useful to set in site-init.el
524 ;;;###autoload
525 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
526   "Function to call to send the current buffer as mail.
527 The headers should be delimited by a line whose contents match the
528 variable `mail-header-separator'.
529
530 Valid values include `message-send-mail-with-sendmail' (the default),
531 `message-send-mail-with-mh', `message-send-mail-with-qmail',
532 `message-smtpmail-send-it', `smtpmail-send-it' and `feedmail-send-it'.
533
534 See also `send-mail-function'."
535   :type '(radio (function-item message-send-mail-with-sendmail)
536                 (function-item message-send-mail-with-mh)
537                 (function-item message-send-mail-with-qmail)
538                 (function-item message-smtpmail-send-it)
539                 (function-item smtpmail-send-it)
540                 (function-item feedmail-send-it)
541                 (function :tag "Other"))
542   :group 'message-sending
543   :group 'message-mail)
544
545 (defcustom message-send-news-function 'message-send-news
546   "Function to call to send the current buffer as news.
547 The headers should be delimited by a line whose contents match the
548 variable `mail-header-separator'."
549   :group 'message-sending
550   :group 'message-news
551   :type 'function)
552
553 (defcustom message-reply-to-function nil
554   "If non-nil, function that should return a list of headers.
555 This function should pick out addresses from the To, Cc, and From headers
556 and respond with new To and Cc headers."
557   :group 'message-interface
558   :type '(choice function (const nil)))
559
560 (defcustom message-wide-reply-to-function nil
561   "If non-nil, function that should return a list of headers.
562 This function should pick out addresses from the To, Cc, and From headers
563 and respond with new To and Cc headers."
564   :group 'message-interface
565   :type '(choice function (const nil)))
566
567 (defcustom message-followup-to-function nil
568   "If non-nil, function that should return a list of headers.
569 This function should pick out addresses from the To, Cc, and From headers
570 and respond with new To and Cc headers."
571   :group 'message-interface
572   :type '(choice function (const nil)))
573
574 (defcustom message-use-followup-to 'ask
575   "*Specifies what to do with Followup-To header.
576 If nil, always ignore the header.  If it is t, use its value, but
577 query before using the \"poster\" value.  If it is the symbol `ask',
578 always query the user whether to use the value.  If it is the symbol
579 `use', always use the value."
580   :group 'message-interface
581   :type '(choice (const :tag "ignore" nil)
582                  (const :tag "use & query" t)
583                  (const use)
584                  (const ask)))
585
586 (defcustom message-use-mail-followup-to 'use
587   "*Specifies what to do with Mail-Followup-To header.
588 If nil, always ignore the header.  If it is the symbol `ask', always
589 query the user whether to use the value.  If it is the symbol `use',
590 always use the value."
591   :group 'message-interface
592   :type '(choice (const :tag "ignore" nil)
593                  (const use)
594                  (const ask)))
595
596 (defcustom message-subscribed-address-functions nil
597   "*Specifies functions for determining list subscription.
598 If nil, do not attempt to determine list subscribtion with functions.
599 If non-nil, this variable contains a list of functions which return
600 regular expressions to match lists.  These functions can be used in
601 conjunction with `message-subscribed-regexps' and
602 `message-subscribed-addresses'."
603   :group 'message-interface
604   :type '(repeat sexp))
605
606 (defcustom message-subscribed-address-file nil
607   "*A file containing addresses the user is subscribed to.
608 If nil, do not look at any files to determine list subscriptions.  If
609 non-nil, each line of this file should be a mailing list address."
610   :group 'message-interface
611   :type 'string)
612
613 (defcustom message-subscribed-addresses nil
614   "*Specifies a list of addresses the user is subscribed to.
615 If nil, do not use any predefined list subscriptions.  This list of
616 addresses can be used in conjuction with
617 `message-subscribed-address-functions' and `message-subscribed-regexps'."
618   :group 'message-interface
619   :type '(repeat string))
620
621 (defcustom message-subscribed-regexps nil
622   "*Specifies a list of addresses the user is subscribed to.
623 If nil, do not use any predefined list subscriptions.  This list of
624 regular expressions can be used in conjuction with
625 `message-subscribed-address-functions' and `message-subscribed-addresses'."
626   :group 'message-interface
627   :type '(repeat regexp))
628
629 (defcustom message-allow-no-recipients 'ask
630   "Specifies what to do when there are no recipients other than Gcc/Fcc.
631 If it is the symbol `always', the posting is allowed.  If it is the
632 symbol `never', the posting is not allowed.  If it is the symbol
633 `ask', you are prompted."
634   :group 'message-interface
635   :type '(choice (const always)
636                  (const never)
637                  (const ask)))
638
639 (defcustom message-sendmail-f-is-evil nil
640   "*Non-nil means don't add \"-f username\" to the sendmail command line.
641 Doing so would be even more evil than leaving it out."
642   :group 'message-sending
643   :type 'boolean)
644
645 (defcustom message-sendmail-envelope-from nil
646   "*Envelope-from when sending mail with sendmail.
647 If this is nil, use `user-mail-address'.  If it is the symbol
648 `header', use the From: header of the message."
649   :type '(choice (string :tag "From name")
650                  (const :tag "Use From: header from message" header)
651                  (const :tag "Use `user-mail-address'" nil))
652   :group 'message-sending)
653
654 ;; qmail-related stuff
655 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
656   "Location of the qmail-inject program."
657   :group 'message-sending
658   :type 'file)
659
660 (defcustom message-qmail-inject-args nil
661   "Arguments passed to qmail-inject programs.
662 This should be a list of strings, one string for each argument.  It
663 may also be a function.
664
665 For e.g., if you wish to set the envelope sender address so that bounces
666 go to the right place or to deal with listserv's usage of that address, you
667 might set this variable to '(\"-f\" \"you@some.where\")."
668   :group 'message-sending
669   :type '(choice (function)
670                  (repeat string)))
671
672 (defvar message-cater-to-broken-inn t
673   "Non-nil means Gnus should not fold the `References' header.
674 Folding `References' makes ancient versions of INN create incorrect
675 NOV lines.")
676
677 (eval-when-compile
678   (defvar gnus-post-method)
679   (defvar gnus-select-method))
680 (defcustom message-post-method
681   (cond ((and (boundp 'gnus-post-method)
682               (listp gnus-post-method)
683               gnus-post-method)
684          gnus-post-method)
685         ((boundp 'gnus-select-method)
686          gnus-select-method)
687         (t '(nnspool "")))
688   "*Method used to post news.
689 Note that when posting from inside Gnus, for instance, this
690 variable isn't used."
691   :group 'message-news
692   :group 'message-sending
693   ;; This should be the `gnus-select-method' widget, but that might
694   ;; create a dependence to `gnus.el'.
695   :type 'sexp)
696
697 ;; FIXME: This should be a temporary workaround until someone implements a
698 ;; proper solution.  If a crash happens while replying, the auto-save file
699 ;; will *not* have a `References:' header if `message-generate-headers-first'
700 ;; is nil.  See: http://article.gmane.org/gmane.emacs.gnus.general/51138
701 (defcustom message-generate-headers-first '(references)
702   "*If non-nil, generate all required headers before composing.
703 The variables `message-required-news-headers' and
704 `message-required-mail-headers' specify which headers to generate.
705 This can also be a list of headers that should be generated before
706 composing.
707
708 Note that the variable `message-deletable-headers' specifies headers which
709 are to be deleted and then re-generated before sending, so this variable
710 will not have a visible effect for those headers."
711   :group 'message-headers
712   :type '(choice (const :tag "None" nil)
713                  (const :tag "References" '(references))
714                  (const :tag "All" t)
715                  (repeat (sexp :tag "Header"))))
716
717 (defcustom message-setup-hook nil
718   "Normal hook, run each time a new outgoing message is initialized.
719 The function `message-setup' runs this hook."
720   :group 'message-various
721   :type 'hook)
722
723 (defcustom message-cancel-hook nil
724   "Hook run when cancelling articles."
725   :group 'message-various
726   :type 'hook)
727
728 (defcustom message-signature-setup-hook nil
729   "Normal hook, run each time a new outgoing message is initialized.
730 It is run after the headers have been inserted and before
731 the signature is inserted."
732   :group 'message-various
733   :type 'hook)
734
735 (defcustom message-mode-hook nil
736   "Hook run in message mode buffers."
737   :group 'message-various
738   :type 'hook)
739
740 (defcustom message-header-hook nil
741   "Hook run in a message mode buffer narrowed to the headers."
742   :group 'message-various
743   :type 'hook)
744
745 (defcustom message-header-setup-hook nil
746   "Hook called narrowed to the headers when setting up a message buffer."
747   :group 'message-various
748   :type 'hook)
749
750 (defcustom message-minibuffer-local-map
751   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
752     (set-keymap-parent map minibuffer-local-map)
753     map)
754   "Keymap for `message-read-from-minibuffer'.")
755
756 ;;;###autoload
757 (defcustom message-citation-line-function 'message-insert-citation-line
758   "*Function called to insert the \"Whomever writes:\" line.
759
760 Note that Gnus provides a feature where the reader can click on
761 `writes:' to hide the cited text.  If you change this line too much,
762 people who read your message will have to change their Gnus
763 configuration.  See the variable `gnus-cite-attribution-suffix'."
764   :type 'function
765   :group 'message-insertion)
766
767 ;;;###autoload
768 (defcustom message-yank-prefix "> "
769   "*Prefix inserted on the lines of yanked messages.
770 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
771 See also `message-yank-cited-prefix'."
772   :type 'string
773   :group 'message-insertion)
774
775 (defcustom message-yank-cited-prefix ">"
776   "*Prefix inserted on cited or empty lines of yanked messages.
777 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
778 See also `message-yank-prefix'."
779   :type 'string
780   :group 'message-insertion)
781
782 (defcustom message-indentation-spaces 3
783   "*Number of spaces to insert at the beginning of each cited line.
784 Used by `message-yank-original' via `message-yank-cite'."
785   :group 'message-insertion
786   :type 'integer)
787
788 ;;;###autoload
789 (defcustom message-cite-function 'message-cite-original
790   "*Function for citing an original message.
791 Predefined functions include `message-cite-original' and
792 `message-cite-original-without-signature'.
793 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
794   :type '(radio (function-item message-cite-original)
795                 (function-item message-cite-original-without-signature)
796                 (function-item sc-cite-original)
797                 (function :tag "Other"))
798   :group 'message-insertion)
799
800 ;;;###autoload
801 (defcustom message-indent-citation-function 'message-indent-citation
802   "*Function for modifying a citation just inserted in the mail buffer.
803 This can also be a list of functions.  Each function can find the
804 citation between (point) and (mark t).  And each function should leave
805 point and mark around the citation text as modified."
806   :type 'function
807   :group 'message-insertion)
808
809 ;;;###autoload
810 (defcustom message-signature t
811   "*String to be inserted at the end of the message buffer.
812 If t, the `message-signature-file' file will be inserted instead.
813 If a function, the result from the function will be used instead.
814 If a form, the result from the form will be used instead."
815   :type 'sexp
816   :group 'message-insertion)
817
818 ;;;###autoload
819 (defcustom message-signature-file "~/.signature"
820   "*Name of file containing the text inserted at end of message buffer.
821 Ignored if the named file doesn't exist.
822 If nil, don't insert a signature."
823   :type '(choice file (const :tags "None" nil))
824   :group 'message-insertion)
825
826 ;;;###autoload
827 (defcustom message-signature-insert-empty-line t
828   "*If non-nil, insert an empty line before the signature separator."
829   :type 'boolean
830   :group 'message-insertion)
831
832 (defcustom message-distribution-function nil
833   "*Function called to return a Distribution header."
834   :group 'message-news
835   :group 'message-headers
836   :type '(choice function (const nil)))
837
838 (defcustom message-expires 14
839   "Number of days before your article expires."
840   :group 'message-news
841   :group 'message-headers
842   :link '(custom-manual "(message)News Headers")
843   :type 'integer)
844
845 (defcustom message-user-path nil
846   "If nil, use the NNTP server name in the Path header.
847 If stringp, use this; if non-nil, use no host name (user name only)."
848   :group 'message-news
849   :group 'message-headers
850   :link '(custom-manual "(message)News Headers")
851   :type '(choice (const :tag "nntp" nil)
852                  (string :tag "name")
853                  (sexp :tag "none" :format "%t" t)))
854
855 (defvar message-reply-buffer nil)
856 (defvar message-reply-headers nil
857   "The headers of the current replied article.
858 It is a vector of the following headers:
859 \[number subject from date id references chars lines xref extra].")
860 (defvar message-newsreader nil)
861 (defvar message-mailer nil)
862 (defvar message-sent-message-via nil)
863 (defvar message-checksum nil)
864 (defvar message-send-actions nil
865   "A list of actions to be performed upon successful sending of a message.")
866 (defvar message-exit-actions nil
867   "A list of actions to be performed upon exiting after sending a message.")
868 (defvar message-kill-actions nil
869   "A list of actions to be performed before killing a message buffer.")
870 (defvar message-postpone-actions nil
871   "A list of actions to be performed after postponing a message.")
872
873 (define-widget 'message-header-lines 'text
874   "All header lines must be LFD terminated."
875   :format "%{%t%}:%n%v"
876   :valid-regexp "^\\'"
877   :error "All header lines must be newline terminated")
878
879 (defcustom message-default-headers ""
880   "*A string containing header lines to be inserted in outgoing messages.
881 It is inserted before you edit the message, so you can edit or delete
882 these lines."
883   :group 'message-headers
884   :type 'message-header-lines)
885
886 (defcustom message-default-mail-headers ""
887   "*A string of header lines to be inserted in outgoing mails."
888   :group 'message-headers
889   :group 'message-mail
890   :type 'message-header-lines)
891
892 (defcustom message-default-news-headers ""
893   "*A string of header lines to be inserted in outgoing news articles."
894   :group 'message-headers
895   :group 'message-news
896   :type 'message-header-lines)
897
898 ;; Note: could use /usr/ucb/mail instead of sendmail;
899 ;; options -t, and -v if not interactive.
900 (defcustom message-mailer-swallows-blank-line
901   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
902                          system-configuration)
903            (file-readable-p "/etc/sendmail.cf")
904            (let ((buffer (get-buffer-create " *temp*")))
905              (unwind-protect
906                  (save-excursion
907                    (set-buffer buffer)
908                    (insert-file-contents "/etc/sendmail.cf")
909                    (goto-char (point-min))
910                    (let ((case-fold-search nil))
911                      (re-search-forward "^OR\\>" nil t)))
912                (kill-buffer buffer))))
913       ;; According to RFC822, "The field-name must be composed of printable
914       ;; ASCII characters (i. e., characters that have decimal values between
915       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
916       ;; space, or colon.
917       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
918   "*Set this non-nil if the system's mailer runs the header and body together.
919 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
920 The value should be an expression to test whether the problem will
921 actually occur."
922   :group 'message-sending
923   :type 'sexp)
924
925 ;;;###autoload
926 (define-mail-user-agent 'message-user-agent
927   'message-mail 'message-send-and-exit
928   'message-kill-buffer 'message-send-hook)
929
930 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
931   "If non-nil, delete the deletable headers before feeding to mh.")
932
933 (defvar message-send-method-alist
934   '((news message-news-p message-send-via-news)
935     (mail message-mail-p message-send-via-mail))
936   "Alist of ways to send outgoing messages.
937 Each element has the form
938
939   \(TYPE PREDICATE FUNCTION)
940
941 where TYPE is a symbol that names the method; PREDICATE is a function
942 called without any parameters to determine whether the message is
943 a message of type TYPE; and FUNCTION is a function to be called if
944 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
945 the prefix.")
946
947 (defcustom message-mail-alias-type 'abbrev
948   "*What alias expansion type to use in Message buffers.
949 The default is `abbrev', which uses mailabbrev.  nil switches
950 mail aliases off."
951   :group 'message
952   :link '(custom-manual "(message)Mail Aliases")
953   :type '(choice (const :tag "Use Mailabbrev" abbrev)
954                  (const :tag "No expansion" nil)))
955
956 (defcustom message-auto-save-directory
957   (file-name-as-directory (nnheader-concat message-directory "drafts"))
958   "*Directory where Message auto-saves buffers if Gnus isn't running.
959 If nil, Message won't auto-save."
960   :group 'message-buffers
961   :type '(choice directory (const :tag "Don't auto-save" nil)))
962
963 (defcustom message-default-charset
964   (and (not (mm-multibyte-p)) 'iso-8859-1)
965   "Default charset used in non-MULE Emacsen.
966 If nil, you might be asked to input the charset."
967   :version "21.1"
968   :group 'message
969   :type 'symbol)
970
971 (defcustom message-dont-reply-to-names
972   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
973   "*A regexp specifying addresses to prune when doing wide replies.
974 A value of nil means exclude your own user name only."
975   :version "21.1"
976   :group 'message
977   :type '(choice (const :tag "Yourself" nil)
978                  regexp))
979
980 (defvar message-shoot-gnksa-feet nil
981   "*A list of GNKSA feet you are allowed to shoot.
982 Gnus gives you all the opportunity you could possibly want for
983 shooting yourself in the foot.  Also, Gnus allows you to shoot the
984 feet of Good Net-Keeping Seal of Approval.  The following are foot
985 candidates:
986 `empty-article'     Allow you to post an empty article;
987 `quoted-text-only'  Allow you to post quoted text only;
988 `multiple-copies'   Allow you to post multiple copies;
989 `cancel-messages'   Allow you to cancel or supersede messages from
990                     your other email addresses.")
991
992 (defsubst message-gnksa-enable-p (feature)
993   (or (not (listp message-shoot-gnksa-feet))
994       (memq feature message-shoot-gnksa-feet)))
995
996 (defcustom message-hidden-headers nil
997   "Regexp of headers to be hidden when composing new messages.
998 This can also be a list of regexps to match headers.  Or a list
999 starting with `not' and followed by regexps.."
1000   :group 'message
1001   :type '(repeat regexp))
1002
1003 ;;; Internal variables.
1004 ;;; Well, not really internal.
1005
1006 (defvar message-mode-syntax-table
1007   (let ((table (copy-syntax-table text-mode-syntax-table)))
1008     (modify-syntax-entry ?% ". " table)
1009     (modify-syntax-entry ?> ". " table)
1010     (modify-syntax-entry ?< ". " table)
1011     table)
1012   "Syntax table used while in Message mode.")
1013
1014 (defface message-header-to-face
1015   '((((class color)
1016       (background dark))
1017      (:foreground "green2" :bold t))
1018     (((class color)
1019       (background light))
1020      (:foreground "MidnightBlue" :bold t))
1021     (t
1022      (:bold t :italic t)))
1023   "Face used for displaying From headers."
1024   :group 'message-faces)
1025
1026 (defface message-header-cc-face
1027   '((((class color)
1028       (background dark))
1029      (:foreground "green4" :bold t))
1030     (((class color)
1031       (background light))
1032      (:foreground "MidnightBlue"))
1033     (t
1034      (:bold t)))
1035   "Face used for displaying Cc headers."
1036   :group 'message-faces)
1037
1038 (defface message-header-subject-face
1039   '((((class color)
1040       (background dark))
1041      (:foreground "green3"))
1042     (((class color)
1043       (background light))
1044      (:foreground "navy blue" :bold t))
1045     (t
1046      (:bold t)))
1047   "Face used for displaying subject headers."
1048   :group 'message-faces)
1049
1050 (defface message-header-newsgroups-face
1051   '((((class color)
1052       (background dark))
1053      (:foreground "yellow" :bold t :italic t))
1054     (((class color)
1055       (background light))
1056      (:foreground "blue4" :bold t :italic t))
1057     (t
1058      (:bold t :italic t)))
1059   "Face used for displaying newsgroups headers."
1060   :group 'message-faces)
1061
1062 (defface message-header-other-face
1063   '((((class color)
1064       (background dark))
1065      (:foreground "#b00000"))
1066     (((class color)
1067       (background light))
1068      (:foreground "steel blue"))
1069     (t
1070      (:bold t :italic t)))
1071   "Face used for displaying newsgroups headers."
1072   :group 'message-faces)
1073
1074 (defface message-header-name-face
1075   '((((class color)
1076       (background dark))
1077      (:foreground "DarkGreen"))
1078     (((class color)
1079       (background light))
1080      (:foreground "cornflower blue"))
1081     (t
1082      (:bold t)))
1083   "Face used for displaying header names."
1084   :group 'message-faces)
1085
1086 (defface message-header-xheader-face
1087   '((((class color)
1088       (background dark))
1089      (:foreground "blue"))
1090     (((class color)
1091       (background light))
1092      (:foreground "blue"))
1093     (t
1094      (:bold t)))
1095   "Face used for displaying X-Header headers."
1096   :group 'message-faces)
1097
1098 (defface message-separator-face
1099   '((((class color)
1100       (background dark))
1101      (:foreground "blue3"))
1102     (((class color)
1103       (background light))
1104      (:foreground "brown"))
1105     (t
1106      (:bold t)))
1107   "Face used for displaying the separator."
1108   :group 'message-faces)
1109
1110 (defface message-cited-text-face
1111   '((((class color)
1112       (background dark))
1113      (:foreground "red"))
1114     (((class color)
1115       (background light))
1116      (:foreground "red"))
1117     (t
1118      (:bold t)))
1119   "Face used for displaying cited text names."
1120   :group 'message-faces)
1121
1122 (defface message-mml-face
1123   '((((class color)
1124       (background dark))
1125      (:foreground "ForestGreen"))
1126     (((class color)
1127       (background light))
1128      (:foreground "ForestGreen"))
1129     (t
1130      (:bold t)))
1131   "Face used for displaying MML."
1132   :group 'message-faces)
1133
1134 (defun message-font-lock-make-header-matcher (regexp)
1135   (let ((form
1136          `(lambda (limit)
1137             (let ((start (point)))
1138               (save-restriction
1139                 (widen)
1140                 (goto-char (point-min))
1141                 (if (re-search-forward
1142                      (concat "^" (regexp-quote mail-header-separator) "$")
1143                      nil t)
1144                     (setq limit (min limit (match-beginning 0))))
1145                 (goto-char start))
1146               (and (< start limit)
1147                    (re-search-forward ,regexp limit t))))))
1148     (if (featurep 'bytecomp)
1149         (byte-compile form)
1150       form)))
1151
1152 (defvar message-font-lock-keywords
1153   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1154     `((,(message-font-lock-make-header-matcher
1155          (concat "^\\([Tt]o:\\)" content))
1156        (1 'message-header-name-face)
1157        (2 'message-header-to-face nil t))
1158       (,(message-font-lock-make-header-matcher
1159          (concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content))
1160        (1 'message-header-name-face)
1161        (2 'message-header-cc-face nil t))
1162       (,(message-font-lock-make-header-matcher
1163          (concat "^\\([Ss]ubject:\\)" content))
1164        (1 'message-header-name-face)
1165        (2 'message-header-subject-face nil t))
1166       (,(message-font-lock-make-header-matcher
1167          (concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content))
1168        (1 'message-header-name-face)
1169        (2 'message-header-newsgroups-face nil t))
1170       (,(message-font-lock-make-header-matcher
1171          (concat "^\\([A-Z][^: \n\t]+:\\)" content))
1172        (1 'message-header-name-face)
1173        (2 'message-header-other-face nil t))
1174       (,(message-font-lock-make-header-matcher
1175          (concat "^\\(X-[A-Za-z0-9-]+:\\|In-Reply-To:\\)" content))
1176        (1 'message-header-name-face)
1177        (2 'message-header-name-face))
1178       ,@(if (and mail-header-separator
1179                  (not (equal mail-header-separator "")))
1180             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1181                1 'message-separator-face))
1182           nil)
1183       ((lambda (limit)
1184          (re-search-forward (concat "^\\("
1185                                     message-cite-prefix-regexp
1186                                     "\\).*")
1187                             limit t))
1188        (0 'message-cited-text-face))
1189       ("<#/?\\(multipart\\|part\\|external\\|mml\\|secure\\)[^>]*>"
1190        (0 'message-mml-face))))
1191   "Additional expressions to highlight in Message mode.")
1192
1193
1194 ;; XEmacs does it like this.  For Emacs, we have to set the
1195 ;; `font-lock-defaults' buffer-local variable.
1196 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
1197
1198 (defvar message-face-alist
1199   '((bold . bold-region)
1200     (underline . underline-region)
1201     (default . (lambda (b e)
1202                  (unbold-region b e)
1203                  (ununderline-region b e))))
1204   "Alist of mail and news faces for facemenu.
1205 The cdr of each entry is a function for applying the face to a region.")
1206
1207 (defcustom message-send-hook nil
1208   "Hook run before sending messages.
1209 This hook is run quite early when sending."
1210   :group 'message-various
1211   :options '(ispell-message)
1212   :type 'hook)
1213
1214 (defcustom message-send-mail-hook nil
1215   "Hook run before sending mail messages.
1216 This hook is run very late -- just before the message is sent as
1217 mail."
1218   :group 'message-various
1219   :type 'hook)
1220
1221 (defcustom message-send-news-hook nil
1222   "Hook run before sending news messages.
1223 This hook is run very late -- just before the message is sent as
1224 news."
1225   :group 'message-various
1226   :type 'hook)
1227
1228 (defcustom message-sent-hook nil
1229   "Hook run after sending messages."
1230   :group 'message-various
1231   :type 'hook)
1232
1233 (defvar message-send-coding-system 'binary
1234   "Coding system to encode outgoing mail.")
1235
1236 (defvar message-draft-coding-system
1237   mm-auto-save-coding-system
1238   "*Coding system to compose mail.
1239 If you'd like to make it possible to share draft files between XEmacs
1240 and Emacs, you may use `iso-2022-7bit' for this value at your own risk.
1241 Note that the coding-system `iso-2022-7bit' isn't suitable to all data.")
1242
1243 (defcustom message-send-mail-partially-limit 1000000
1244   "The limitation of messages sent as message/partial.
1245 The lower bound of message size in characters, beyond which the message
1246 should be sent in several parts.  If it is nil, the size is unlimited."
1247   :version "21.1"
1248   :group 'message-buffers
1249   :type '(choice (const :tag "unlimited" nil)
1250                  (integer 1000000)))
1251
1252 (defcustom message-alternative-emails nil
1253   "A regexp to match the alternative email addresses.
1254 The first matched address (not primary one) is used in the From field."
1255   :group 'message-headers
1256   :type '(choice (const :tag "Always use primary" nil)
1257                  regexp))
1258
1259 (defcustom message-hierarchical-addresses nil
1260   "A list of hierarchical mail address definitions.
1261
1262 Inside each entry, the first address is the \"top\" address, and
1263 subsequent addresses are subaddresses; this is used to indicate that
1264 mail sent to the first address will automatically be delivered to the
1265 subaddresses.  So if the first address appears in the recipient list
1266 for a message, the subaddresses will be removed (if present) before
1267 the mail is sent.  All addresses in this structure should be
1268 downcased."
1269   :group 'message-headers
1270   :type '(repeat (repeat string)))
1271
1272 (defcustom message-mail-user-agent nil
1273   "Like `mail-user-agent'.
1274 Except if it is nil, use Gnus native MUA; if it is t, use
1275 `mail-user-agent'."
1276   :type '(radio (const :tag "Gnus native"
1277                        :format "%t\n"
1278                        nil)
1279                 (const :tag "`mail-user-agent'"
1280                        :format "%t\n"
1281                        t)
1282                 (function-item :tag "Default Emacs mail"
1283                                :format "%t\n"
1284                                sendmail-user-agent)
1285                 (function-item :tag "Emacs interface to MH"
1286                                :format "%t\n"
1287                                mh-e-user-agent)
1288                 (function :tag "Other"))
1289   :version "21.1"
1290   :group 'message)
1291
1292 (defcustom message-wide-reply-confirm-recipients nil
1293   "Whether to confirm a wide reply to multiple email recipients.
1294 If this variable is nil, don't ask whether to reply to all recipients.
1295 If this variable is non-nil, pose the question \"Reply to all
1296 recipients?\" before a wide reply to multiple recipients.  If the user
1297 answers yes, reply to all recipients as usual.  If the user answers
1298 no, only reply back to the author."
1299   :version "21.3"
1300   :group 'message-headers
1301   :type 'boolean)
1302
1303 (defcustom message-user-fqdn nil
1304   "*Domain part of Messsage-Ids."
1305   :group 'message-headers
1306   :link '(custom-manual "(message)News Headers")
1307   :type 'string)
1308
1309 (defcustom message-use-idna (and (condition-case nil (require 'idna)
1310                                    (file-error))
1311                                  (mm-coding-system-p 'utf-8)
1312                                  (executable-find idna-program)
1313                                  'ask)
1314   "Whether to encode non-ASCII in domain names into ASCII according to IDNA."
1315   :group 'message-headers
1316   :type '(choice (const :tag "Ask" ask)
1317                  (const :tag "Never" nil)
1318                  (const :tag "Always" t)))
1319
1320 ;;; Internal variables.
1321
1322 (defvar message-sending-message "Sending...")
1323 (defvar message-buffer-list nil)
1324 (defvar message-this-is-news nil)
1325 (defvar message-this-is-mail nil)
1326 (defvar message-draft-article nil)
1327 (defvar message-mime-part nil)
1328 (defvar message-posting-charset nil)
1329
1330 ;; Byte-compiler warning
1331 (eval-when-compile
1332   (defvar gnus-active-hashtb)
1333   (defvar gnus-read-active-file))
1334
1335 ;;; Regexp matching the delimiter of messages in UNIX mail format
1336 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1337 ;;; of rmail.el's rmail-unix-mail-delimiter.
1338 (defvar message-unix-mail-delimiter
1339   (let ((time-zone-regexp
1340          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1341                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1342                  "\\|"
1343                  "\\) *")))
1344     (concat
1345      "From "
1346
1347      ;; Many things can happen to an RFC 822 mailbox before it is put into
1348      ;; a `From' line.  The leading phrase can be stripped, e.g.
1349      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1350      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1351      ;; can be removed, e.g.
1352      ;;         From: joe@y.z (Joe      K
1353      ;;                 User)
1354      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1355      ;;         From: Joe User
1356      ;;                 <joe@y.z>
1357      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1358      ;; The mailbox can be removed or be replaced by white space, e.g.
1359      ;;         From: "Joe User"{space}{tab}
1360      ;;                 <joe@y.z>
1361      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1362      ;; where {space} and {tab} represent the Ascii space and tab characters.
1363      ;; We want to match the results of any of these manglings.
1364      ;; The following regexp rejects names whose first characters are
1365      ;; obviously bogus, but after that anything goes.
1366      "\\([^\0-\b\n-\r\^?].*\\)?"
1367
1368      ;; The time the message was sent.
1369      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1370      "\\([^\0-\r \^?]+\\) +"            ; month
1371      "\\([0-3]?[0-9]\\) +"              ; day of month
1372      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1373
1374      ;; Perhaps a time zone, specified by an abbreviation, or by a
1375      ;; numeric offset.
1376      time-zone-regexp
1377
1378      ;; The year.
1379      " \\([0-9][0-9]+\\) *"
1380
1381      ;; On some systems the time zone can appear after the year, too.
1382      time-zone-regexp
1383
1384      ;; Old uucp cruft.
1385      "\\(remote from .*\\)?"
1386
1387      "\n"))
1388   "Regexp matching the delimiter of messages in UNIX mail format.")
1389
1390 (defvar message-unsent-separator
1391   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1392           "^ *---+ +Returned message +---+ *$\\|"
1393           "^Start of returned message$\\|"
1394           "^ *---+ +Original message +---+ *$\\|"
1395           "^ *--+ +begin message +--+ *$\\|"
1396           "^ *---+ +Original message follows +---+ *$\\|"
1397           "^ *---+ +Undelivered message follows +---+ *$\\|"
1398           "^|? *---+ +Message text follows: +---+ *|?$")
1399   "A regexp that matches the separator before the text of a failed message.")
1400
1401 (defvar message-header-format-alist
1402   `((Newsgroups)
1403     (To . message-fill-address)
1404     (Cc . message-fill-address)
1405     (Subject)
1406     (In-Reply-To)
1407     (Fcc)
1408     (Bcc)
1409     (Date)
1410     (Organization)
1411     (Distribution)
1412     (Lines)
1413     (Expires)
1414     (Message-ID)
1415     (References . message-shorten-references)
1416     (User-Agent))
1417   "Alist used for formatting headers.")
1418
1419 (defvar message-options nil
1420   "Some saved answers when sending message.")
1421
1422 (defvar message-send-mail-real-function nil
1423   "Internal send mail function.")
1424
1425 (defvar message-bogus-system-names "^localhost\\."
1426   "The regexp of bogus system names.")
1427
1428 (defcustom message-valid-fqdn-regexp
1429   (concat "[a-z0-9][-.a-z0-9]+\\." ;; [hostname.subdomain.]domain.
1430           ;; valid TLDs:
1431           "\\([a-z][a-z]" ;; two letter country TDLs
1432           "\\|biz\\|com\\|edu\\|gov\\|int\\|mil\\|net\\|org"
1433           "\\|aero\\|coop\\|info\\|name\\|museum"
1434           "\\|arpa\\|pro\\|uucp\\|bitnet\\|bofh" ;; old style?
1435           "\\)")
1436   "Regular expression that matches a valid FQDN."
1437   ;; see also: gnus-button-valid-fqdn-regexp
1438   :group 'message-headers
1439   :type 'regexp)
1440
1441 (eval-and-compile
1442   (autoload 'message-setup-toolbar "messagexmas")
1443   (autoload 'mh-new-draft-name "mh-comp")
1444   (autoload 'mh-send-letter "mh-comp")
1445   (autoload 'gnus-point-at-eol "gnus-util")
1446   (autoload 'gnus-point-at-bol "gnus-util")
1447   (autoload 'gnus-output-to-rmail "gnus-util")
1448   (autoload 'gnus-output-to-mail "gnus-util")
1449   (autoload 'nndraft-request-associate-buffer "nndraft")
1450   (autoload 'nndraft-request-expire-articles "nndraft")
1451   (autoload 'gnus-open-server "gnus-int")
1452   (autoload 'gnus-request-post "gnus-int")
1453   (autoload 'gnus-alive-p "gnus-util")
1454   (autoload 'gnus-server-string "gnus")
1455   (autoload 'gnus-group-name-charset "gnus-group")
1456   (autoload 'gnus-group-name-decode "gnus-group")
1457   (autoload 'gnus-groups-from-server "gnus")
1458   (autoload 'rmail-output "rmailout")
1459   (autoload 'gnus-delay-article "gnus-delay")
1460   (autoload 'gnus-make-local-hook "gnus-util"))
1461
1462 \f
1463
1464 ;;;
1465 ;;; Utility functions.
1466 ;;;
1467
1468 (defmacro message-y-or-n-p (question show &rest text)
1469   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1470   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1471
1472 (defmacro message-delete-line (&optional n)
1473   "Delete the current line (and the next N lines)."
1474   `(delete-region (progn (beginning-of-line) (point))
1475                   (progn (forward-line ,(or n 1)) (point))))
1476
1477 (defun message-mark-active-p ()
1478   "Non-nil means the mark and region are currently active in this buffer."
1479   mark-active)
1480
1481 (defun message-unquote-tokens (elems)
1482   "Remove double quotes (\") from strings in list ELEMS."
1483   (mapcar (lambda (item)
1484             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1485               (setq item (concat (match-string 1 item)
1486                                  (match-string 2 item))))
1487             item)
1488           elems))
1489
1490 (defun message-tokenize-header (header &optional separator)
1491   "Split HEADER into a list of header elements.
1492 SEPARATOR is a string of characters to be used as separators.  \",\"
1493 is used by default."
1494   (if (not header)
1495       nil
1496     (let ((regexp (format "[%s]+" (or separator ",")))
1497           (beg 1)
1498           (first t)
1499           quoted elems paren)
1500       (with-temp-buffer
1501         (mm-enable-multibyte)
1502         (insert header)
1503         (goto-char (point-min))
1504         (while (not (eobp))
1505           (if first
1506               (setq first nil)
1507             (forward-char 1))
1508           (cond ((and (> (point) beg)
1509                       (or (eobp)
1510                           (and (looking-at regexp)
1511                                (not quoted)
1512                                (not paren))))
1513                  (push (buffer-substring beg (point)) elems)
1514                  (setq beg (match-end 0)))
1515                 ((eq (char-after) ?\")
1516                  (setq quoted (not quoted)))
1517                 ((and (eq (char-after) ?\()
1518                       (not quoted))
1519                  (setq paren t))
1520                 ((and (eq (char-after) ?\))
1521                       (not quoted))
1522                  (setq paren nil))))
1523         (nreverse elems)))))
1524
1525 (defun message-mail-file-mbox-p (file)
1526   "Say whether FILE looks like a Unix mbox file."
1527   (when (and (file-exists-p file)
1528              (file-readable-p file)
1529              (file-regular-p file))
1530     (with-temp-buffer
1531       (nnheader-insert-file-contents file)
1532       (goto-char (point-min))
1533       (looking-at message-unix-mail-delimiter))))
1534
1535 (defun message-fetch-field (header &optional not-all)
1536   "The same as `mail-fetch-field', only remove all newlines."
1537   (let* ((inhibit-point-motion-hooks t)
1538          (case-fold-search t)
1539          (value (mail-fetch-field header nil (not not-all))))
1540     (when value
1541       (while (string-match "\n[\t ]+" value)
1542         (setq value (replace-match " " t t value)))
1543       (set-text-properties 0 (length value) nil value)
1544       value)))
1545
1546 (defun message-narrow-to-field ()
1547   "Narrow the buffer to the header on the current line."
1548   (beginning-of-line)
1549   (narrow-to-region
1550    (point)
1551    (progn
1552      (forward-line 1)
1553      (if (re-search-forward "^[^ \n\t]" nil t)
1554          (progn
1555            (beginning-of-line)
1556            (point))
1557        (point-max))))
1558   (goto-char (point-min)))
1559
1560 (defun message-add-header (&rest headers)
1561   "Add the HEADERS to the message header, skipping those already present."
1562   (while headers
1563     (let (hclean)
1564       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1565         (error "Invalid header `%s'" (car headers)))
1566       (setq hclean (match-string 1 (car headers)))
1567       (save-restriction
1568         (message-narrow-to-headers)
1569         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1570           (goto-char (point-max))
1571           (if (string-match "\n$" (car headers))
1572               (insert (car headers))
1573             (insert (car headers) ?\n)))))
1574     (setq headers (cdr headers))))
1575
1576 (defmacro message-with-reply-buffer (&rest forms)
1577   "Evaluate FORMS in the reply buffer, if it exists."
1578   `(when (and message-reply-buffer
1579               (buffer-name message-reply-buffer))
1580      (save-excursion
1581        (set-buffer message-reply-buffer)
1582        ,@forms)))
1583
1584 (put 'message-with-reply-buffer 'lisp-indent-function 0)
1585 (put 'message-with-reply-buffer 'edebug-form-spec '(body))
1586
1587 (defun message-fetch-reply-field (header)
1588   "Fetch field HEADER from the message we're replying to."
1589   (message-with-reply-buffer
1590     (save-restriction
1591       (mail-narrow-to-head)
1592       (message-fetch-field header))))
1593
1594 (defun message-functionp (form)
1595   "Return non-nil if FORM is funcallable."
1596   (or (and (symbolp form) (fboundp form))
1597       (and (listp form) (eq (car form) 'lambda))
1598       (byte-code-function-p form)))
1599
1600 (defun message-strip-list-identifiers (subject)
1601   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1602   (require 'gnus-sum)                   ; for gnus-list-identifiers
1603   (let ((regexp (if (stringp gnus-list-identifiers)
1604                     gnus-list-identifiers
1605                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1606     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1607                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
1608         (concat (substring subject 0 (match-beginning 1))
1609                 (or (match-string 3 subject)
1610                     (match-string 5 subject))
1611                 (substring subject
1612                            (match-end 1)))
1613       subject)))
1614
1615 (defun message-strip-subject-re (subject)
1616   "Remove \"Re:\" from subject lines in string SUBJECT."
1617   (if (string-match message-subject-re-regexp subject)
1618       (substring subject (match-end 0))
1619     subject))
1620
1621 ;;; Start of functions adopted from `message-utils.el'.
1622
1623 (defun message-strip-subject-trailing-was (subject)
1624   "Remove trailing \"(Was: <old subject>)\" from SUBJECT lines.
1625 Leading \"Re: \" is not stripped by this function.  Use the function
1626 `message-strip-subject-re' for this."
1627   (let* ((query message-subject-trailing-was-query)
1628          (new) (found))
1629     (setq found
1630           (string-match
1631            (if (eq query 'ask)
1632                message-subject-trailing-was-ask-regexp
1633              message-subject-trailing-was-regexp)
1634            subject))
1635     (if found
1636         (setq new (substring subject 0 (match-beginning 0))))
1637     (if (or (not found) (eq query nil))
1638         subject
1639       (if (eq query 'ask)
1640           (if (message-y-or-n-p
1641                "Strip `(was: <old subject>)' in subject? " t
1642                (concat
1643                 "Strip `(was: <old subject>)' in subject "
1644                 "and use the new one instead?\n\n"
1645                 "Current subject is:   \""
1646                 subject "\"\n\n"
1647                 "New subject would be: \""
1648                 new "\"\n\n"
1649                 "See the variable `message-subject-trailing-was-query' "
1650                 "to get rid of this query."
1651                 ))
1652               new subject)
1653         new))))
1654
1655 ;;; Suggested by Jonas Steverud  @  www.dtek.chalmers.se/~d4jonas/
1656
1657 ;;;###autoload
1658 (defun message-change-subject (new-subject)
1659   "Ask for NEW-SUBJECT header, append (was: <Old Subject>)."
1660   (interactive
1661    (list
1662     (read-from-minibuffer "New subject: ")))
1663   (cond ((and (not (or (null new-subject) ; new subject not empty
1664                        (zerop (string-width new-subject))
1665                        (string-match "^[ \t]*$" new-subject))))
1666          (save-excursion
1667            (let ((old-subject (message-fetch-field "Subject")))
1668              (cond ((not old-subject)
1669                     (error "No current subject"))
1670                    ((not (string-match
1671                           (concat "^[ \t]*"
1672                                   (regexp-quote new-subject)
1673                                   " \t]*$")
1674                           old-subject))  ; yes, it really is a new subject
1675                     ;; delete eventual Re: prefix
1676                     (setq old-subject
1677                           (message-strip-subject-re old-subject))
1678                     (message-goto-subject)
1679                     (message-delete-line)
1680                     (insert (concat "Subject: "
1681                                     new-subject
1682                                     " (was: "
1683                                     old-subject ")\n")))))))))
1684
1685 ;;;###autoload
1686 (defun message-mark-inserted-region (beg end)
1687   "Mark some region in the current article with enclosing tags.
1688 See `message-mark-insert-begin' and `message-mark-insert-end'."
1689   (interactive "r")
1690   (save-excursion
1691     ; add to the end of the region first, otherwise end would be invalid
1692     (goto-char end)
1693     (insert message-mark-insert-end)
1694     (goto-char beg)
1695     (insert message-mark-insert-begin)))
1696
1697 ;;;###autoload
1698 (defun message-mark-insert-file (file)
1699   "Insert FILE at point, marking it with enclosing tags.
1700 See `message-mark-insert-begin' and `message-mark-insert-end'."
1701   (interactive "fFile to insert: ")
1702     ;; reverse insertion to get correct result.
1703   (let ((p (point)))
1704     (insert message-mark-insert-end)
1705     (goto-char p)
1706     (insert-file-contents file)
1707     (goto-char p)
1708     (insert message-mark-insert-begin)))
1709
1710 ;;;###autoload
1711 (defun message-add-archive-header ()
1712   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
1713 The note can be customized using `message-archive-note'.  When called with a
1714 prefix argument, ask for a text to insert.  If you don't want the note in the
1715 body, set  `message-archive-note' to nil."
1716   (interactive)
1717   (if current-prefix-arg
1718       (setq message-archive-note
1719             (read-from-minibuffer "Reason for No-Archive: "
1720                                   (cons message-archive-note 0))))
1721     (save-excursion
1722       (if (message-goto-signature)
1723           (re-search-backward message-signature-separator))
1724       (when message-archive-note
1725         (insert message-archive-note)
1726         (newline))
1727       (message-add-header message-archive-header)
1728       (message-sort-headers)))
1729
1730 ;;;###autoload
1731 (defun message-cross-post-followup-to-header (target-group)
1732   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
1733 With prefix-argument just set Follow-Up, don't cross-post."
1734   (interactive
1735    (list ; Completion based on Gnus
1736     (completing-read "Followup To: "
1737                      (if (boundp 'gnus-newsrc-alist)
1738                          gnus-newsrc-alist)
1739                      nil nil '("poster" . 0)
1740                      (if (boundp 'gnus-group-history)
1741                          'gnus-group-history))))
1742   (message-remove-header "Follow[Uu]p-[Tt]o" t)
1743   (message-goto-newsgroups)
1744   (beginning-of-line)
1745   ;; if we already did a crosspost before, kill old target
1746   (if (and message-cross-post-old-target
1747            (re-search-forward
1748             (regexp-quote (concat "," message-cross-post-old-target))
1749             nil t))
1750       (replace-match ""))
1751   ;; unless (followup is to poster or user explicitly asked not
1752   ;; to cross-post, or target-group is already in Newsgroups)
1753   ;; add target-group to Newsgroups line.
1754   (cond ((and (or
1755                ;; def: cross-post, req:no
1756                (and message-cross-post-default (not current-prefix-arg))
1757                ;; def: no-cross-post, req:yes
1758                (and (not message-cross-post-default) current-prefix-arg))
1759               (not (string-match "poster" target-group))
1760               (not (string-match (regexp-quote target-group)
1761                                  (message-fetch-field "Newsgroups"))))
1762          (end-of-line)
1763          (insert (concat "," target-group))))
1764   (end-of-line) ; ensure Followup: comes after Newsgroups:
1765   ;; unless new followup would be identical to Newsgroups line
1766   ;; make a new Followup-To line
1767   (if (not (string-match (concat "^[ \t]*"
1768                                  target-group
1769                                  "[ \t]*$")
1770                          (message-fetch-field "Newsgroups")))
1771       (insert (concat "\nFollowup-To: " target-group)))
1772   (setq message-cross-post-old-target target-group))
1773
1774 ;;;###autoload
1775 (defun message-cross-post-insert-note (target-group cross-post in-old
1776                                                     old-groups)
1777   "Insert a in message body note about a set Followup or Crosspost.
1778 If there have been previous notes, delete them.  TARGET-GROUP specifies the
1779 group to Followup-To.  When CROSS-POST is t, insert note about
1780 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
1781 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
1782 been made to before the user asked for a Crosspost."
1783   ;; start scanning body for previous uses
1784   (message-goto-signature)
1785   (let ((head (re-search-backward
1786                (concat "^" mail-header-separator)
1787                nil t))) ; just search in body
1788     (message-goto-signature)
1789     (while (re-search-backward
1790             (concat "^" (regexp-quote message-cross-post-note) ".*")
1791             head t)
1792       (message-delete-line))
1793     (message-goto-signature)
1794     (while (re-search-backward
1795             (concat "^" (regexp-quote message-followup-to-note) ".*")
1796             head t)
1797       (message-delete-line))
1798     ;; insert new note
1799     (if (message-goto-signature)
1800         (re-search-backward message-signature-separator))
1801     (if (or in-old
1802             (not cross-post)
1803             (string-match "^[ \t]*poster[ \t]*$" target-group))
1804         (insert (concat message-followup-to-note target-group "\n"))
1805       (insert (concat message-cross-post-note target-group "\n")))))
1806
1807 ;;;###autoload
1808 (defun message-cross-post-followup-to (target-group)
1809   "Crossposts message and set Followup-To to TARGET-GROUP.
1810 With prefix-argument just set Follow-Up, don't cross-post."
1811   (interactive
1812    (list ; Completion based on Gnus
1813     (completing-read "Followup To: "
1814                      (if (boundp 'gnus-newsrc-alist)
1815                          gnus-newsrc-alist)
1816                      nil nil '("poster" . 0)
1817                      (if (boundp 'gnus-group-history)
1818                          'gnus-group-history))))
1819   (cond ((not (or (null target-group) ; new subject not empty
1820                   (zerop (string-width target-group))
1821                   (string-match "^[ \t]*$" target-group)))
1822          (save-excursion
1823            (let* ((old-groups (message-fetch-field "Newsgroups"))
1824                   (in-old (string-match
1825                            (regexp-quote target-group)
1826                            (or old-groups ""))))
1827              ;; check whether target exactly matches old Newsgroups
1828              (cond ((not old-groups)
1829                     (error "No current newsgroup"))
1830                    ((or (not in-old)
1831                         (not (string-match
1832                               (concat "^[ \t]*"
1833                                       (regexp-quote target-group)
1834                                       "[ \t]*$")
1835                               old-groups)))
1836                     ;; yes, Newsgroups line must change
1837                     (message-cross-post-followup-to-header target-group)
1838                     ;; insert note whether we do cross-post or followup-to
1839                     (funcall message-cross-post-note-function
1840                              target-group
1841                              (if (or (and message-cross-post-default
1842                                           (not current-prefix-arg))
1843                                      (and (not message-cross-post-default)
1844                                           current-prefix-arg)) t)
1845                              in-old old-groups))))))))
1846
1847 ;;; Reduce To: to Cc: or Bcc: header
1848
1849 ;;;###autoload
1850 (defun message-reduce-to-to-cc ()
1851  "Replace contents of To: header with contents of Cc: or Bcc: header."
1852  (interactive)
1853  (let ((cc-content (message-fetch-field "cc"))
1854        (bcc nil))
1855    (if (and (not cc-content)
1856             (setq cc-content (message-fetch-field "bcc")))
1857        (setq bcc t))
1858    (cond (cc-content
1859           (save-excursion
1860             (message-goto-to)
1861             (message-delete-line)
1862             (insert (concat "To: " cc-content "\n"))
1863             (message-remove-header (if bcc
1864                                        "bcc"
1865                                      "cc")))))))
1866
1867 ;;; End of functions adopted from `message-utils.el'.
1868
1869 (defun message-remove-header (header &optional is-regexp first reverse)
1870   "Remove HEADER in the narrowed buffer.
1871 If IS-REGEXP, HEADER is a regular expression.
1872 If FIRST, only remove the first instance of the header.
1873 Return the number of headers removed."
1874   (goto-char (point-min))
1875   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1876         (number 0)
1877         (case-fold-search t)
1878         last)
1879     (while (and (not (eobp))
1880                 (not last))
1881       (if (if reverse
1882               (not (looking-at regexp))
1883             (looking-at regexp))
1884           (progn
1885             (incf number)
1886             (when first
1887               (setq last t))
1888             (delete-region
1889              (point)
1890              ;; There might be a continuation header, so we have to search
1891              ;; until we find a new non-continuation line.
1892              (progn
1893                (forward-line 1)
1894                (if (re-search-forward "^[^ \t]" nil t)
1895                    (goto-char (match-beginning 0))
1896                  (point-max)))))
1897         (forward-line 1)
1898         (if (re-search-forward "^[^ \t]" nil t)
1899             (goto-char (match-beginning 0))
1900           (goto-char (point-max)))))
1901     number))
1902
1903 (defun message-remove-first-header (header)
1904   "Remove the first instance of HEADER if there is more than one."
1905   (let ((count 0)
1906         (regexp (concat "^" (regexp-quote header) ":")))
1907     (save-excursion
1908       (goto-char (point-min))
1909       (while (re-search-forward regexp nil t)
1910         (incf count)))
1911     (while (> count 1)
1912       (message-remove-header header nil t)
1913       (decf count))))
1914
1915 (defun message-narrow-to-headers ()
1916   "Narrow the buffer to the head of the message."
1917   (widen)
1918   (narrow-to-region
1919    (goto-char (point-min))
1920    (if (re-search-forward
1921         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1922        (match-beginning 0)
1923      (point-max)))
1924   (goto-char (point-min)))
1925
1926 (defun message-narrow-to-head-1 ()
1927   "Like `message-narrow-to-head'.  Don't widen."
1928   (narrow-to-region
1929    (goto-char (point-min))
1930    (if (search-forward "\n\n" nil 1)
1931        (1- (point))
1932      (point-max)))
1933   (goto-char (point-min)))
1934
1935 (defun message-narrow-to-head ()
1936   "Narrow the buffer to the head of the message.
1937 Point is left at the beginning of the narrowed-to region."
1938   (widen)
1939   (message-narrow-to-head-1))
1940
1941 (defun message-narrow-to-headers-or-head ()
1942   "Narrow the buffer to the head of the message."
1943   (widen)
1944   (narrow-to-region
1945    (goto-char (point-min))
1946    (cond
1947     ((re-search-forward
1948       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1949      (match-beginning 0))
1950     ((search-forward "\n\n" nil t)
1951      (1- (point)))
1952     (t
1953      (point-max))))
1954   (goto-char (point-min)))
1955
1956 (defun message-news-p ()
1957   "Say whether the current buffer contains a news message."
1958   (and (not message-this-is-mail)
1959        (or message-this-is-news
1960            (save-excursion
1961              (save-restriction
1962                (message-narrow-to-headers)
1963                (and (message-fetch-field "newsgroups")
1964                     (not (message-fetch-field "posted-to"))))))))
1965
1966 (defun message-mail-p ()
1967   "Say whether the current buffer contains a mail message."
1968   (and (not message-this-is-news)
1969        (or message-this-is-mail
1970            (save-excursion
1971              (save-restriction
1972                (message-narrow-to-headers)
1973                (or (message-fetch-field "to")
1974                    (message-fetch-field "cc")
1975                    (message-fetch-field "bcc")))))))
1976
1977 (defun message-subscribed-p ()
1978   "Say whether we need to insert a MFT header."
1979   (or message-subscribed-regexps
1980       message-subscribed-addresses
1981       message-subscribed-address-file
1982       message-subscribed-address-functions))
1983
1984 (defun message-next-header ()
1985   "Go to the beginning of the next header."
1986   (beginning-of-line)
1987   (or (eobp) (forward-char 1))
1988   (not (if (re-search-forward "^[^ \t]" nil t)
1989            (beginning-of-line)
1990          (goto-char (point-max)))))
1991
1992 (defun message-sort-headers-1 ()
1993   "Sort the buffer as headers using `message-rank' text props."
1994   (goto-char (point-min))
1995   (require 'sort)
1996   (sort-subr
1997    nil 'message-next-header
1998    (lambda ()
1999      (message-next-header)
2000      (unless (bobp)
2001        (forward-char -1)))
2002    (lambda ()
2003      (or (get-text-property (point) 'message-rank)
2004          10000))))
2005
2006 (defun message-sort-headers ()
2007   "Sort the headers of the current message according to `message-header-format-alist'."
2008   (interactive)
2009   (save-excursion
2010     (save-restriction
2011       (let ((max (1+ (length message-header-format-alist)))
2012             rank)
2013         (message-narrow-to-headers)
2014         (while (re-search-forward "^[^ \n]+:" nil t)
2015           (put-text-property
2016            (match-beginning 0) (1+ (match-beginning 0))
2017            'message-rank
2018            (if (setq rank (length (memq (assq (intern (buffer-substring
2019                                                        (match-beginning 0)
2020                                                        (1- (match-end 0))))
2021                                               message-header-format-alist)
2022                                         message-header-format-alist)))
2023                (- max rank)
2024              (1+ max)))))
2025       (message-sort-headers-1))))
2026
2027
2028 \f
2029
2030 ;;;
2031 ;;; Message mode
2032 ;;;
2033
2034 ;;; Set up keymap.
2035
2036 (defvar message-mode-map nil)
2037
2038 (unless message-mode-map
2039   (setq message-mode-map (make-keymap))
2040   (set-keymap-parent message-mode-map text-mode-map)
2041   (define-key message-mode-map "\C-c?" 'describe-mode)
2042
2043   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
2044   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
2045   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
2046   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
2047   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
2048   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
2049   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
2050   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
2051   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
2052   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
2053   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2054   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
2055   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
2056   (define-key message-mode-map "\C-c\C-f\C-i"
2057     'message-insert-or-toggle-importance)
2058   (define-key message-mode-map "\C-c\C-f\C-a"
2059     'message-generate-unsubscribed-mail-followup-to)
2060
2061   ;; modify headers (and insert notes in body)
2062   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
2063   ;;
2064   (define-key message-mode-map "\C-c\C-fx"    'message-cross-post-followup-to)
2065   ;; prefix+message-cross-post-followup-to = same w/o cross-post
2066   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
2067   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
2068   ;; mark inserted text
2069   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
2070   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
2071
2072   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
2073   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
2074
2075   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
2076   (define-key message-mode-map "\C-c\C-fw" 'message-insert-wide-reply)
2077   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
2078   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
2079
2080   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
2081   (define-key message-mode-map "\C-c\M-n"
2082     'message-insert-disposition-notification-to)
2083
2084   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
2085   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
2086   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
2087   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2088   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2089   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2090   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2091   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2092
2093   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2094   (define-key message-mode-map "\C-c\C-s" 'message-send)
2095   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2096   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2097   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2098
2099   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2100   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2101   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2102   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2103   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
2104   (define-key message-mode-map [remap split-line]  'message-split-line)
2105
2106   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
2107
2108   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2109   (define-key message-mode-map "\t" 'message-tab)
2110   (define-key message-mode-map "\M-;" 'comment-region))
2111
2112 (easy-menu-define
2113   message-mode-menu message-mode-map "Message Menu."
2114   `("Message"
2115     ["Yank Original" message-yank-original message-reply-buffer]
2116     ["Fill Yanked Message" message-fill-yanked-message t]
2117     ["Insert Signature" message-insert-signature t]
2118     ["Caesar (rot13) Message" message-caesar-buffer-body t]
2119     ["Caesar (rot13) Region" message-caesar-region (message-mark-active-p)]
2120     ["Elide Region" message-elide-region 
2121      :active (message-mark-active-p)
2122      ,@(if (featurep 'xemacs) nil
2123          '(:help "Replace text in region with an ellipsis"))]
2124     ["Delete Outside Region" message-delete-not-region 
2125      :active (message-mark-active-p)
2126      ,@(if (featurep 'xemacs) nil
2127          '(:help "Delete all quoted text outside region"))]
2128     ["Kill To Signature" message-kill-to-signature t]
2129     ["Newline and Reformat" message-newline-and-reformat t]
2130     ["Rename buffer" message-rename-buffer t]
2131     ["Spellcheck" ispell-message
2132      ,@(if (featurep 'xemacs) '(t)
2133          '(:help "Spellcheck this message"))]
2134     "----"
2135     ["Insert Region Marked" message-mark-inserted-region
2136      :active (message-mark-active-p)
2137      ,@(if (featurep 'xemacs) nil
2138          '(:help "Mark region with enclosing tags"))]
2139     ["Insert File Marked..." message-mark-insert-file
2140      ,@(if (featurep 'xemacs) '(t)
2141          '(:help "Insert file at point marked with enclosing tags"))]
2142     "----"
2143     ["Send Message" message-send-and-exit
2144      ,@(if (featurep 'xemacs) '(t)
2145          '(:help "Send this message"))]
2146     ["Postpone Message" message-dont-send
2147      ,@(if (featurep 'xemacs) '(t)
2148          '(:help "File this draft message and exit"))]
2149     ["Send at Specific Time..." gnus-delay-article
2150      ,@(if (featurep 'xemacs) '(t)
2151          '(:help "Ask, then arrange to send message at that time"))]
2152     ["Kill Message" message-kill-buffer
2153      ,@(if (featurep 'xemacs) '(t)
2154          '(:help "Delete this message without sending"))]))
2155
2156 (easy-menu-define
2157   message-mode-field-menu message-mode-map ""
2158   `("Field"
2159     ["Fetch To" message-insert-to t]
2160     ["Fetch Newsgroups" message-insert-newsgroups t]
2161     "----"
2162     ["To" message-goto-to t]
2163     ["From" message-goto-from t]
2164     ["Subject" message-goto-subject t]
2165     ["Change subject..." message-change-subject t]
2166     ["Cc" message-goto-cc t]
2167     ["Bcc" message-goto-bcc t]
2168     ["Fcc" message-goto-fcc t]
2169     ["Reply-To" message-goto-reply-to t]
2170     ["Flag As Important" message-insert-importance-high
2171      ,@(if (featurep 'xemacs) '(t)
2172          '(:help "Mark this message as important"))]
2173     ["Flag As Unimportant" message-insert-importance-low
2174      ,@(if (featurep 'xemacs) '(t)
2175          '(:help "Mark this message as unimportant"))]
2176     ["Request Receipt"
2177      message-insert-disposition-notification-to
2178      ,@(if (featurep 'xemacs) '(t)
2179          '(:help "Request a receipt notification"))]
2180     "----"
2181     ;; (typical) news stuff
2182     ["Summary" message-goto-summary t]
2183     ["Keywords" message-goto-keywords t]
2184     ["Newsgroups" message-goto-newsgroups t]
2185     ["Followup-To" message-goto-followup-to t]
2186     ;; ["Followup-To (with note in body)" message-cross-post-followup-to t]
2187     ["Crosspost / Followup-To..." message-cross-post-followup-to t]
2188     ["Distribution" message-goto-distribution t]
2189     ["X-No-Archive:" message-add-archive-header t ]
2190     "----"
2191     ;; (typical) mailing-lists stuff
2192     ["Send to list only" message-to-list-only t]
2193     ["Mail-Followup-To" message-goto-mail-followup-to t]
2194     ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2195     "----"
2196     ["Sort Headers" message-sort-headers t]
2197     ["Encode non-ASCII domain names" message-idna-to-ascii-rhs t]
2198     ["Goto Body" message-goto-body t]
2199     ["Goto Signature" message-goto-signature t]))
2200
2201 (defvar message-tool-bar-map nil)
2202
2203 (eval-when-compile
2204   (defvar facemenu-add-face-function)
2205   (defvar facemenu-remove-face-function))
2206
2207 ;;; Forbidden properties
2208 ;;
2209 ;; We use `after-change-functions' to keep special text properties
2210 ;; that interfer with the normal function of message mode out of the
2211 ;; buffer.
2212
2213 (defcustom message-strip-special-text-properties t
2214   "Strip special properties from the message buffer.
2215
2216 Emacs has a number of special text properties which can break message
2217 composing in various ways.  If this option is set, message will strip
2218 these properties from the message composition buffer.  However, some
2219 packages requires these properties to be present in order to work.
2220 If you use one of these packages, turn this option off, and hope the
2221 message composition doesn't break too bad."
2222   :group 'message-various
2223   :type 'boolean)
2224
2225 (defconst message-forbidden-properties
2226   ;; No reason this should be clutter up customize.  We make it a
2227   ;; property list (rather than a list of property symbols), to be
2228   ;; directly useful for `remove-text-properties'.
2229   '(field nil read-only nil invisible nil intangible nil
2230           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2231           insert-behind-hooks nil point-entered nil point-left nil)
2232   ;; Other special properties:
2233   ;; category, face, display: probably doesn't do any harm.
2234   ;; fontified: is used by font-lock.
2235   ;; syntax-table, local-map: I dunno.
2236   ;; We need to add XEmacs names to the list.
2237   "Property list of with properties.forbidden in message buffers.
2238 The values of the properties are ignored, only the property names are used.")
2239
2240 (defun message-tamago-not-in-use-p (pos)
2241   "Return t when tamago version 4 is not in use at the cursor position.
2242 Tamago version 4 is a popular input method for writing Japanese text.
2243 It uses the properties `intangible', `invisible', `modification-hooks'
2244 and `read-only' when translating ascii or kana text to kanji text.
2245 These properties are essential to work, so we should never strip them."
2246   (not (and (boundp 'egg-modefull-mode)
2247             (symbol-value 'egg-modefull-mode)
2248             (or (memq (get-text-property pos 'intangible)
2249                       '(its-part-1 its-part-2))
2250                 (get-text-property pos 'egg-end)
2251                 (get-text-property pos 'egg-lang)
2252                 (get-text-property pos 'egg-start)))))
2253
2254 (defun message-strip-forbidden-properties (begin end &optional old-length)
2255   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2256 This function is intended to be called from `after-change-functions'.
2257 See also `message-forbidden-properties'."
2258   (when (and message-strip-special-text-properties
2259              (message-tamago-not-in-use-p begin))
2260     (while (not (= begin end))
2261       (when (not (get-text-property begin 'message-hidden))
2262         (remove-text-properties begin (1+ begin)
2263                                 message-forbidden-properties))
2264       (incf begin))))
2265
2266 ;;;###autoload
2267 (define-derived-mode message-mode text-mode "Message"
2268   "Major mode for editing mail and news to be sent.
2269 Like Text Mode but with these additional commands:\\<message-mode-map>
2270 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2271 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2272 C-c C-f  move to a header field (and create it if there isn't):
2273          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2274          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2275          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2276          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2277          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2278          C-c C-f C-o  move to From (\"Originator\")
2279          C-c C-f C-f  move to Followup-To
2280          C-c C-f C-m  move to Mail-Followup-To
2281          C-c C-f C-i  cycle through Importance values
2282          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2283          C-c C-f x    crossposting with FollowUp-To header and note in body
2284          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2285          C-c C-f a    Insert X-No-Archive: header and a note in the body
2286 C-c C-t  `message-insert-to' (add a To header to a news followup)
2287 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2288 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2289 C-c C-b  `message-goto-body' (move to beginning of message text).
2290 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2291 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2292 C-c C-y  `message-yank-original' (insert current message, if any).
2293 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2294 C-c C-e  `message-elide-region' (elide the text between point and mark).
2295 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2296 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2297 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2298 C-c C-a  `mml-attach-file' (attach a file as MIME).
2299 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2300 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2301 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2302 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2303 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2304   (setq local-abbrev-table text-mode-abbrev-table)
2305   (set (make-local-variable 'message-reply-buffer) nil)
2306   (make-local-variable 'message-send-actions)
2307   (make-local-variable 'message-exit-actions)
2308   (make-local-variable 'message-kill-actions)
2309   (make-local-variable 'message-postpone-actions)
2310   (make-local-variable 'message-draft-article)
2311   (setq buffer-offer-save t)
2312   (set (make-local-variable 'facemenu-add-face-function)
2313        (lambda (face end)
2314          (let ((face-fun (cdr (assq face message-face-alist))))
2315            (if face-fun
2316                (funcall face-fun (point) end)
2317              (error "Face %s not configured for %s mode" face mode-name)))
2318          ""))
2319   (set (make-local-variable 'facemenu-remove-face-function) t)
2320   (set (make-local-variable 'message-reply-headers) nil)
2321   (make-local-variable 'message-newsreader)
2322   (make-local-variable 'message-mailer)
2323   (make-local-variable 'message-post-method)
2324   (set (make-local-variable 'message-sent-message-via) nil)
2325   (set (make-local-variable 'message-checksum) nil)
2326   (set (make-local-variable 'message-mime-part) 0)
2327   (message-setup-fill-variables)
2328   (set
2329    (make-local-variable 'paragraph-separate)
2330    (format "\\(%s\\)\\|\\(%s\\)"
2331            paragraph-separate
2332            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
2333   ;; Allow using comment commands to add/remove quoting.
2334   (set (make-local-variable 'comment-start) message-yank-prefix)
2335   (if (featurep 'xemacs)
2336       (message-setup-toolbar)
2337     (set (make-local-variable 'font-lock-defaults)
2338          '(message-font-lock-keywords t))
2339     (if (boundp 'tool-bar-map)
2340         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2341   (easy-menu-add message-mode-menu message-mode-map)
2342   (easy-menu-add message-mode-field-menu message-mode-map)
2343   (gnus-make-local-hook 'after-change-functions)
2344   ;; Mmmm... Forbidden properties...
2345   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2346             nil 'local)
2347   ;; Allow mail alias things.
2348   (when (eq message-mail-alias-type 'abbrev)
2349     (if (fboundp 'mail-abbrevs-setup)
2350         (mail-abbrevs-setup)
2351       (mail-aliases-setup)))
2352   (unless buffer-file-name
2353     (message-set-auto-save-file-name))
2354   (unless (buffer-base-buffer)
2355     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
2356     ;; multibyte is not necessary at all. -- zsh
2357     (mm-enable-multibyte))
2358   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
2359   (mml-mode))
2360
2361 (defun message-setup-fill-variables ()
2362   "Setup message fill variables."
2363   (set (make-local-variable 'fill-paragraph-function)
2364        'message-fill-paragraph)
2365   (make-local-variable 'paragraph-separate)
2366   (make-local-variable 'paragraph-start)
2367   (make-local-variable 'adaptive-fill-regexp)
2368   (unless (boundp 'adaptive-fill-first-line-regexp)
2369     (setq adaptive-fill-first-line-regexp nil))
2370   (make-local-variable 'adaptive-fill-first-line-regexp)
2371   (let ((quote-prefix-regexp
2372          ;; User should change message-cite-prefix-regexp if
2373          ;; message-yank-prefix is set to an abnormal value.
2374          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2375     (setq paragraph-start
2376           (concat
2377            (regexp-quote mail-header-separator) "$\\|"
2378            "[ \t]*$\\|"                 ; blank lines
2379            "-- $\\|"                    ; signature delimiter
2380            "---+$\\|"              ; delimiters for forwarded messages
2381            page-delimiter "$\\|"        ; spoiler warnings
2382            ".*wrote:$\\|"               ; attribution lines
2383            quote-prefix-regexp "$"))    ; empty lines in quoted text
2384     (setq paragraph-separate paragraph-start)
2385     (setq adaptive-fill-regexp
2386           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2387     (setq adaptive-fill-first-line-regexp
2388           (concat quote-prefix-regexp "\\|"
2389                   adaptive-fill-first-line-regexp)))
2390   (make-local-variable 'auto-fill-inhibit-regexp)
2391   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2392   (setq auto-fill-inhibit-regexp nil)
2393   (make-local-variable 'normal-auto-fill-function)
2394   (setq normal-auto-fill-function 'message-do-auto-fill)
2395   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2396   ;; In that case, ensure that it uses the right function.  The real
2397   ;; solution would be not to use `define-derived-mode', and run
2398   ;; `text-mode-hook' ourself at the end of the mode.
2399   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2400   (when auto-fill-function
2401     (setq auto-fill-function normal-auto-fill-function)))
2402
2403 \f
2404
2405 ;;;
2406 ;;; Message mode commands
2407 ;;;
2408
2409 ;;; Movement commands
2410
2411 (defun message-goto-to ()
2412   "Move point to the To header."
2413   (interactive)
2414   (message-position-on-field "To"))
2415
2416 (defun message-goto-from ()
2417   "Move point to the From header."
2418   (interactive)
2419   (message-position-on-field "From"))
2420
2421 (defun message-goto-subject ()
2422   "Move point to the Subject header."
2423   (interactive)
2424   (message-position-on-field "Subject"))
2425
2426 (defun message-goto-cc ()
2427   "Move point to the Cc header."
2428   (interactive)
2429   (message-position-on-field "Cc" "To"))
2430
2431 (defun message-goto-bcc ()
2432   "Move point to the Bcc  header."
2433   (interactive)
2434   (message-position-on-field "Bcc" "Cc" "To"))
2435
2436 (defun message-goto-fcc ()
2437   "Move point to the Fcc header."
2438   (interactive)
2439   (message-position-on-field "Fcc" "To" "Newsgroups"))
2440
2441 (defun message-goto-reply-to ()
2442   "Move point to the Reply-To header."
2443   (interactive)
2444   (message-position-on-field "Reply-To" "Subject"))
2445
2446 (defun message-goto-newsgroups ()
2447   "Move point to the Newsgroups header."
2448   (interactive)
2449   (message-position-on-field "Newsgroups"))
2450
2451 (defun message-goto-distribution ()
2452   "Move point to the Distribution header."
2453   (interactive)
2454   (message-position-on-field "Distribution"))
2455
2456 (defun message-goto-followup-to ()
2457   "Move point to the Followup-To header."
2458   (interactive)
2459   (message-position-on-field "Followup-To" "Newsgroups"))
2460
2461 (defun message-goto-mail-followup-to ()
2462   "Move point to the Mail-Followup-To header."
2463   (interactive)
2464   (message-position-on-field "Mail-Followup-To" "From"))
2465
2466 (defun message-goto-keywords ()
2467   "Move point to the Keywords header."
2468   (interactive)
2469   (message-position-on-field "Keywords" "Subject"))
2470
2471 (defun message-goto-summary ()
2472   "Move point to the Summary header."
2473   (interactive)
2474   (message-position-on-field "Summary" "Subject"))
2475
2476 (defun message-goto-body (&optional interactivep)
2477   "Move point to the beginning of the message body."
2478   (interactive (list t))
2479   (when (and interactivep
2480              (looking-at "[ \t]*\n"))
2481     (expand-abbrev))
2482   (goto-char (point-min))
2483   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2484       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2485
2486 (defun message-goto-eoh ()
2487   "Move point to the end of the headers."
2488   (interactive)
2489   (message-goto-body)
2490   (forward-line -1))
2491
2492 (defun message-goto-signature ()
2493   "Move point to the beginning of the message signature.
2494 If there is no signature in the article, go to the end and
2495 return nil."
2496   (interactive)
2497   (goto-char (point-min))
2498   (if (re-search-forward message-signature-separator nil t)
2499       (forward-line 1)
2500     (goto-char (point-max))
2501     nil))
2502
2503 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2504   "Insert a reasonable MFT header in a post to an unsubscribed list.
2505 When making original posts to a mailing list you are not subscribed to,
2506 you have to type in a MFT header by hand.  The contents, usually, are
2507 the addresses of the list and your own address.  This function inserts
2508 such a header automatically.  It fetches the contents of the To: header
2509 in the current mail buffer, and appends the current `user-mail-address'.
2510
2511 If the optional argument INCLUDE-CC is non-nil, the addresses in the
2512 Cc: header are also put into the MFT."
2513
2514   (interactive "P")
2515   (message-remove-header "Mail-Followup-To")
2516   (let* ((cc (and include-cc (message-fetch-field "Cc")))
2517          (tos (if cc
2518                   (concat (message-fetch-field "To") "," cc)
2519                 (message-fetch-field "To"))))
2520     (message-goto-mail-followup-to)
2521     (insert (concat tos ", " user-mail-address))))
2522
2523 \f
2524
2525 (defun message-insert-to (&optional force)
2526   "Insert a To header that points to the author of the article being replied to.
2527 If the original author requested not to be sent mail, the function signals
2528 an error.
2529 With the prefix argument FORCE, insert the header anyway."
2530   (interactive "P")
2531   (let ((co (message-fetch-reply-field "mail-copies-to")))
2532     (when (and (null force)
2533                co
2534                (or (equal (downcase co) "never")
2535                    (equal (downcase co) "nobody")))
2536       (error "The user has requested not to have copies sent via mail")))
2537   (message-carefully-insert-headers
2538    (list (cons 'To
2539                (or (message-fetch-reply-field "mail-reply-to")
2540                    (message-fetch-reply-field "reply-to")
2541                    (message-fetch-reply-field "from")
2542                    "")))))
2543
2544 (defun message-insert-wide-reply ()
2545   "Insert To and Cc headers as if you were doing a wide reply."
2546   (interactive)
2547   (let ((headers (message-with-reply-buffer
2548                    (message-get-reply-headers t))))
2549     (message-carefully-insert-headers headers)))
2550
2551 (defun message-carefully-insert-headers (headers)
2552   (dolist (header headers)
2553     (let ((header-name (symbol-name (car header))))
2554       (when (and (message-position-on-field header-name)
2555                  (mail-fetch-field header-name)
2556                  (not (string-match "\\` *\\'"
2557                                     (mail-fetch-field header-name))))
2558         (insert ", "))
2559       (insert (cdr header)))))
2560
2561 (defun message-widen-reply ()
2562   "Widen the reply to include maximum recipients."
2563   (interactive)
2564   (let ((follow-to
2565          (and message-reply-buffer
2566               (buffer-name message-reply-buffer)
2567               (save-excursion
2568                 (set-buffer message-reply-buffer)
2569                 (message-get-reply-headers t)))))
2570     (save-excursion
2571       (save-restriction
2572         (message-narrow-to-headers)
2573         (dolist (elem follow-to)
2574           (message-remove-header (symbol-name (car elem)))
2575           (goto-char (point-min))
2576           (insert (symbol-name (car elem)) ": "
2577                   (cdr elem) "\n"))))))
2578
2579 (defun message-insert-newsgroups ()
2580   "Insert the Newsgroups header from the article being replied to."
2581   (interactive)
2582   (when (and (message-position-on-field "Newsgroups")
2583              (mail-fetch-field "newsgroups")
2584              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
2585     (insert ","))
2586   (insert (or (message-fetch-reply-field "newsgroups") "")))
2587
2588 \f
2589
2590 ;;; Various commands
2591
2592 (defun message-delete-not-region (beg end)
2593   "Delete everything in the body of the current message outside of the region."
2594   (interactive "r")
2595   (let (citeprefix)
2596     (save-excursion
2597       (goto-char beg)
2598       ;; snarf citation prefix, if appropriate
2599       (unless (eq (point) (progn (beginning-of-line) (point)))
2600         (when (looking-at message-cite-prefix-regexp)
2601           (setq citeprefix (match-string 0))))
2602       (goto-char end)
2603       (delete-region (point) (if (not (message-goto-signature))
2604                                  (point)
2605                                (forward-line -2)
2606                                (point)))
2607       (insert "\n")
2608       (goto-char beg)
2609       (delete-region beg (progn (message-goto-body)
2610                                 (forward-line 2)
2611                                 (point)))
2612       (when citeprefix
2613         (insert citeprefix))))
2614   (when (message-goto-signature)
2615     (forward-line -2)))
2616
2617 (defun message-kill-to-signature ()
2618   "Deletes all text up to the signature."
2619   (interactive)
2620   (let ((point (point)))
2621     (message-goto-signature)
2622     (unless (eobp)
2623       (end-of-line -1))
2624     (kill-region point (point))
2625     (unless (bolp)
2626       (insert "\n"))))
2627
2628 (defun message-newline-and-reformat (&optional arg not-break)
2629   "Insert four newlines, and then reformat if inside quoted text.
2630 Prefix arg means justify as well."
2631   (interactive (list (if current-prefix-arg 'full)))
2632   (let (quoted point beg end leading-space bolp)
2633     (setq point (point))
2634     (beginning-of-line)
2635     (setq beg (point))
2636     (setq bolp (= beg point))
2637     ;; Find first line of the paragraph.
2638     (if not-break
2639         (while (and (not (eobp))
2640                     (not (looking-at message-cite-prefix-regexp))
2641                     (looking-at paragraph-start))
2642           (forward-line 1)))
2643     ;; Find the prefix
2644     (when (looking-at message-cite-prefix-regexp)
2645       (setq quoted (match-string 0))
2646       (goto-char (match-end 0))
2647       (looking-at "[ \t]*")
2648       (setq leading-space (match-string 0)))
2649     (if (and quoted
2650              (not not-break)
2651              (not bolp)
2652              (< (- point beg) (length quoted)))
2653         ;; break inside the cite prefix.
2654         (setq quoted nil
2655               end nil))
2656     (if quoted
2657         (progn
2658           (forward-line 1)
2659           (while (and (not (eobp))
2660                       (not (looking-at paragraph-separate))
2661                       (looking-at message-cite-prefix-regexp)
2662                       (equal quoted (match-string 0)))
2663             (goto-char (match-end 0))
2664             (looking-at "[ \t]*")
2665             (if (> (length leading-space) (length (match-string 0)))
2666                 (setq leading-space (match-string 0)))
2667             (forward-line 1))
2668           (setq end (point))
2669           (goto-char beg)
2670           (while (and (if (bobp) nil (forward-line -1) t)
2671                       (not (looking-at paragraph-start))
2672                       (looking-at message-cite-prefix-regexp)
2673                       (equal quoted (match-string 0)))
2674             (setq beg (point))
2675             (goto-char (match-end 0))
2676             (looking-at "[ \t]*")
2677             (if (> (length leading-space) (length (match-string 0)))
2678                 (setq leading-space (match-string 0)))))
2679       (while (and (not (eobp))
2680                   (not (looking-at paragraph-separate))
2681                   (not (looking-at message-cite-prefix-regexp)))
2682         (forward-line 1))
2683       (setq end (point))
2684       (goto-char beg)
2685       (while (and (if (bobp) nil (forward-line -1) t)
2686                   (not (looking-at paragraph-start))
2687                   (not (looking-at message-cite-prefix-regexp)))
2688         (setq beg (point))))
2689     (goto-char point)
2690     (save-restriction
2691       (narrow-to-region beg end)
2692       (if not-break
2693           (setq point nil)
2694         (if bolp
2695             (newline)
2696           (newline)
2697           (newline))
2698         (setq point (point))
2699         ;; (newline 2) doesn't mark both newline's as hard, so call
2700         ;; newline twice. -jas
2701         (newline)
2702         (newline)
2703         (delete-region (point) (re-search-forward "[ \t]*"))
2704         (when (and quoted (not bolp))
2705           (insert quoted leading-space)))
2706       (undo-boundary)
2707       (if quoted
2708           (let* ((adaptive-fill-regexp
2709                   (regexp-quote (concat quoted leading-space)))
2710                  (adaptive-fill-first-line-regexp
2711                   adaptive-fill-regexp ))
2712             (fill-paragraph arg))
2713         (fill-paragraph arg))
2714       (if point (goto-char point)))))
2715
2716 (defun message-fill-paragraph (&optional arg)
2717   "Like `fill-paragraph'."
2718   (interactive (list (if current-prefix-arg 'full)))
2719   (if (if (boundp 'filladapt-mode) filladapt-mode)
2720       nil
2721     (message-newline-and-reformat arg t)
2722     t))
2723
2724 ;; Is it better to use `mail-header-end'?
2725 (defun message-point-in-header-p ()
2726   "Return t if point is in the header."
2727   (save-excursion
2728     (let ((p (point)))
2729       (goto-char (point-min))
2730       (not (re-search-forward
2731             (concat "^" (regexp-quote mail-header-separator) "\n")
2732             p t)))))
2733
2734 (defun message-do-auto-fill ()
2735   "Like `do-auto-fill', but don't fill in message header."
2736   (unless (message-point-in-header-p)
2737     (do-auto-fill)))
2738
2739 (defun message-insert-signature (&optional force)
2740   "Insert a signature.  See documentation for variable `message-signature'."
2741   (interactive (list 0))
2742   (let* ((signature
2743           (cond
2744            ((and (null message-signature)
2745                  (eq force 0))
2746             (save-excursion
2747               (goto-char (point-max))
2748               (not (re-search-backward message-signature-separator nil t))))
2749            ((and (null message-signature)
2750                  force)
2751             t)
2752            ((message-functionp message-signature)
2753             (funcall message-signature))
2754            ((listp message-signature)
2755             (eval message-signature))
2756            (t message-signature)))
2757          (signature
2758           (cond ((stringp signature)
2759                  signature)
2760                 ((and (eq t signature)
2761                       message-signature-file
2762                       (file-exists-p message-signature-file))
2763                  signature))))
2764     (when signature
2765       (goto-char (point-max))
2766       ;; Insert the signature.
2767       (unless (bolp)
2768         (insert "\n"))
2769       (when message-signature-insert-empty-line
2770         (insert "\n"))
2771       (insert "-- \n")
2772       (if (eq signature t)
2773           (insert-file-contents message-signature-file)
2774         (insert signature))
2775       (goto-char (point-max))
2776       (or (bolp) (insert "\n")))))
2777
2778 (defun message-insert-importance-high ()
2779   "Insert header to mark message as important."
2780   (interactive)
2781   (save-excursion
2782     (message-remove-header "Importance")
2783     (message-goto-eoh)
2784     (insert "Importance: high\n")))
2785
2786 (defun message-insert-importance-low ()
2787   "Insert header to mark message as unimportant."
2788   (interactive)
2789   (save-excursion
2790     (message-remove-header "Importance")
2791     (message-goto-eoh)
2792     (insert "Importance: low\n")))
2793
2794 (defun message-insert-or-toggle-importance ()
2795   "Insert a \"Importance: high\" header, or cycle through the header values.
2796 The three allowed values according to RFC 1327 are `high', `normal'
2797 and `low'."
2798   (interactive)
2799   (save-excursion
2800     (let ((valid '("high" "normal" "low"))
2801           (new "high")
2802           cur)
2803       (when (setq cur (message-fetch-field "Importance"))
2804         (message-remove-header "Importance")
2805         (setq new (cond ((string= cur "high")
2806                          "low")
2807                         ((string= cur "low")
2808                          "normal")
2809                         (t
2810                          "high"))))
2811       (message-goto-eoh)
2812       (insert (format "Importance: %s\n" new)))))
2813
2814 (defun message-insert-disposition-notification-to ()
2815   "Request a disposition notification (return receipt) to this message.
2816 Note that this should not be used in newsgroups."
2817   (interactive)
2818   (save-excursion
2819     (message-remove-header "Disposition-Notification-To")
2820     (message-goto-eoh)
2821     (insert (format "Disposition-Notification-To: %s\n"
2822                     (or (message-fetch-field "From") (message-make-from))))))
2823
2824 (defun message-elide-region (b e)
2825   "Elide the text in the region.
2826 An ellipsis (from `message-elide-ellipsis') will be inserted where the
2827 text was killed."
2828   (interactive "r")
2829   (kill-region b e)
2830   (insert message-elide-ellipsis))
2831
2832 (defvar message-caesar-translation-table nil)
2833
2834 (defun message-caesar-region (b e &optional n)
2835   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
2836   (interactive
2837    (list
2838     (min (point) (or (mark t) (point)))
2839     (max (point) (or (mark t) (point)))
2840     (when current-prefix-arg
2841       (prefix-numeric-value current-prefix-arg))))
2842
2843   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
2844   (unless (or (zerop n)                 ; no action needed for a rot of 0
2845               (= b e))                  ; no region to rotate
2846     ;; We build the table, if necessary.
2847     (when (or (not message-caesar-translation-table)
2848               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
2849       (setq message-caesar-translation-table
2850             (message-make-caesar-translation-table n)))
2851     (translate-region b e message-caesar-translation-table)))
2852
2853 (defun message-make-caesar-translation-table (n)
2854   "Create a rot table with offset N."
2855   (let ((i -1)
2856         (table (make-string 256 0)))
2857     (while (< (incf i) 256)
2858       (aset table i i))
2859     (concat
2860      (substring table 0 ?A)
2861      (substring table (+ ?A n) (+ ?A n (- 26 n)))
2862      (substring table ?A (+ ?A n))
2863      (substring table (+ ?A 26) ?a)
2864      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2865      (substring table ?a (+ ?a n))
2866      (substring table (+ ?a 26) 255))))
2867
2868 (defun message-caesar-buffer-body (&optional rotnum)
2869   "Caesar rotate all letters in the current buffer by 13 places.
2870 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2871 With prefix arg, specifies the number of places to rotate each letter forward.
2872 Mail and USENET news headers are not rotated."
2873   (interactive (if current-prefix-arg
2874                    (list (prefix-numeric-value current-prefix-arg))
2875                  (list nil)))
2876   (save-excursion
2877     (save-restriction
2878       (when (message-goto-body)
2879         (narrow-to-region (point) (point-max)))
2880       (message-caesar-region (point-min) (point-max) rotnum))))
2881
2882 (defun message-pipe-buffer-body (program)
2883   "Pipe the message body in the current buffer through PROGRAM."
2884   (save-excursion
2885     (save-restriction
2886       (when (message-goto-body)
2887         (narrow-to-region (point) (point-max)))
2888       (shell-command-on-region
2889        (point-min) (point-max) program nil t))))
2890
2891 (defun message-rename-buffer (&optional enter-string)
2892   "Rename the *message* buffer to \"*message* RECIPIENT\".
2893 If the function is run with a prefix, it will ask for a new buffer
2894 name, rather than giving an automatic name."
2895   (interactive "Pbuffer name: ")
2896   (save-excursion
2897     (save-restriction
2898       (goto-char (point-min))
2899       (narrow-to-region (point)
2900                         (search-forward mail-header-separator nil 'end))
2901       (let* ((mail-to (or
2902                        (if (message-news-p) (message-fetch-field "Newsgroups")
2903                          (message-fetch-field "To"))
2904                        ""))
2905              (mail-trimmed-to
2906               (if (string-match "," mail-to)
2907                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2908                 mail-to))
2909              (name-default (concat "*message* " mail-trimmed-to))
2910              (name (if enter-string
2911                        (read-string "New buffer name: " name-default)
2912                      name-default)))
2913         (rename-buffer name t)))))
2914
2915 (defun message-fill-yanked-message (&optional justifyp)
2916   "Fill the paragraphs of a message yanked into this one.
2917 Numeric argument means justify as well."
2918   (interactive "P")
2919   (save-excursion
2920     (goto-char (point-min))
2921     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2922     (let ((fill-prefix message-yank-prefix))
2923       (fill-individual-paragraphs (point) (point-max) justifyp))))
2924
2925 (defun message-indent-citation ()
2926   "Modify text just inserted from a message to be cited.
2927 The inserted text should be the region.
2928 When this function returns, the region is again around the modified text.
2929
2930 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2931 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2932   (let ((start (point)))
2933     ;; Remove unwanted headers.
2934     (when message-ignored-cited-headers
2935       (let (all-removed)
2936         (save-restriction
2937           (narrow-to-region
2938            (goto-char start)
2939            (if (search-forward "\n\n" nil t)
2940                (1- (point))
2941              (point)))
2942           (message-remove-header message-ignored-cited-headers t)
2943           (when (= (point-min) (point-max))
2944             (setq all-removed t))
2945           (goto-char (point-max)))
2946         (if all-removed
2947             (goto-char start)
2948           (forward-line 1))))
2949     ;; Delete blank lines at the start of the buffer.
2950     (while (and (point-min)
2951                 (eolp)
2952                 (not (eobp)))
2953       (message-delete-line))
2954     ;; Delete blank lines at the end of the buffer.
2955     (goto-char (point-max))
2956     (unless (eolp)
2957       (insert "\n"))
2958     (while (and (zerop (forward-line -1))
2959                 (looking-at "$"))
2960       (message-delete-line))
2961     ;; Do the indentation.
2962     (if (null message-yank-prefix)
2963         (indent-rigidly start (mark t) message-indentation-spaces)
2964       (save-excursion
2965         (goto-char start)
2966         (while (< (point) (mark t))
2967           (if (or (looking-at ">") (looking-at "^$"))
2968               (insert message-yank-cited-prefix)
2969             (insert message-yank-prefix))
2970           (forward-line 1))))
2971     (goto-char start)))
2972
2973 (defun message-yank-original (&optional arg)
2974   "Insert the message being replied to, if any.
2975 Puts point before the text and mark after.
2976 Normally indents each nonblank line ARG spaces (default 3).  However,
2977 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2978
2979 This function uses `message-cite-function' to do the actual citing.
2980
2981 Just \\[universal-argument] as argument means don't indent, insert no
2982 prefix, and don't delete any headers."
2983   (interactive "P")
2984   (let ((modified (buffer-modified-p)))
2985     (when (and message-reply-buffer
2986                message-cite-function)
2987       (delete-windows-on message-reply-buffer t)
2988       (insert-buffer message-reply-buffer)
2989       (unless arg
2990         (funcall message-cite-function))
2991       (message-exchange-point-and-mark)
2992       (unless (bolp)
2993         (insert ?\n))
2994       (unless modified
2995         (setq message-checksum (message-checksum))))))
2996
2997 (defun message-yank-buffer (buffer)
2998   "Insert BUFFER into the current buffer and quote it."
2999   (interactive "bYank buffer: ")
3000   (let ((message-reply-buffer buffer))
3001     (save-window-excursion
3002       (message-yank-original))))
3003
3004 (defun message-buffers ()
3005   "Return a list of active message buffers."
3006   (let (buffers)
3007     (save-excursion
3008       (dolist (buffer (buffer-list t))
3009         (set-buffer buffer)
3010         (when (and (eq major-mode 'message-mode)
3011                    (null message-sent-message-via))
3012           (push (buffer-name buffer) buffers))))
3013     (nreverse buffers)))
3014
3015 (defun message-cite-original-without-signature ()
3016   "Cite function in the standard Message manner."
3017   (let ((start (point))
3018         (end (mark t))
3019         (functions
3020          (when message-indent-citation-function
3021            (if (listp message-indent-citation-function)
3022                message-indent-citation-function
3023              (list message-indent-citation-function)))))
3024     (mml-quote-region start end)
3025     ;; Allow undoing.
3026     (undo-boundary)
3027     (goto-char end)
3028     (when (re-search-backward message-signature-separator start t)
3029       ;; Also peel off any blank lines before the signature.
3030       (forward-line -1)
3031       (while (looking-at "^[ \t]*$")
3032         (forward-line -1))
3033       (forward-line 1)
3034       (delete-region (point) end)
3035       (unless (search-backward "\n\n" start t)
3036         ;; Insert a blank line if it is peeled off.
3037         (insert "\n")))
3038     (goto-char start)
3039     (while functions
3040       (funcall (pop functions)))
3041     (when message-citation-line-function
3042       (unless (bolp)
3043         (insert "\n"))
3044       (funcall message-citation-line-function))))
3045
3046 (eval-when-compile (defvar mail-citation-hook)) ;Compiler directive
3047 (defun message-cite-original ()
3048   "Cite function in the standard Message manner."
3049   (if (and (boundp 'mail-citation-hook)
3050            mail-citation-hook)
3051       (run-hooks 'mail-citation-hook)
3052     (let ((start (point))
3053           (end (mark t))
3054           (functions
3055            (when message-indent-citation-function
3056              (if (listp message-indent-citation-function)
3057                  message-indent-citation-function
3058                (list message-indent-citation-function)))))
3059       (mml-quote-region start end)
3060       (goto-char start)
3061       (while functions
3062         (funcall (pop functions)))
3063       (when message-citation-line-function
3064         (unless (bolp)
3065           (insert "\n"))
3066         (funcall message-citation-line-function)))))
3067
3068 (defun message-insert-citation-line ()
3069   "Insert a simple citation line."
3070   (when message-reply-headers
3071     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3072
3073 (defun message-position-on-field (header &rest afters)
3074   (let ((case-fold-search t))
3075     (save-restriction
3076       (narrow-to-region
3077        (goto-char (point-min))
3078        (progn
3079          (re-search-forward
3080           (concat "^" (regexp-quote mail-header-separator) "$"))
3081          (match-beginning 0)))
3082       (goto-char (point-min))
3083       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3084           (progn
3085             (re-search-forward "^[^ \t]" nil 'move)
3086             (beginning-of-line)
3087             (skip-chars-backward "\n")
3088             t)
3089         (while (and afters
3090                     (not (re-search-forward
3091                           (concat "^" (regexp-quote (car afters)) ":")
3092                           nil t)))
3093           (pop afters))
3094         (when afters
3095           (re-search-forward "^[^ \t]" nil 'move)
3096           (beginning-of-line))
3097         (insert header ": \n")
3098         (forward-char -1)
3099         nil))))
3100
3101 (defun message-remove-signature ()
3102   "Remove the signature from the text between point and mark.
3103 The text will also be indented the normal way."
3104   (save-excursion
3105     (let ((start (point))
3106           mark)
3107       (if (not (re-search-forward message-signature-separator (mark t) t))
3108           ;; No signature here, so we just indent the cited text.
3109           (message-indent-citation)
3110         ;; Find the last non-empty line.
3111         (forward-line -1)
3112         (while (looking-at "[ \t]*$")
3113           (forward-line -1))
3114         (forward-line 1)
3115         (setq mark (set-marker (make-marker) (point)))
3116         (goto-char start)
3117         (message-indent-citation)
3118         ;; Enable undoing the deletion.
3119         (undo-boundary)
3120         (delete-region mark (mark t))
3121         (set-marker mark nil)))))
3122
3123 \f
3124
3125 ;;;
3126 ;;; Sending messages
3127 ;;;
3128
3129 (defun message-send-and-exit (&optional arg)
3130   "Send message like `message-send', then, if no errors, exit from mail buffer."
3131   (interactive "P")
3132   (let ((buf (current-buffer))
3133         (actions message-exit-actions))
3134     (when (and (message-send arg)
3135                (buffer-name buf))
3136       (if message-kill-buffer-on-exit
3137           (kill-buffer buf)
3138         (bury-buffer buf)
3139         (when (eq buf (current-buffer))
3140           (message-bury buf)))
3141       (message-do-actions actions)
3142       t)))
3143
3144 (defun message-dont-send ()
3145   "Don't send the message you have been editing.
3146 Instead, just auto-save the buffer and then bury it."
3147   (interactive)
3148   (set-buffer-modified-p t)
3149   (save-buffer)
3150   (let ((actions message-postpone-actions))
3151     (message-bury (current-buffer))
3152     (message-do-actions actions)))
3153
3154 (defun message-kill-buffer ()
3155   "Kill the current buffer."
3156   (interactive)
3157   (when (or (not (buffer-modified-p))
3158             (yes-or-no-p "Message modified; kill anyway? "))
3159     (let ((actions message-kill-actions)
3160           (draft-article message-draft-article)
3161           (auto-save-file-name buffer-auto-save-file-name)
3162           (file-name buffer-file-name)
3163           (modified (buffer-modified-p)))
3164       (setq buffer-file-name nil)
3165       (kill-buffer (current-buffer))
3166       (when (and (or (and auto-save-file-name
3167                           (file-exists-p auto-save-file-name))
3168                      (and file-name
3169                           (file-exists-p file-name)))
3170                (yes-or-no-p (format "Remove the backup file%s? "
3171                                     (if modified " too" ""))))
3172         (ignore-errors
3173           (delete-file auto-save-file-name))
3174         (let ((message-draft-article draft-article))
3175           (message-disassociate-draft)))
3176       (message-do-actions actions))))
3177
3178 (defun message-bury (buffer)
3179   "Bury this mail BUFFER."
3180   (let ((newbuf (other-buffer buffer)))
3181     (bury-buffer buffer)
3182     (if (and (fboundp 'frame-parameters)
3183              (cdr (assq 'dedicated (frame-parameters)))
3184              (not (null (delq (selected-frame) (visible-frame-list)))))
3185         (delete-frame (selected-frame))
3186       (switch-to-buffer newbuf))))
3187
3188 (defun message-send (&optional arg)
3189   "Send the message in the current buffer.
3190 If `message-interactive' is non-nil, wait for success indication or
3191 error messages, and inform user.
3192 Otherwise any failure is reported in a message back to the user from
3193 the mailer.
3194 The usage of ARG is defined by the instance that called Message.
3195 It should typically alter the sending method in some way or other."
3196   (interactive "P")
3197   ;; Make it possible to undo the coming changes.
3198   (undo-boundary)
3199   (let ((inhibit-read-only t))
3200     (put-text-property (point-min) (point-max) 'read-only nil))
3201   (message-fix-before-sending)
3202   (run-hooks 'message-send-hook)
3203   (message message-sending-message)
3204   (let ((alist message-send-method-alist)
3205         (success t)
3206         elem sent dont-barf-on-no-method
3207         (message-options message-options))
3208     (message-options-set-recipient)
3209     (while (and success
3210                 (setq elem (pop alist)))
3211       (when (funcall (cadr elem))
3212         (when (and (or (not (memq (car elem)
3213                                   message-sent-message-via))
3214                        (not (message-fetch-field "supersedes"))
3215                        (if (or (message-gnksa-enable-p 'multiple-copies)
3216                                (not (eq (car elem) 'news)))
3217                            (y-or-n-p
3218                             (format
3219                              "Already sent message via %s; resend? "
3220                              (car elem)))
3221                          (error "Denied posting -- multiple copies")))
3222                    (setq success (funcall (caddr elem) arg)))
3223           (setq sent t))))
3224     (unless (or sent
3225                 (not success)
3226                 (let ((fcc (message-fetch-field "Fcc"))
3227                       (gcc (message-fetch-field "Gcc")))
3228                   (when (or fcc gcc)
3229                     (or (eq message-allow-no-recipients 'always)
3230                         (and (not (eq message-allow-no-recipients 'never))
3231                              (setq dont-barf-on-no-method
3232                                    (gnus-y-or-n-p
3233                                     (format "No receiver, perform %s anyway? "
3234                                             (cond ((and fcc gcc) "Fcc and Gcc")
3235                                                   (fcc "Fcc")
3236                                                   (t "Gcc"))))))))))
3237       (error "No methods specified to send by"))
3238     (when (or dont-barf-on-no-method
3239               (and success sent))
3240       (message-do-fcc)
3241       (save-excursion
3242         (run-hooks 'message-sent-hook))
3243       (message "Sending...done")
3244       ;; Mark the buffer as unmodified and delete auto-save.
3245       (set-buffer-modified-p nil)
3246       (delete-auto-save-file-if-necessary t)
3247       (message-disassociate-draft)
3248       ;; Delete other mail buffers and stuff.
3249       (message-do-send-housekeeping)
3250       (message-do-actions message-send-actions)
3251       ;; Return success.
3252       t)))
3253
3254 (defun message-send-via-mail (arg)
3255   "Send the current message via mail."
3256   (message-send-mail arg))
3257
3258 (defun message-send-via-news (arg)
3259   "Send the current message via news."
3260   (funcall message-send-news-function arg))
3261
3262 (defmacro message-check (type &rest forms)
3263   "Eval FORMS if TYPE is to be checked."
3264   `(or (message-check-element ,type)
3265        (save-excursion
3266          ,@forms)))
3267
3268 (put 'message-check 'lisp-indent-function 1)
3269 (put 'message-check 'edebug-form-spec '(form body))
3270
3271 (defun message-text-with-property (prop)
3272   "Return a list of all points where the text has PROP."
3273   (let ((points nil)
3274         (point (point-min)))
3275     (save-excursion
3276       (while (< point (point-max))
3277         (when (get-text-property point prop)
3278           (push point points))
3279         (incf point)))
3280     (nreverse points)))
3281
3282 (defun message-fix-before-sending ()
3283   "Do various things to make the message nice before sending it."
3284   ;; Make sure there's a newline at the end of the message.
3285   (goto-char (point-max))
3286   (unless (bolp)
3287     (insert "\n"))
3288   ;; Make the hidden headers visible.
3289   (let ((points (message-text-with-property 'message-hidden)))
3290     (when points
3291       (goto-char (car points))
3292       (dolist (point points)
3293         (add-text-properties point (1+ point)
3294                              '(invisible nil intangible nil)))))
3295   ;; Make invisible text visible.
3296   (message-check 'invisible-text
3297     (let ((points (message-text-with-property 'invisible)))
3298       (when points
3299         (goto-char (car points))
3300         (dolist (point points)
3301           (add-text-properties point (1+ point)
3302                                '(invisible nil face highlight
3303                                            font-lock-face highlight)))
3304         (unless (yes-or-no-p
3305                  "Invisible text found and made visible; continue posting? ")
3306           (error "Invisible text found and made visible")))))
3307   (message-check 'illegible-text
3308     (let (found choice)
3309       (message-goto-body)
3310       (skip-chars-forward mm-7bit-chars)
3311       (while (not (eobp))
3312         (when (let ((char (char-after)))
3313                 (or (< (mm-char-int char) 128)
3314                     (and (mm-multibyte-p)
3315                          (memq (char-charset char)
3316                                '(eight-bit-control eight-bit-graphic
3317                                                    control-1)))))
3318           (add-text-properties (point) (1+ (point))
3319                                '(font-lock-face highlight face highlight))
3320           (setq found t))
3321         (forward-char)
3322         (skip-chars-forward mm-7bit-chars))
3323       (when found
3324         (setq choice
3325               (gnus-multiple-choice
3326                "Illegible text found.  Continue posting?"
3327                '((?d "Remove and continue posting")
3328                  (?r "Replace with dots and continue posting")
3329                  (?i "Ignore and continue posting")
3330                  (?e "Continue editing"))))
3331         (if (eq choice ?e)
3332           (error "Illegible text found"))
3333         (message-goto-body)
3334         (skip-chars-forward mm-7bit-chars)
3335         (while (not (eobp))
3336           (when (let ((char (char-after)))
3337                   (or (< (mm-char-int char) 128)
3338                       (and (mm-multibyte-p)
3339                            (memq (char-charset char)
3340                                  '(eight-bit-control eight-bit-graphic
3341                                                      control-1)))))
3342             (if (eq choice ?i)
3343                 (remove-text-properties (point) (1+ (point))
3344                                         '(font-lock-face highlight face highlight))
3345               (delete-char 1)
3346               (when (eq choice ?r)
3347                 (insert "."))))
3348           (forward-char)
3349           (skip-chars-forward mm-7bit-chars))))))
3350
3351 (defun message-add-action (action &rest types)
3352   "Add ACTION to be performed when doing an exit of type TYPES."
3353   (while types
3354     (add-to-list (intern (format "message-%s-actions" (pop types)))
3355                  action)))
3356
3357 (defun message-delete-action (action &rest types)
3358   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
3359   (let (var)
3360     (while types
3361       (set (setq var (intern (format "message-%s-actions" (pop types))))
3362            (delq action (symbol-value var))))))
3363
3364 (defun message-do-actions (actions)
3365   "Perform all actions in ACTIONS."
3366   ;; Now perform actions on successful sending.
3367   (while actions
3368     (ignore-errors
3369       (cond
3370        ;; A simple function.
3371        ((message-functionp (car actions))
3372         (funcall (car actions)))
3373        ;; Something to be evaled.
3374        (t
3375         (eval (car actions)))))
3376     (pop actions)))
3377
3378 (defun message-send-mail-partially ()
3379   "Send mail as message/partial."
3380   ;; replace the header delimiter with a blank line
3381   (goto-char (point-min))
3382   (re-search-forward
3383    (concat "^" (regexp-quote mail-header-separator) "\n"))
3384   (replace-match "\n")
3385   (run-hooks 'message-send-mail-hook)
3386   (let ((p (goto-char (point-min)))
3387         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
3388         (curbuf (current-buffer))
3389         (id (message-make-message-id)) (n 1)
3390         plist total  header required-mail-headers)
3391     (while (not (eobp))
3392       (if (< (point-max) (+ p message-send-mail-partially-limit))
3393           (goto-char (point-max))
3394         (goto-char (+ p message-send-mail-partially-limit))
3395         (beginning-of-line)
3396         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
3397       (push p plist)
3398       (setq p (point)))
3399     (setq total (length plist))
3400     (push (point-max) plist)
3401     (setq plist (nreverse plist))
3402     (unwind-protect
3403         (save-excursion
3404           (setq p (pop plist))
3405           (while plist
3406             (set-buffer curbuf)
3407             (copy-to-buffer tembuf p (car plist))
3408             (set-buffer tembuf)
3409             (goto-char (point-min))
3410             (if header
3411                 (progn
3412                   (goto-char (point-min))
3413                   (narrow-to-region (point) (point))
3414                   (insert header))
3415               (message-goto-eoh)
3416               (setq header (buffer-substring (point-min) (point)))
3417               (goto-char (point-min))
3418               (narrow-to-region (point) (point))
3419               (insert header)
3420               (message-remove-header "Mime-Version")
3421               (message-remove-header "Content-Type")
3422               (message-remove-header "Content-Transfer-Encoding")
3423               (message-remove-header "Message-ID")
3424               (message-remove-header "Lines")
3425               (goto-char (point-max))
3426               (insert "Mime-Version: 1.0\n")
3427               (setq header (buffer-string)))
3428             (goto-char (point-max))
3429             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
3430                             id n total))
3431             (forward-char -1)
3432             (let ((mail-header-separator ""))
3433               (when (memq 'Message-ID message-required-mail-headers)
3434                 (insert "Message-ID: " (message-make-message-id) "\n"))
3435               (when (memq 'Lines message-required-mail-headers)
3436                 (insert "Lines: " (message-make-lines) "\n"))
3437               (message-goto-subject)
3438               (end-of-line)
3439               (insert (format " (%d/%d)" n total))
3440               (widen)
3441               (mm-with-unibyte-current-buffer
3442                 (funcall (or message-send-mail-real-function
3443                              message-send-mail-function))))
3444             (setq n (+ n 1))
3445             (setq p (pop plist))
3446             (erase-buffer)))
3447       (kill-buffer tembuf))))
3448
3449 (defun message-send-mail (&optional arg)
3450   (require 'mail-utils)
3451   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
3452          (case-fold-search nil)
3453          (news (message-news-p))
3454          (mailbuf (current-buffer))
3455          (message-this-is-mail t)
3456          (message-posting-charset
3457           (if (fboundp 'gnus-setup-posting-charset)
3458               (gnus-setup-posting-charset nil)
3459             message-posting-charset))
3460          (headers message-required-mail-headers))
3461     (save-restriction
3462       (message-narrow-to-headers)
3463       ;; Generate the Mail-Followup-To header if the header is not there...
3464       (if (and (message-subscribed-p)
3465                (not (mail-fetch-field "mail-followup-to")))
3466           (setq headers
3467                 (cons
3468                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
3469                  message-required-mail-headers))
3470         ;; otherwise, delete the MFT header if the field is empty
3471         (when (equal "" (mail-fetch-field "mail-followup-to"))
3472           (message-remove-header "^Mail-Followup-To:")))
3473       ;; Insert some headers.
3474       (let ((message-deletable-headers
3475              (if news nil message-deletable-headers)))
3476         (message-generate-headers headers))
3477       ;; Let the user do all of the above.
3478       (run-hooks 'message-header-hook))
3479     (unwind-protect
3480         (save-excursion
3481           (set-buffer tembuf)
3482           (erase-buffer)
3483           ;; Avoid copying text props (except hard newlines).
3484           (insert (with-current-buffer mailbuf
3485                     (mml-buffer-substring-no-properties-except-hard-newlines
3486                      (point-min) (point-max))))
3487           ;; Remove some headers.
3488           (message-encode-message-body)
3489           (save-restriction
3490             (message-narrow-to-headers)
3491             ;; We (re)generate the Lines header.
3492             (when (memq 'Lines message-required-mail-headers)
3493               (message-generate-headers '(Lines)))
3494             ;; Remove some headers.
3495             (message-remove-header message-ignored-mail-headers t)
3496             (let ((mail-parse-charset message-default-charset))
3497               (mail-encode-encoded-word-buffer)))
3498           (goto-char (point-max))
3499           ;; require one newline at the end.
3500           (or (= (preceding-char) ?\n)
3501               (insert ?\n))
3502           (message-cleanup-headers)
3503           ;; FIXME: we're inserting the courtesy copy after encoding.
3504           ;; This is wrong if the courtesy copy string contains
3505           ;; non-ASCII characters. -- jh
3506           (when
3507               (save-restriction
3508                 (message-narrow-to-headers)
3509                 (and news
3510                      (or (message-fetch-field "cc")
3511                          (message-fetch-field "bcc")
3512                          (message-fetch-field "to"))
3513                      (let ((content-type (message-fetch-field
3514                                           "content-type")))
3515                        (and
3516                         (or
3517                          (not content-type)
3518                          (string= "text/plain"
3519                                   (car 
3520                                    (mail-header-parse-content-type
3521                                     content-type))))
3522                         (not
3523                          (string= "base64"
3524                                   (message-fetch-field
3525                                    "content-transfer-encoding")))))))
3526             (message-insert-courtesy-copy))
3527           (if (or (not message-send-mail-partially-limit)
3528                   (< (point-max) message-send-mail-partially-limit)
3529                   (not (message-y-or-n-p
3530                         "The message size is too large, split? "
3531                         t
3532                         "\
3533 The message size, "
3534                         (/ (point-max) 1000) "KB, is too large.
3535
3536 Some mail gateways (MTA's) bounce large messages.  To avoid the
3537 problem, answer `y', and the message will be split into several
3538 smaller pieces, the size of each is about "
3539                         (/ message-send-mail-partially-limit 1000)
3540                         "KB except the last
3541 one.
3542
3543 However, some mail readers (MUA's) can't read split messages, i.e.,
3544 mails in message/partially format. Answer `n', and the message will be
3545 sent in one piece.
3546
3547 The size limit is controlled by `message-send-mail-partially-limit'.
3548 If you always want Gnus to send messages in one piece, set
3549 `message-send-mail-partially-limit' to nil.
3550 ")))
3551               (mm-with-unibyte-current-buffer
3552                 (message "Sending via mail...")
3553                 (funcall (or message-send-mail-real-function
3554                              message-send-mail-function)))
3555             (message-send-mail-partially)))
3556       (kill-buffer tembuf))
3557     (set-buffer mailbuf)
3558     (push 'mail message-sent-message-via)))
3559
3560 (defun message-send-mail-with-sendmail ()
3561   "Send off the prepared buffer with sendmail."
3562   (let ((errbuf (if message-interactive
3563                     (message-generate-new-buffer-clone-locals
3564                      " sendmail errors")
3565                   0))
3566         resend-to-addresses delimline)
3567     (unwind-protect
3568         (progn
3569           (let ((case-fold-search t))
3570             (save-restriction
3571               (message-narrow-to-headers)
3572               (setq resend-to-addresses (message-fetch-field "resent-to")))
3573             ;; Change header-delimiter to be what sendmail expects.
3574             (goto-char (point-min))
3575             (re-search-forward
3576              (concat "^" (regexp-quote mail-header-separator) "\n"))
3577             (replace-match "\n")
3578             (backward-char 1)
3579             (setq delimline (point-marker))
3580             (run-hooks 'message-send-mail-hook)
3581             ;; Insert an extra newline if we need it to work around
3582             ;; Sun's bug that swallows newlines.
3583             (goto-char (1+ delimline))
3584             (when (eval message-mailer-swallows-blank-line)
3585               (newline))
3586             (when message-interactive
3587               (save-excursion
3588                 (set-buffer errbuf)
3589                 (erase-buffer))))
3590           (let* ((default-directory "/")
3591                  (coding-system-for-write message-send-coding-system)
3592                  (cpr (apply
3593                        'call-process-region
3594                        (append
3595                         (list (point-min) (point-max)
3596                               (if (boundp 'sendmail-program)
3597                                   sendmail-program
3598                                 "/usr/lib/sendmail")
3599                               nil errbuf nil "-oi")
3600                         ;; Always specify who from,
3601                         ;; since some systems have broken sendmails.
3602                         ;; But some systems are more broken with -f, so
3603                         ;; we'll let users override this.
3604                         (if (null message-sendmail-f-is-evil)
3605                             (list "-f" (message-sendmail-envelope-from)))
3606                         ;; These mean "report errors by mail"
3607                         ;; and "deliver in background".
3608                         (if (null message-interactive) '("-oem" "-odb"))
3609                         ;; Get the addresses from the message
3610                         ;; unless this is a resend.
3611                         ;; We must not do that for a resend
3612                         ;; because we would find the original addresses.
3613                         ;; For a resend, include the specific addresses.
3614                         (if resend-to-addresses
3615                             (list resend-to-addresses)
3616                           '("-t"))))))
3617             (unless (or (null cpr) (zerop cpr))
3618               (error "Sending...failed with exit value %d" cpr)))
3619           (when message-interactive
3620             (save-excursion
3621               (set-buffer errbuf)
3622               (goto-char (point-min))
3623               (while (re-search-forward "\n\n* *" nil t)
3624                 (replace-match "; "))
3625               (if (not (zerop (buffer-size)))
3626                   (error "Sending...failed to %s"
3627                          (buffer-string))))))
3628       (when (bufferp errbuf)
3629         (kill-buffer errbuf)))))
3630
3631 (defun message-send-mail-with-qmail ()
3632   "Pass the prepared message buffer to qmail-inject.
3633 Refer to the documentation for the variable `message-send-mail-function'
3634 to find out how to use this."
3635   ;; replace the header delimiter with a blank line
3636   (goto-char (point-min))
3637   (re-search-forward
3638    (concat "^" (regexp-quote mail-header-separator) "\n"))
3639   (replace-match "\n")
3640   (run-hooks 'message-send-mail-hook)
3641   ;; send the message
3642   (case
3643       (let ((coding-system-for-write message-send-coding-system))
3644         (apply
3645          'call-process-region 1 (point-max) message-qmail-inject-program
3646          nil nil nil
3647          ;; qmail-inject's default behaviour is to look for addresses on the
3648          ;; command line; if there're none, it scans the headers.
3649          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
3650          ;;
3651          ;; in general, ALL of qmail-inject's defaults are perfect for simply
3652          ;; reading a formatted (i. e., at least a To: or Resent-To header)
3653          ;; message from stdin.
3654          ;;
3655          ;; qmail also has the advantage of not having been raped by
3656          ;; various vendors, so we don't have to allow for that, either --
3657          ;; compare this with message-send-mail-with-sendmail and weep
3658          ;; for sendmail's lost innocence.
3659          ;;
3660          ;; all this is way cool coz it lets us keep the arguments entirely
3661          ;; free for -inject-arguments -- a big win for the user and for us
3662          ;; since we don't have to play that double-guessing game and the user
3663          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
3664          (if (message-functionp message-qmail-inject-args)
3665              (funcall message-qmail-inject-args)
3666            message-qmail-inject-args)))
3667     ;; qmail-inject doesn't say anything on it's stdout/stderr,
3668     ;; we have to look at the retval instead
3669     (0 nil)
3670     (100 (error "qmail-inject reported permanent failure"))
3671     (111 (error "qmail-inject reported transient failure"))
3672     ;; should never happen
3673     (t   (error "qmail-inject reported unknown failure"))))
3674
3675 (defun message-send-mail-with-mh ()
3676   "Send the prepared message buffer with mh."
3677   (let ((mh-previous-window-config nil)
3678         (name (mh-new-draft-name)))
3679     (setq buffer-file-name name)
3680     ;; MH wants to generate these headers itself.
3681     (when message-mh-deletable-headers
3682       (let ((headers message-mh-deletable-headers))
3683         (while headers
3684           (goto-char (point-min))
3685           (and (re-search-forward
3686                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3687                (message-delete-line))
3688           (pop headers))))
3689     (run-hooks 'message-send-mail-hook)
3690     ;; Pass it on to mh.
3691     (mh-send-letter)))
3692
3693 (defun message-smtpmail-send-it ()
3694   "Send the prepared message buffer with `smtpmail-send-it'.
3695 This only differs from `smtpmail-send-it' that this command evaluates
3696 `message-send-mail-hook' just before sending a message.  It is useful
3697 if your ISP requires the POP-before-SMTP authentication.  See the
3698 documentation for the function `mail-source-touch-pop'."
3699   (run-hooks 'message-send-mail-hook)
3700   (smtpmail-send-it))
3701
3702 (defun message-canlock-generate ()
3703   "Return a string that is non-trival to guess.
3704 Do not use this for anything important, it is cryptographically weak."
3705   (let (sha1-maximum-internal-length)
3706     (sha1 (concat (message-unique-id)
3707                   (format "%x%x%x" (random) (random t) (random))
3708                   (prin1-to-string (recent-keys))
3709                   (prin1-to-string (garbage-collect))))))
3710
3711 (defun message-canlock-password ()
3712   "The password used by message for cancel locks.
3713 This is the value of `canlock-password', if that option is non-nil.
3714 Otherwise, generate and save a value for `canlock-password' first."
3715   (unless canlock-password
3716     (customize-save-variable 'canlock-password (message-canlock-generate))
3717     (setq canlock-password-for-verify canlock-password))
3718   canlock-password)
3719
3720 (defun message-insert-canlock ()
3721   (when message-insert-canlock
3722     (message-canlock-password)
3723     (canlock-insert-header)))
3724
3725 (defun message-send-news (&optional arg)
3726   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
3727          (case-fold-search nil)
3728          (method (if (message-functionp message-post-method)
3729                      (funcall message-post-method arg)
3730                    message-post-method))
3731          (newsgroups-field (save-restriction
3732                             (message-narrow-to-headers-or-head)
3733                             (message-fetch-field "Newsgroups")))
3734          (followup-field (save-restriction
3735                            (message-narrow-to-headers-or-head)
3736                            (message-fetch-field "Followup-To")))
3737          ;; BUG: We really need to get the charset for each name in the
3738          ;; Newsgroups and Followup-To lines to allow crossposting
3739          ;; between group namess with incompatible character sets.
3740          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
3741          (group-field-charset
3742           (gnus-group-name-charset method newsgroups-field))
3743          (followup-field-charset
3744           (gnus-group-name-charset method (or followup-field "")))
3745          (rfc2047-header-encoding-alist
3746           (append (when group-field-charset
3747                     (list (cons "Newsgroups" group-field-charset)))
3748                   (when followup-field-charset
3749                     (list (cons "Followup-To" followup-field-charset)))
3750                   rfc2047-header-encoding-alist))
3751          (messbuf (current-buffer))
3752          (message-syntax-checks
3753           (if (and arg
3754                    (listp message-syntax-checks))
3755               (cons '(existing-newsgroups . disabled)
3756                     message-syntax-checks)
3757             message-syntax-checks))
3758          (message-this-is-news t)
3759          (message-posting-charset
3760           (gnus-setup-posting-charset newsgroups-field))
3761          result)
3762     (if (not (message-check-news-body-syntax))
3763         nil
3764       (save-restriction
3765         (message-narrow-to-headers)
3766         ;; Insert some headers.
3767         (message-generate-headers message-required-news-headers)
3768         (message-insert-canlock)
3769         ;; Let the user do all of the above.
3770         (run-hooks 'message-header-hook))
3771       ;; Note: This check will be disabled by the ".*" default value for
3772       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
3773       (when (and group-field-charset
3774                  (listp message-syntax-checks))
3775         (setq message-syntax-checks
3776               (cons '(valid-newsgroups . disabled)
3777                     message-syntax-checks)))
3778       (message-cleanup-headers)
3779       (if (not (let ((message-post-method method))
3780                  (message-check-news-syntax)))
3781           nil
3782         (unwind-protect
3783             (save-excursion
3784               (set-buffer tembuf)
3785               (buffer-disable-undo)
3786               (erase-buffer)
3787               ;; Avoid copying text props (except hard newlines).
3788               (insert
3789                (with-current-buffer messbuf
3790                  (mml-buffer-substring-no-properties-except-hard-newlines
3791                   (point-min) (point-max))))
3792               (message-encode-message-body)
3793               ;; Remove some headers.
3794               (save-restriction
3795                 (message-narrow-to-headers)
3796                 ;; We (re)generate the Lines header.
3797                 (when (memq 'Lines message-required-mail-headers)
3798                   (message-generate-headers '(Lines)))
3799                 ;; Remove some headers.
3800                 (message-remove-header message-ignored-news-headers t)
3801                 (let ((mail-parse-charset message-default-charset))
3802                   (mail-encode-encoded-word-buffer)))
3803               (goto-char (point-max))
3804               ;; require one newline at the end.
3805               (or (= (preceding-char) ?\n)
3806                   (insert ?\n))
3807               (let ((case-fold-search t))
3808                 ;; Remove the delimiter.
3809                 (goto-char (point-min))
3810                 (re-search-forward
3811                  (concat "^" (regexp-quote mail-header-separator) "\n"))
3812                 (replace-match "\n")
3813                 (backward-char 1))
3814               (run-hooks 'message-send-news-hook)
3815               (gnus-open-server method)
3816               (message "Sending news via %s..." (gnus-server-string method))
3817               (setq result (let ((mail-header-separator ""))
3818                              (gnus-request-post method))))
3819           (kill-buffer tembuf))
3820         (set-buffer messbuf)
3821         (if result
3822             (push 'news message-sent-message-via)
3823           (message "Couldn't send message via news: %s"
3824                    (nnheader-get-report (car method)))
3825           nil)))))
3826
3827 ;;;
3828 ;;; Header generation & syntax checking.
3829 ;;;
3830
3831 (defun message-check-element (type)
3832   "Return non-nil if this TYPE is not to be checked."
3833   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
3834       t
3835     (let ((able (assq type message-syntax-checks)))
3836       (and (consp able)
3837            (eq (cdr able) 'disabled)))))
3838
3839 (defun message-check-news-syntax ()
3840   "Check the syntax of the message."
3841   (save-excursion
3842     (save-restriction
3843       (widen)
3844       ;; We narrow to the headers and check them first.
3845       (save-excursion
3846         (save-restriction
3847           (message-narrow-to-headers)
3848           (message-check-news-header-syntax))))))
3849
3850 (defun message-check-news-header-syntax ()
3851   (and
3852    ;; Check Newsgroups header.
3853    (message-check 'newsgroups
3854      (let ((group (message-fetch-field "newsgroups")))
3855        (or
3856         (and group
3857              (not (string-match "\\`[ \t]*\\'" group)))
3858         (ignore
3859          (message
3860           "The newsgroups field is empty or missing.  Posting is denied.")))))
3861    ;; Check the Subject header.
3862    (message-check 'subject
3863      (let* ((case-fold-search t)
3864             (subject (message-fetch-field "subject")))
3865        (or
3866         (and subject
3867              (not (string-match "\\`[ \t]*\\'" subject)))
3868         (ignore
3869          (message
3870           "The subject field is empty or missing.  Posting is denied.")))))
3871    ;; Check for commands in Subject.
3872    (message-check 'subject-cmsg
3873      (if (string-match "^cmsg " (message-fetch-field "subject"))
3874          (y-or-n-p
3875           "The control code \"cmsg\" is in the subject.  Really post? ")
3876        t))
3877    ;; Check long header lines.
3878    (message-check 'long-header-lines
3879      (let ((start (point))
3880            (header nil)
3881            (length 0)
3882            found)
3883        (while (and (not found)
3884                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
3885          (if (> (- (point) (match-beginning 0)) 998)
3886              (setq found t
3887                    length (- (point) (match-beginning 0)))
3888            (setq header (match-string-no-properties 1)))
3889          (setq start (match-beginning 0))
3890          (forward-line 1))
3891        (if found
3892            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
3893                              header length))
3894          t)))
3895    ;; Check for multiple identical headers.
3896    (message-check 'multiple-headers
3897      (let (found)
3898        (while (and (not found)
3899                    (re-search-forward "^[^ \t:]+: " nil t))
3900          (save-excursion
3901            (or (re-search-forward
3902                 (concat "^"
3903                         (regexp-quote
3904                          (setq found
3905                                (buffer-substring
3906                                 (match-beginning 0) (- (match-end 0) 2))))
3907                         ":")
3908                 nil t)
3909                (setq found nil))))
3910        (if found
3911            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
3912          t)))
3913    ;; Check for Version and Sendsys.
3914    (message-check 'sendsys
3915      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
3916          (y-or-n-p
3917           (format "The article contains a %s command.  Really post? "
3918                   (buffer-substring (match-beginning 0)
3919                                     (1- (match-end 0)))))
3920        t))
3921    ;; See whether we can shorten Followup-To.
3922    (message-check 'shorten-followup-to
3923      (let ((newsgroups (message-fetch-field "newsgroups"))
3924            (followup-to (message-fetch-field "followup-to"))
3925            to)
3926        (when (and newsgroups
3927                   (string-match "," newsgroups)
3928                   (not followup-to)
3929                   (not
3930                    (zerop
3931                     (length
3932                      (setq to (completing-read
3933                                "Followups to (default: no Followup-To header) "
3934                                (mapcar #'list
3935                                        (cons "poster"
3936                                              (message-tokenize-header
3937                                               newsgroups)))))))))
3938          (goto-char (point-min))
3939          (insert "Followup-To: " to "\n"))
3940        t))
3941    ;; Check "Shoot me".
3942    (message-check 'shoot
3943      (if (re-search-forward
3944           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
3945          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
3946        t))
3947    ;; Check for Approved.
3948    (message-check 'approved
3949      (if (re-search-forward "^Approved:" nil t)
3950          (y-or-n-p "The article contains an Approved header.  Really post? ")
3951        t))
3952    ;; Check the Message-ID header.
3953    (message-check 'message-id
3954      (let* ((case-fold-search t)
3955             (message-id (message-fetch-field "message-id" t)))
3956        (or (not message-id)
3957            ;; Is there an @ in the ID?
3958            (and (string-match "@" message-id)
3959                 ;; Is there a dot in the ID?
3960                 (string-match "@[^.]*\\." message-id)
3961                 ;; Does the ID end with a dot?
3962                 (not (string-match "\\.>" message-id)))
3963            (y-or-n-p
3964             (format "The Message-ID looks strange: \"%s\".  Really post? "
3965                     message-id)))))
3966    ;; Check the Newsgroups & Followup-To headers.
3967    (message-check 'existing-newsgroups
3968      (let* ((case-fold-search t)
3969             (newsgroups (message-fetch-field "newsgroups"))
3970             (followup-to (message-fetch-field "followup-to"))
3971             (groups (message-tokenize-header
3972                      (if followup-to
3973                          (concat newsgroups "," followup-to)
3974                        newsgroups)))
3975             (post-method (if (message-functionp message-post-method)
3976                              (funcall message-post-method)
3977                            message-post-method))
3978             ;; KLUDGE to handle nnvirtual groups.  Doing this right
3979             ;; would probably involve a new nnoo function.
3980             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
3981             (method (if (and (consp post-method)
3982                              (eq (car post-method) 'nnvirtual)
3983                              gnus-message-group-art)
3984                         (let ((group (car (nnvirtual-find-group-art
3985                                            (car gnus-message-group-art)
3986                                            (cdr gnus-message-group-art)))))
3987                           (gnus-find-method-for-group group))
3988                       post-method))
3989             (known-groups
3990              (mapcar (lambda (n)
3991                        (gnus-group-name-decode
3992                         (gnus-group-real-name n)
3993                         (gnus-group-name-charset method n)))
3994                      (gnus-groups-from-server method)))
3995             errors)
3996        (while groups
3997          (when (and (not (equal (car groups) "poster"))
3998                     (not (member (car groups) known-groups))
3999                     (not (member (car groups) errors)))
4000            (push (car groups) errors))
4001          (pop groups))
4002        (cond
4003         ;; Gnus is not running.
4004         ((or (not (and (boundp 'gnus-active-hashtb)
4005                        gnus-active-hashtb))
4006              (not (boundp 'gnus-read-active-file)))
4007          t)
4008         ;; We don't have all the group names.
4009         ((and (or (not gnus-read-active-file)
4010                   (eq gnus-read-active-file 'some))
4011               errors)
4012          (y-or-n-p
4013           (format
4014            "Really use %s possibly unknown group%s: %s? "
4015            (if (= (length errors) 1) "this" "these")
4016            (if (= (length errors) 1) "" "s")
4017            (mapconcat 'identity errors ", "))))
4018         ;; There were no errors.
4019         ((not errors)
4020          t)
4021         ;; There are unknown groups.
4022         (t
4023          (y-or-n-p
4024           (format
4025            "Really post to %s unknown group%s: %s? "
4026            (if (= (length errors) 1) "this" "these")
4027            (if (= (length errors) 1) "" "s")
4028            (mapconcat 'identity errors ", ")))))))
4029    ;; Check continuation headers.
4030    (message-check 'continuation-headers
4031      (goto-char (point-min))
4032      (let ((do-posting t))
4033        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4034          (if (y-or-n-p "Fix continuation lines? ")
4035              (progn
4036                (goto-char (match-beginning 0))
4037                (insert " "))
4038            (unless (y-or-n-p "Send anyway? ")
4039              (setq do-posting nil))))
4040        do-posting))
4041    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4042    (message-check 'valid-newsgroups
4043      (let ((case-fold-search t)
4044            (headers '("Newsgroups" "Followup-To"))
4045            header error)
4046        (while (and headers (not error))
4047          (when (setq header (mail-fetch-field (car headers)))
4048            (if (or
4049                 (not
4050                  (string-match
4051                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4052                   header))
4053                 (memq
4054                  nil (mapcar
4055                       (lambda (g)
4056                         (not (string-match "\\.\\'\\|\\.\\." g)))
4057                       (message-tokenize-header header ","))))
4058                (setq error t)))
4059          (unless error
4060            (pop headers)))
4061        (if (not error)
4062            t
4063          (y-or-n-p
4064           (format "The %s header looks odd: \"%s\".  Really post? "
4065                   (car headers) header)))))
4066    (message-check 'repeated-newsgroups
4067      (let ((case-fold-search t)
4068            (headers '("Newsgroups" "Followup-To"))
4069            header error groups group)
4070        (while (and headers
4071                    (not error))
4072          (when (setq header (mail-fetch-field (pop headers)))
4073            (setq groups (message-tokenize-header header ","))
4074            (while (setq group (pop groups))
4075              (when (member group groups)
4076                (setq error group
4077                      groups nil)))))
4078        (if (not error)
4079            t
4080          (y-or-n-p
4081           (format "Group %s is repeated in headers.  Really post? " error)))))
4082    ;; Check the From header.
4083    (message-check 'from
4084      (let* ((case-fold-search t)
4085             (from (message-fetch-field "from"))
4086             ad)
4087        (cond
4088         ((not from)
4089          (message "There is no From line.  Posting is denied.")
4090          nil)
4091         ((or (not (string-match
4092                    "@[^\\.]*\\."
4093                    (setq ad (nth 1 (mail-extract-address-components
4094                                     from))))) ;larsi@ifi
4095              (string-match "\\.\\." ad) ;larsi@ifi..uio
4096              (string-match "@\\." ad)   ;larsi@.ifi.uio
4097              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4098              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4099              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4100          (message
4101           "Denied posting -- the From looks strange: \"%s\"." from)
4102          nil)
4103         ((let ((addresses (rfc822-addresses from)))
4104            (while (and addresses
4105                        (not (eq (string-to-char (car addresses)) ?\()))
4106              (setq addresses (cdr addresses)))
4107            addresses)
4108          (message
4109           "Denied posting -- bad From address: \"%s\"." from)
4110          nil)
4111         (t t))))
4112    ;; Check the Reply-To header.
4113    (message-check 'reply-to
4114      (let* ((case-fold-search t)
4115             (reply-to (message-fetch-field "reply-to"))
4116             ad)
4117        (cond
4118         ((not reply-to)
4119          t)
4120         ((string-match "," reply-to)
4121          (y-or-n-p
4122           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4123                   reply-to)))
4124         ((or (not (string-match
4125                    "@[^\\.]*\\."
4126                    (setq ad (nth 1 (mail-extract-address-components
4127                                     reply-to))))) ;larsi@ifi
4128              (string-match "\\.\\." ad) ;larsi@ifi..uio
4129              (string-match "@\\." ad)   ;larsi@.ifi.uio
4130              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4131              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4132              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
4133          (y-or-n-p
4134           (format
4135            "The Reply-To looks strange: \"%s\". Really post? "
4136            reply-to)))
4137         (t t))))))
4138
4139 (defun message-check-news-body-syntax ()
4140   (and
4141    ;; Check for long lines.
4142    (message-check 'long-lines
4143      (goto-char (point-min))
4144      (re-search-forward
4145       (concat "^" (regexp-quote mail-header-separator) "$"))
4146      (forward-line 1)
4147      (while (and
4148              (or (looking-at
4149                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
4150                  (let ((p (point)))
4151                    (end-of-line)
4152                    (< (- (point) p) 80)))
4153              (zerop (forward-line 1))))
4154      (or (bolp)
4155          (eobp)
4156          (y-or-n-p
4157           "You have lines longer than 79 characters.  Really post? ")))
4158    ;; Check whether the article is empty.
4159    (message-check 'empty
4160      (goto-char (point-min))
4161      (re-search-forward
4162       (concat "^" (regexp-quote mail-header-separator) "$"))
4163      (forward-line 1)
4164      (let ((b (point)))
4165        (goto-char (point-max))
4166        (re-search-backward message-signature-separator nil t)
4167        (beginning-of-line)
4168        (or (re-search-backward "[^ \n\t]" b t)
4169            (if (message-gnksa-enable-p 'empty-article)
4170                (y-or-n-p "Empty article.  Really post? ")
4171              (message "Denied posting -- Empty article.")
4172              nil))))
4173    ;; Check for control characters.
4174    (message-check 'control-chars
4175      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
4176          (y-or-n-p
4177           "The article contains control characters.  Really post? ")
4178        t))
4179    ;; Check excessive size.
4180    (message-check 'size
4181      (if (> (buffer-size) 60000)
4182          (y-or-n-p
4183           (format "The article is %d octets long.  Really post? "
4184                   (buffer-size)))
4185        t))
4186    ;; Check whether any new text has been added.
4187    (message-check 'new-text
4188      (or
4189       (not message-checksum)
4190       (not (eq (message-checksum) message-checksum))
4191       (if (message-gnksa-enable-p 'quoted-text-only)
4192           (y-or-n-p
4193            "It looks like no new text has been added.  Really post? ")
4194         (message "Denied posting -- no new text has been added.")
4195         nil)))
4196    ;; Check the length of the signature.
4197    (message-check 'signature
4198      (goto-char (point-max))
4199      (if (> (count-lines (point) (point-max)) 5)
4200          (y-or-n-p
4201           (format
4202            "Your .sig is %d lines; it should be max 4.  Really post? "
4203            (1- (count-lines (point) (point-max)))))
4204        t))
4205    ;; Ensure that text follows last quoted portion.
4206    (message-check 'quoting-style
4207      (goto-char (point-max))
4208      (let ((no-problem t))
4209        (when (search-backward-regexp "^>[^\n]*\n" nil t)
4210          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
4211        (if no-problem
4212            t
4213          (if (message-gnksa-enable-p 'quoted-text-only)
4214              (y-or-n-p "Your text should follow quoted text.  Really post? ")
4215            ;; Ensure that
4216            (goto-char (point-min))
4217            (re-search-forward
4218             (concat "^" (regexp-quote mail-header-separator) "$"))
4219            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
4220                (y-or-n-p "Your text should follow quoted text.  Really post? ")
4221              (message "Denied posting -- only quoted text.")
4222              nil)))))))
4223
4224 (defun message-checksum ()
4225   "Return a \"checksum\" for the current buffer."
4226   (let ((sum 0))
4227     (save-excursion
4228       (goto-char (point-min))
4229       (re-search-forward
4230        (concat "^" (regexp-quote mail-header-separator) "$"))
4231       (while (not (eobp))
4232         (when (not (looking-at "[ \t\n]"))
4233           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
4234                             (char-after))))
4235         (forward-char 1)))
4236     sum))
4237
4238 (defun message-do-fcc ()
4239   "Process Fcc headers in the current buffer."
4240   (let ((case-fold-search t)
4241         (buf (current-buffer))
4242         list file
4243         (mml-externalize-attachments message-fcc-externalize-attachments))
4244     (save-excursion
4245       (save-restriction
4246         (message-narrow-to-headers)
4247         (setq file (message-fetch-field "fcc" t)))
4248       (when file
4249         (set-buffer (get-buffer-create " *message temp*"))
4250         (erase-buffer)
4251         (insert-buffer-substring buf)
4252         (message-encode-message-body)
4253         (save-restriction
4254           (message-narrow-to-headers)
4255           (while (setq file (message-fetch-field "fcc" t))
4256             (push file list)
4257             (message-remove-header "fcc" nil t))
4258           (let ((mail-parse-charset message-default-charset)
4259                 (rfc2047-header-encoding-alist
4260                  (cons '("Newsgroups" . default)
4261                        rfc2047-header-encoding-alist)))
4262             (mail-encode-encoded-word-buffer)))
4263         (goto-char (point-min))
4264         (when (re-search-forward
4265                (concat "^" (regexp-quote mail-header-separator) "$")
4266                nil t)
4267           (replace-match "" t t ))
4268         ;; Process FCC operations.
4269         (while list
4270           (setq file (pop list))
4271           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
4272               ;; Pipe the article to the program in question.
4273               (call-process-region (point-min) (point-max) shell-file-name
4274                                    nil nil nil shell-command-switch
4275                                    (match-string 1 file))
4276             ;; Save the article.
4277             (setq file (expand-file-name file))
4278             (unless (file-exists-p (file-name-directory file))
4279               (make-directory (file-name-directory file) t))
4280             (if (and message-fcc-handler-function
4281                      (not (eq message-fcc-handler-function 'rmail-output)))
4282                 (funcall message-fcc-handler-function file)
4283               (if (and (file-readable-p file) (mail-file-babyl-p file))
4284                   (rmail-output file 1 nil t)
4285                 (let ((mail-use-rfc822 t))
4286                   (rmail-output file 1 t t))))))
4287         (kill-buffer (current-buffer))))))
4288
4289 (defun message-output (filename)
4290   "Append this article to Unix/babyl mail file FILENAME."
4291   (if (and (file-readable-p filename)
4292            (mail-file-babyl-p filename))
4293       (gnus-output-to-rmail filename t)
4294     (gnus-output-to-mail filename t)))
4295
4296 (defun message-cleanup-headers ()
4297   "Do various automatic cleanups of the headers."
4298   ;; Remove empty lines in the header.
4299   (save-restriction
4300     (message-narrow-to-headers)
4301     ;; Remove blank lines.
4302     (while (re-search-forward "^[ \t]*\n" nil t)
4303       (replace-match "" t t))
4304
4305     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
4306     ;; spaces to comma and eliminate spaces around commas.  Eliminate
4307     ;; embedded line breaks.
4308     (goto-char (point-min))
4309     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
4310       (save-restriction
4311         (narrow-to-region
4312          (point)
4313          (if (re-search-forward "^[^ \t]" nil t)
4314              (match-beginning 0)
4315            (forward-line 1)
4316            (point)))
4317         (goto-char (point-min))
4318         (while (re-search-forward "\n[ \t]+" nil t)
4319           (replace-match " " t t))     ;No line breaks (too confusing)
4320         (goto-char (point-min))
4321         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
4322           (replace-match "," t t))
4323         (goto-char (point-min))
4324         ;; Remove trailing commas.
4325         (when (re-search-forward ",+$" nil t)
4326           (replace-match "" t t))))))
4327
4328 (defun message-make-date (&optional now)
4329   "Make a valid data header.
4330 If NOW, use that time instead."
4331   (let* ((now (or now (current-time)))
4332          (zone (nth 8 (decode-time now)))
4333          (sign "+"))
4334     (when (< zone 0)
4335       (setq sign "-")
4336       (setq zone (- zone)))
4337     (concat
4338      ;; The day name of the %a spec is locale-specific.  Pfff.
4339      (format "%s, " (capitalize (car (rassoc (nth 6 (decode-time now))
4340                                              parse-time-weekdays))))
4341      (format-time-string "%d" now)
4342      ;; The month name of the %b spec is locale-specific.  Pfff.
4343      (format " %s "
4344              (capitalize (car (rassoc (nth 4 (decode-time now))
4345                                       parse-time-months))))
4346      (format-time-string "%Y %H:%M:%S " now)
4347      ;; We do all of this because XEmacs doesn't have the %z spec.
4348      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
4349
4350 (defun message-make-message-id ()
4351   "Make a unique Message-ID."
4352   (concat "<" (message-unique-id)
4353           (let ((psubject (save-excursion (message-fetch-field "subject")))
4354                 (psupersedes
4355                  (save-excursion (message-fetch-field "supersedes"))))
4356             (if (or
4357                  (and message-reply-headers
4358                       (mail-header-references message-reply-headers)
4359                       (mail-header-subject message-reply-headers)
4360                       psubject
4361                       (not (string=
4362                             (message-strip-subject-re
4363                              (mail-header-subject message-reply-headers))
4364                             (message-strip-subject-re psubject))))
4365                  (and psupersedes
4366                       (string-match "_-_@" psupersedes)))
4367                 "_-_" ""))
4368           "@" (message-make-fqdn) ">"))
4369
4370 (defvar message-unique-id-char nil)
4371
4372 ;; If you ever change this function, make sure the new version
4373 ;; cannot generate IDs that the old version could.
4374 ;; You might for example insert a "." somewhere (not next to another dot
4375 ;; or string boundary), or modify the "fsf" string.
4376 (defun message-unique-id ()
4377   ;; Don't use microseconds from (current-time), they may be unsupported.
4378   ;; Instead we use this randomly inited counter.
4379   (setq message-unique-id-char
4380         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
4381            ;; (current-time) returns 16-bit ints,
4382            ;; and 2^16*25 just fits into 4 digits i base 36.
4383            (* 25 25)))
4384   (let ((tm (current-time)))
4385     (concat
4386      (if (memq system-type '(ms-dos emx vax-vms))
4387          (let ((user (downcase (user-login-name))))
4388            (while (string-match "[^a-z0-9_]" user)
4389              (aset user (match-beginning 0) ?_))
4390            user)
4391        (message-number-base36 (user-uid) -1))
4392      (message-number-base36 (+ (car tm)
4393                                (lsh (% message-unique-id-char 25) 16)) 4)
4394      (message-number-base36 (+ (nth 1 tm)
4395                                (lsh (/ message-unique-id-char 25) 16)) 4)
4396      ;; Append a given name, because while the generated ID is unique
4397      ;; to this newsreader, other newsreaders might otherwise generate
4398      ;; the same ID via another algorithm.
4399      ".fsf")))
4400
4401 (defun message-number-base36 (num len)
4402   (if (if (< len 0)
4403           (<= num 0)
4404         (= len 0))
4405       ""
4406     (concat (message-number-base36 (/ num 36) (1- len))
4407             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
4408                                   (% num 36))))))
4409
4410 (defun message-make-organization ()
4411   "Make an Organization header."
4412   (let* ((organization
4413           (when message-user-organization
4414             (if (message-functionp message-user-organization)
4415                 (funcall message-user-organization)
4416               message-user-organization))))
4417     (with-temp-buffer
4418       (mm-enable-multibyte)
4419       (cond ((stringp organization)
4420              (insert organization))
4421             ((and (eq t organization)
4422                   message-user-organization-file
4423                   (file-exists-p message-user-organization-file))
4424              (insert-file-contents message-user-organization-file)))
4425       (goto-char (point-min))
4426       (while (re-search-forward "[\t\n]+" nil t)
4427         (replace-match "" t t))
4428       (unless (zerop (buffer-size))
4429         (buffer-string)))))
4430
4431 (defun message-make-lines ()
4432   "Count the number of lines and return numeric string."
4433   (save-excursion
4434     (save-restriction
4435       (widen)
4436       (message-goto-body)
4437       (int-to-string (count-lines (point) (point-max))))))
4438
4439 (defun message-make-references ()
4440   "Return the References header for this message."
4441   (when message-reply-headers
4442     (let ((message-id (mail-header-message-id message-reply-headers))
4443           (references (mail-header-references message-reply-headers))
4444           new-references)
4445       (if (or references message-id)
4446           (concat (or references "") (and references " ")
4447                   (or message-id ""))
4448         nil))))
4449
4450 (defun message-make-in-reply-to ()
4451   "Return the In-Reply-To header for this message."
4452   (when message-reply-headers
4453     (let ((from (mail-header-from message-reply-headers))
4454           (date (mail-header-date message-reply-headers))
4455           (msg-id (mail-header-message-id message-reply-headers)))
4456       (when from
4457         (let ((name (mail-extract-address-components from)))
4458           (concat msg-id (if msg-id " (")
4459                   (or (car name)
4460                       (nth 1 name))
4461                   "'s message of \""
4462                   (if (or (not date) (string= date ""))
4463                       "(unknown date)" date)
4464                   "\"" (if msg-id ")")))))))
4465
4466 (defun message-make-distribution ()
4467   "Make a Distribution header."
4468   (let ((orig-distribution (message-fetch-reply-field "distribution")))
4469     (cond ((message-functionp message-distribution-function)
4470            (funcall message-distribution-function))
4471           (t orig-distribution))))
4472
4473 (defun message-make-expires ()
4474   "Return an Expires header based on `message-expires'."
4475   (let ((current (current-time))
4476         (future (* 1.0 message-expires 60 60 24)))
4477     ;; Add the future to current.
4478     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
4479     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
4480     (message-make-date current)))
4481
4482 (defun message-make-path ()
4483   "Return uucp path."
4484   (let ((login-name (user-login-name)))
4485     (cond ((null message-user-path)
4486            (concat (system-name) "!" login-name))
4487           ((stringp message-user-path)
4488            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
4489            (concat message-user-path "!" login-name))
4490           (t login-name))))
4491
4492 (defun message-make-from ()
4493   "Make a From header."
4494   (let* ((style message-from-style)
4495          (login (message-make-address))
4496          (fullname
4497           (or (and (boundp 'user-full-name)
4498                    user-full-name)
4499               (user-full-name))))
4500     (when (string= fullname "&")
4501       (setq fullname (user-login-name)))
4502     (with-temp-buffer
4503       (mm-enable-multibyte)
4504       (cond
4505        ((or (null style)
4506             (equal fullname ""))
4507         (insert login))
4508        ((or (eq style 'angles)
4509             (and (not (eq style 'parens))
4510                  ;; Use angles if no quoting is needed, or if parens would
4511                  ;; need quoting too.
4512                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
4513                      (let ((tmp (concat fullname nil)))
4514                        (while (string-match "([^()]*)" tmp)
4515                          (aset tmp (match-beginning 0) ?-)
4516                          (aset tmp (1- (match-end 0)) ?-))
4517                        (string-match "[\\()]" tmp)))))
4518         (insert fullname)
4519         (insert " <" login ">"))
4520        (t                               ; 'parens or default
4521         (insert login " (")
4522         (let ((fullname-start (point)))
4523           (insert fullname)
4524           (goto-char fullname-start)
4525           ;; RFC 822 says \ and nonmatching parentheses
4526           ;; must be escaped in comments.
4527           ;; Escape every instance of ()\ ...
4528           (while (re-search-forward "[()\\]" nil 1)
4529             (replace-match "\\\\\\&" t))
4530           ;; ... then undo escaping of matching parentheses,
4531           ;; including matching nested parentheses.
4532           (goto-char fullname-start)
4533           (while (re-search-forward
4534                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
4535                   nil 1)
4536             (replace-match "\\1(\\3)" t)
4537             (goto-char fullname-start)))
4538         (insert ")")))
4539       (buffer-string))))
4540
4541 (defun message-make-sender ()
4542   "Return the \"real\" user address.
4543 This function tries to ignore all user modifications, and
4544 give as trustworthy answer as possible."
4545   (concat (user-login-name) "@" (system-name)))
4546
4547 (defun message-make-address ()
4548   "Make the address of the user."
4549   (or (message-user-mail-address)
4550       (concat (user-login-name) "@" (message-make-domain))))
4551
4552 (defun message-user-mail-address ()
4553   "Return the pertinent part of `user-mail-address'."
4554   (when (and user-mail-address
4555              (string-match "@.*\\." user-mail-address))
4556     (if (string-match " " user-mail-address)
4557         (nth 1 (mail-extract-address-components user-mail-address))
4558       user-mail-address)))
4559
4560 (defun message-sendmail-envelope-from ()
4561   "Return the envelope from."
4562   (cond ((eq message-sendmail-envelope-from 'header)
4563          (nth 1 (mail-extract-address-components
4564                  (message-fetch-field "from"))))
4565         ((stringp message-sendmail-envelope-from)
4566          message-sendmail-envelope-from)
4567         (t
4568          (message-make-address))))
4569
4570 (defun message-make-fqdn ()
4571   "Return user's fully qualified domain name."
4572   (let* ((system-name (system-name))
4573          (user-mail (message-user-mail-address))
4574          (user-domain
4575           (if (and user-mail
4576                    (string-match "@\\(.*\\)\\'" user-mail))
4577               (match-string 1 user-mail))))
4578     (cond
4579      ((and message-user-fqdn
4580            (stringp message-user-fqdn)
4581            (string-match message-valid-fqdn-regexp message-user-fqdn)
4582            (not (string-match message-bogus-system-names message-user-fqdn)))
4583       message-user-fqdn)
4584      ;; `message-user-fqdn' seems to be valid
4585      ((and (string-match message-valid-fqdn-regexp system-name)
4586            (not (string-match message-bogus-system-names system-name)))
4587       ;; `system-name' returned the right result.
4588       system-name)
4589      ;; Try `mail-host-address'.
4590      ((and (boundp 'mail-host-address)
4591            (stringp mail-host-address)
4592            (string-match message-valid-fqdn-regexp mail-host-address)
4593            (not (string-match message-bogus-system-names mail-host-address)))
4594       mail-host-address)
4595      ;; We try `user-mail-address' as a backup.
4596      ((and user-domain
4597            (stringp user-domain)
4598            (string-match message-valid-fqdn-regexp user-domain)
4599            (not (string-match message-bogus-system-names user-domain)))
4600       user-domain)
4601      ;; Default to this bogus thing.
4602      (t
4603       (concat system-name
4604               ".i-did-not-set--mail-host-address--so-tickle-me")))))
4605
4606 (defun message-make-host-name ()
4607   "Return the name of the host."
4608   (let ((fqdn (message-make-fqdn)))
4609     (string-match "^[^.]+\\." fqdn)
4610     (substring fqdn 0 (1- (match-end 0)))))
4611
4612 (defun message-make-domain ()
4613   "Return the domain name."
4614   (or mail-host-address
4615       (message-make-fqdn)))
4616
4617 (defun message-to-list-only ()
4618   "Send a message to the list only.
4619 Remove all addresses but the list address from To and Cc headers."
4620   (interactive)
4621   (let ((listaddr (message-make-mail-followup-to t)))
4622     (when listaddr
4623       (save-excursion
4624         (message-remove-header "to")
4625         (message-remove-header "cc")
4626         (message-position-on-field "To" "X-Draft-From")
4627         (insert listaddr)))))
4628
4629 (defun message-make-mail-followup-to (&optional only-show-subscribed)
4630   "Return the Mail-Followup-To header.
4631 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
4632 subscribed address (and not the additional To and Cc header contents)."
4633   (let* ((case-fold-search t)
4634          (to (message-fetch-field "To"))
4635          (cc (message-fetch-field "cc"))
4636          (msg-recipients (concat to (and to cc ", ") cc))
4637          (recipients
4638           (mapcar 'mail-strip-quoted-names
4639                   (message-tokenize-header msg-recipients)))
4640          (file-regexps
4641           (if message-subscribed-address-file
4642               (let (begin end item re)
4643                 (save-excursion
4644                   (with-temp-buffer
4645                     (insert-file-contents message-subscribed-address-file)
4646                     (while (not (eobp))
4647                       (setq begin (point))
4648                       (forward-line 1)
4649                       (setq end (point))
4650                       (if (bolp) (setq end (1- end)))
4651                       (setq item (regexp-quote (buffer-substring begin end)))
4652                       (if re (setq re (concat re "\\|" item))
4653                         (setq re (concat "\\`\\(" item))))
4654                     (and re (list (concat re "\\)\\'"))))))))
4655          (mft-regexps (apply 'append message-subscribed-regexps
4656                              (mapcar 'regexp-quote
4657                                      message-subscribed-addresses)
4658                              file-regexps
4659                              (mapcar 'funcall
4660                                      message-subscribed-address-functions))))
4661     (save-match-data
4662       (let ((subscribed-lists nil)
4663             (list
4664              (loop for recipient in recipients
4665                when (loop for regexp in mft-regexps
4666                       when (string-match regexp recipient) return t)
4667                return recipient)))
4668         (when list
4669           (if only-show-subscribed
4670               list
4671             msg-recipients))))))
4672
4673 (defun message-idna-inside-rhs-p ()
4674   "Return t iff point is inside a RHS (heuristically).
4675 Only works properly if header contains mailbox-list or address-list.
4676 I.e., calling it on a Subject: header is useless."
4677   (save-restriction
4678     (narrow-to-region (save-excursion (or (re-search-backward "^[^ \t]" nil t)
4679                                           (point-min)))
4680                       (save-excursion (or (re-search-forward "^[^ \t]" nil t)
4681                                           (point-max))))
4682     (if (re-search-backward "[\\\n\r\t ]"
4683                             (save-excursion (search-backward "@" nil t)) t)
4684         ;; whitespace between @ and point
4685         nil
4686       (let ((dquote 1) (paren 1))
4687         (while (save-excursion (re-search-backward "[^\\]\"" nil t dquote))
4688           (incf dquote))
4689         (while (save-excursion (re-search-backward "[^\\]\(" nil t paren))
4690           (incf paren))
4691         (and (= (% dquote 2) 1) (= (% paren 2) 1))))))
4692
4693 (autoload 'idna-to-ascii "idna")
4694
4695 (defun message-idna-to-ascii-rhs-1 (header)
4696   "Interactively potentially IDNA encode domain names in HEADER."
4697   (let (rhs ace start startpos endpos ovl)
4698     (goto-char (point-min))
4699     (while (re-search-forward (concat "^" header) nil t)
4700       (while (re-search-forward "@\\([^ \t\r\n>]+\\)"
4701                                 (or (save-excursion
4702                                       (re-search-forward "^[^ \t]" nil t))
4703                                     (point-max))
4704                                 t)
4705         (setq rhs (match-string-no-properties 1)
4706               startpos (match-beginning 1)
4707               endpos (match-end 1))
4708         (when (save-match-data
4709                 (and (message-idna-inside-rhs-p)
4710                      (setq ace (idna-to-ascii rhs))
4711                      (not (string= rhs ace))
4712                      (if (eq message-use-idna 'ask)
4713                          (unwind-protect
4714                              (progn
4715                                (setq ovl (message-make-overlay startpos
4716                                                                endpos))
4717                                (message-overlay-put ovl 'face 'highlight)
4718                                (y-or-n-p
4719                                 (format "Replace with `%s'? " ace)))
4720                            (message "")
4721                            (message-delete-overlay ovl))
4722                        message-use-idna)))
4723           (replace-match (concat "@" ace)))))))
4724
4725 (defun message-idna-to-ascii-rhs ()
4726   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
4727 See `message-idna-encode'."
4728   (interactive)
4729   (when message-use-idna
4730     (save-excursion
4731       (save-restriction
4732         (message-narrow-to-head)
4733         (message-idna-to-ascii-rhs-1 "From")
4734         (message-idna-to-ascii-rhs-1 "To")
4735         (message-idna-to-ascii-rhs-1 "Cc")))))
4736
4737 (defun message-generate-headers (headers)
4738   "Prepare article HEADERS.
4739 Headers already prepared in the buffer are not modified."
4740   (setq headers (append headers message-required-headers))
4741   (save-restriction
4742     (message-narrow-to-headers)
4743     (let* ((Date (message-make-date))
4744            (Message-ID (message-make-message-id))
4745            (Organization (message-make-organization))
4746            (From (message-make-from))
4747            (Path (message-make-path))
4748            (Subject nil)
4749            (Newsgroups nil)
4750            (In-Reply-To (message-make-in-reply-to))
4751            (References (message-make-references))
4752            (To nil)
4753            (Distribution (message-make-distribution))
4754            (Lines (message-make-lines))
4755            (User-Agent message-newsreader)
4756            (Expires (message-make-expires))
4757            (case-fold-search t)
4758            (optionalp nil)
4759            header value elem)
4760       ;; First we remove any old generated headers.
4761       (let ((headers message-deletable-headers))
4762         (unless (buffer-modified-p)
4763           (setq headers (delq 'Message-ID (copy-sequence headers))))
4764         (while headers
4765           (goto-char (point-min))
4766           (and (re-search-forward
4767                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4768                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
4769                (message-delete-line))
4770           (pop headers)))
4771       ;; Go through all the required headers and see if they are in the
4772       ;; articles already.  If they are not, or are empty, they are
4773       ;; inserted automatically - except for Subject, Newsgroups and
4774       ;; Distribution.
4775       (while headers
4776         (goto-char (point-min))
4777         (setq elem (pop headers))
4778         (if (consp elem)
4779             (if (eq (car elem) 'optional)
4780                 (setq header (cdr elem)
4781                       optionalp t)
4782               (setq header (car elem)))
4783           (setq header elem))
4784         (when (or (not (re-search-forward
4785                         (concat "^"
4786                                 (regexp-quote
4787                                  (downcase
4788                                   (if (stringp header)
4789                                       header
4790                                     (symbol-name header))))
4791                                 ":")
4792                         nil t))
4793                   (progn
4794                     ;; The header was found.  We insert a space after the
4795                     ;; colon, if there is none.
4796                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
4797                     ;; Find out whether the header is empty.
4798                     (looking-at "[ \t]*\n[^ \t]")))
4799           ;; So we find out what value we should insert.
4800           (setq value
4801                 (cond
4802                  ((and (consp elem)
4803                        (eq (car elem) 'optional))
4804                   ;; This is an optional header.  If the cdr of this
4805                   ;; is something that is nil, then we do not insert
4806                   ;; this header.
4807                   (setq header (cdr elem))
4808                   (or (and (message-functionp (cdr elem))
4809                            (funcall (cdr elem)))
4810                       (and (boundp (cdr elem))
4811                            (symbol-value (cdr elem)))))
4812                  ((consp elem)
4813                   ;; The element is a cons.  Either the cdr is a
4814                   ;; string to be inserted verbatim, or it is a
4815                   ;; function, and we insert the value returned from
4816                   ;; this function.
4817                   (or (and (stringp (cdr elem))
4818                            (cdr elem))
4819                       (and (message-functionp (cdr elem))
4820                            (funcall (cdr elem)))))
4821                  ((and (boundp header)
4822                        (symbol-value header))
4823                   ;; The element is a symbol.  We insert the value
4824                   ;; of this symbol, if any.
4825                   (symbol-value header))
4826                  ((not (message-check-element header))
4827                   ;; We couldn't generate a value for this header,
4828                   ;; so we just ask the user.
4829                   (read-from-minibuffer
4830                    (format "Empty header for %s; enter value: " header)))))
4831           ;; Finally insert the header.
4832           (when (and value
4833                      (not (equal value "")))
4834             (save-excursion
4835               (if (bolp)
4836                   (progn
4837                     ;; This header didn't exist, so we insert it.
4838                     (goto-char (point-max))
4839                     (let ((formatter
4840                            (cdr (assq header message-header-format-alist))))
4841                       (if formatter
4842                           (funcall formatter header value)
4843                         (insert (if (stringp header)
4844                                     header (symbol-name header))
4845                                 ": " value))
4846                       ;; We check whether the value was ended by a
4847                       ;; newline.  If now, we insert one.
4848                       (unless (bolp)
4849                         (insert "\n"))
4850                       (forward-line -1)))
4851                 ;; The value of this header was empty, so we clear
4852                 ;; totally and insert the new value.
4853                 (delete-region (point) (gnus-point-at-eol))
4854                 ;; If the header is optional, and the header was
4855                 ;; empty, we con't insert it anyway.
4856                 (unless optionalp
4857                   (insert value)))
4858               ;; Add the deletable property to the headers that require it.
4859               (and (memq header message-deletable-headers)
4860                    (progn (beginning-of-line) (looking-at "[^:]+: "))
4861                    (add-text-properties
4862                     (point) (match-end 0)
4863                     '(message-deletable t face italic) (current-buffer)))))))
4864       ;; Insert new Sender if the From is strange.
4865       (let ((from (message-fetch-field "from"))
4866             (sender (message-fetch-field "sender"))
4867             (secure-sender (message-make-sender)))
4868         (when (and from
4869                    (not (message-check-element 'sender))
4870                    (not (string=
4871                          (downcase
4872                           (cadr (mail-extract-address-components from)))
4873                          (downcase secure-sender)))
4874                    (or (null sender)
4875                        (not
4876                         (string=
4877                          (downcase
4878                           (cadr (mail-extract-address-components sender)))
4879                          (downcase secure-sender)))))
4880           (goto-char (point-min))
4881           ;; Rename any old Sender headers to Original-Sender.
4882           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
4883             (beginning-of-line)
4884             (insert "Original-")
4885             (beginning-of-line))
4886           (when (or (message-news-p)
4887                     (string-match "@.+\\.." secure-sender))
4888             (insert "Sender: " secure-sender "\n"))))
4889       ;; Check for IDNA
4890       (message-idna-to-ascii-rhs))))
4891
4892 (defun message-insert-courtesy-copy ()
4893   "Insert a courtesy message in mail copies of combined messages."
4894   (let (newsgroups)
4895     (save-excursion
4896       (save-restriction
4897         (message-narrow-to-headers)
4898         (when (setq newsgroups (message-fetch-field "newsgroups"))
4899           (goto-char (point-max))
4900           (insert "Posted-To: " newsgroups "\n")))
4901       (forward-line 1)
4902       (when message-courtesy-message
4903         (cond
4904          ((string-match "%s" message-courtesy-message)
4905           (insert (format message-courtesy-message newsgroups)))
4906          (t
4907           (insert message-courtesy-message)))))))
4908
4909 ;;;
4910 ;;; Setting up a message buffer
4911 ;;;
4912
4913 (defun message-fill-address (header value)
4914   (save-restriction
4915     (narrow-to-region (point) (point))
4916     (insert (capitalize (symbol-name header))
4917             ": "
4918             (if (consp value) (car value) value)
4919             "\n")
4920     (narrow-to-region (point-min) (1- (point-max)))
4921     (let (quoted last)
4922       (goto-char (point-min))
4923       (while (not (eobp))
4924         (skip-chars-forward "^,\"" (point-max))
4925         (if (or (eq (char-after) ?,)
4926                 (eobp))
4927             (when (not quoted)
4928               (if (and (> (current-column) 78)
4929                        last)
4930                   (progn
4931                     (save-excursion
4932                       (goto-char last)
4933                       (insert "\n\t"))
4934                     (setq last (1+ (point))))
4935                 (setq last (1+ (point)))))
4936           (setq quoted (not quoted)))
4937         (unless (eobp)
4938           (forward-char 1))))
4939     (goto-char (point-max))
4940     (widen)
4941     (forward-line 1)))
4942
4943 (defun message-split-line ()
4944   "Split current line, moving portion beyond point vertically down.
4945 If the current line has `message-yank-prefix', insert it on the new line."
4946   (interactive "*")
4947   (condition-case nil
4948       (split-line message-yank-prefix) ;; Emacs 21.3.50+ supports arg.
4949     (error
4950      (split-line))))
4951      
4952
4953 (defun message-fill-header (header value)
4954   (let ((begin (point))
4955         (fill-column 78)
4956         (fill-prefix "\t"))
4957     (insert (capitalize (symbol-name header))
4958             ": "
4959             (if (consp value) (car value) value)
4960             "\n")
4961     (save-restriction
4962       (narrow-to-region begin (point))
4963       (fill-region-as-paragraph begin (point))
4964       ;; Tapdance around looong Message-IDs.
4965       (forward-line -1)
4966       (when (looking-at "[ \t]*$")
4967         (message-delete-line))
4968       (goto-char begin)
4969       (re-search-forward ":" nil t)
4970       (when (looking-at "\n[ \t]+")
4971         (replace-match " " t t))
4972       (goto-char (point-max)))))
4973
4974 (defun message-shorten-1 (list cut surplus)
4975   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
4976   (setcdr (nthcdr (- cut 2) list)
4977           (nthcdr (+ (- cut 2) surplus 1) list)))
4978
4979 (defun message-shorten-references (header references)
4980   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
4981 If folding is disallowed, also check that the REFERENCES are less
4982 than 988 characters long, and if they are not, trim them until they are."
4983   (let ((maxcount 21)
4984         (count 0)
4985         (cut 2)
4986         refs)
4987     (with-temp-buffer
4988       (insert references)
4989       (goto-char (point-min))
4990       ;; Cons a list of valid references.
4991       (while (re-search-forward "<[^>]+>" nil t)
4992         (push (match-string 0) refs))
4993       (setq refs (nreverse refs)
4994             count (length refs)))
4995
4996     ;; If the list has more than MAXCOUNT elements, trim it by
4997     ;; removing the CUTth element and the required number of
4998     ;; elements that follow.
4999     (when (> count maxcount)
5000       (let ((surplus (- count maxcount)))
5001         (message-shorten-1 refs cut surplus)
5002         (decf count surplus)))
5003
5004     ;; If folding is disallowed, make sure the total length (including
5005     ;; the spaces between) will be less than MAXSIZE characters.
5006     ;;
5007     ;; Only disallow folding for News messages. At this point the headers
5008     ;; have not been generated, thus we use message-this-is-news directly.
5009     (when (and message-this-is-news message-cater-to-broken-inn)
5010       (let ((maxsize 988)
5011             (totalsize (+ (apply #'+ (mapcar #'length refs))
5012                           (1- count)))
5013             (surplus 0)
5014             (ptr (nthcdr (1- cut) refs)))
5015         ;; Decide how many elements to cut off...
5016         (while (> totalsize maxsize)
5017           (decf totalsize (1+ (length (car ptr))))
5018           (incf surplus)
5019           (setq ptr (cdr ptr)))
5020         ;; ...and do it.
5021         (when (> surplus 0)
5022           (message-shorten-1 refs cut surplus))))
5023
5024     ;; Finally, collect the references back into a string and insert
5025     ;; it into the buffer.
5026     (let ((refstring (mapconcat #'identity refs " ")))
5027       (if (and message-this-is-news message-cater-to-broken-inn)
5028           (insert (capitalize (symbol-name header)) ": "
5029                   refstring "\n")
5030         (message-fill-header header refstring)))))
5031
5032 (defun message-position-point ()
5033   "Move point to where the user probably wants to find it."
5034   (message-narrow-to-headers)
5035   (cond
5036    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5037     (search-backward ":" )
5038     (widen)
5039     (forward-char 1)
5040     (if (eq (char-after) ? )
5041         (forward-char 1)
5042       (insert " ")))
5043    (t
5044     (goto-char (point-max))
5045     (widen)
5046     (forward-line 1)
5047     (unless (looking-at "$")
5048       (forward-line 2)))
5049    (sit-for 0)))
5050
5051 (defcustom message-beginning-of-line t
5052   "Whether C-a goes to beginning of header values."
5053   :group 'message-buffers
5054   :type 'boolean)
5055
5056 (defun message-beginning-of-line (&optional n)
5057   "Move point to beginning of header value or to beginning of line."
5058   (interactive "p")
5059   (let ((zrs 'zmacs-region-stays))
5060     (when (and (interactive-p) (boundp zrs))
5061       (set zrs t)))
5062   (if (and message-beginning-of-line
5063            (message-point-in-header-p))
5064       (let* ((here (point))
5065              (bol (progn (beginning-of-line n) (point)))
5066              (eol (gnus-point-at-eol))
5067              (eoh (re-search-forward ": *" eol t)))
5068         (if (or (not eoh) (equal here eoh))
5069             (goto-char bol)
5070           (goto-char eoh)))
5071     (beginning-of-line n)))
5072
5073 (defun message-buffer-name (type &optional to group)
5074   "Return a new (unique) buffer name based on TYPE and TO."
5075   (cond
5076    ;; Generate a new buffer name The Message Way.
5077    ((eq message-generate-new-buffers 'unique)
5078     (generate-new-buffer-name
5079      (concat "*" type
5080              (if to
5081                  (concat " to "
5082                          (or (car (mail-extract-address-components to))
5083                              to) "")
5084                "")
5085              (if (and group (not (string= group ""))) (concat " on " group) "")
5086              "*")))
5087    ;; Check whether `message-generate-new-buffers' is a function,
5088    ;; and if so, call it.
5089    ((message-functionp message-generate-new-buffers)
5090     (funcall message-generate-new-buffers type to group))
5091    ((eq message-generate-new-buffers 'unsent)
5092     (generate-new-buffer-name
5093      (concat "*unsent " type
5094              (if to
5095                  (concat " to "
5096                          (or (car (mail-extract-address-components to))
5097                              to) "")
5098                "")
5099              (if (and group (not (string= group ""))) (concat " on " group) "")
5100              "*")))
5101    ;; Use standard name.
5102    (t
5103     (format "*%s message*" type))))
5104
5105 (defun message-pop-to-buffer (name)
5106   "Pop to buffer NAME, and warn if it already exists and is modified."
5107   (let ((buffer (get-buffer name)))
5108     (if (and buffer
5109              (buffer-name buffer))
5110         (progn
5111           (set-buffer (pop-to-buffer buffer))
5112           (when (and (buffer-modified-p)
5113                      (not (y-or-n-p
5114                            "Message already being composed; erase? ")))
5115             (error "Message being composed")))
5116       (set-buffer (pop-to-buffer name)))
5117     (erase-buffer)
5118     (message-mode)))
5119
5120 (defun message-do-send-housekeeping ()
5121   "Kill old message buffers."
5122   ;; We might have sent this buffer already.  Delete it from the
5123   ;; list of buffers.
5124   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
5125   (while (and message-max-buffers
5126               message-buffer-list
5127               (>= (length message-buffer-list) message-max-buffers))
5128     ;; Kill the oldest buffer -- unless it has been changed.
5129     (let ((buffer (pop message-buffer-list)))
5130       (when (and (buffer-name buffer)
5131                  (not (buffer-modified-p buffer)))
5132         (kill-buffer buffer))))
5133   ;; Rename the buffer.
5134   (if message-send-rename-function
5135       (funcall message-send-rename-function)
5136     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
5137     (when (string-match
5138            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
5139            (buffer-name))
5140       (let ((name (match-string 2 (buffer-name)))
5141             to group)
5142         (if (not (or (null name)
5143                      (string-equal name "mail")
5144                      (string-equal name "posting")))
5145             (setq name (concat "*sent " name "*"))
5146           (message-narrow-to-headers)
5147           (setq to (message-fetch-field "to"))
5148           (setq group (message-fetch-field "newsgroups"))
5149           (widen)
5150           (setq name
5151                 (cond
5152                  (to (concat "*sent mail to "
5153                              (or (car (mail-extract-address-components to))
5154                                  to) "*"))
5155                  ((and group (not (string= group "")))
5156                   (concat "*sent posting on " group "*"))
5157                  (t "*sent mail*"))))
5158         (unless (string-equal name (buffer-name))
5159           (rename-buffer name t)))))
5160   ;; Push the current buffer onto the list.
5161   (when message-max-buffers
5162     (setq message-buffer-list
5163           (nconc message-buffer-list (list (current-buffer))))))
5164
5165 (defun message-mail-user-agent ()
5166   (let ((mua (cond
5167               ((not message-mail-user-agent) nil)
5168               ((eq message-mail-user-agent t) mail-user-agent)
5169               (t message-mail-user-agent))))
5170     (if (memq mua '(message-user-agent gnus-user-agent))
5171         nil
5172       mua)))
5173
5174 (defun message-setup (headers &optional replybuffer actions switch-function)
5175   (let ((mua (message-mail-user-agent))
5176         subject to field yank-action)
5177     (if (not (and message-this-is-mail mua))
5178         (message-setup-1 headers replybuffer actions)
5179       (if replybuffer
5180           (setq yank-action (list 'insert-buffer replybuffer)))
5181       (setq headers (copy-sequence headers))
5182       (setq field (assq 'Subject headers))
5183       (when field
5184         (setq subject (cdr field))
5185         (setq headers (delq field headers)))
5186       (setq field (assq 'To headers))
5187       (when field
5188         (setq to (cdr field))
5189         (setq headers (delq field headers)))
5190       (let ((mail-user-agent mua))
5191         (compose-mail to subject
5192                       (mapcar (lambda (item)
5193                                 (cons
5194                                  (format "%s" (car item))
5195                                  (cdr item)))
5196                               headers)
5197                       nil switch-function yank-action actions)))))
5198
5199 (defun message-headers-to-generate (headers included-headers excluded-headers)
5200   "Return a list that includes all headers from HEADERS.
5201 If INCLUDED-HEADERS is a list, just include those headers.  If if is
5202 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
5203 are not included."
5204   (let ((result nil)
5205         header-name)
5206     (dolist (header headers)
5207       (setq header-name (cond
5208                          ((and (consp header)
5209                                (eq (car header) 'optional))
5210                           ;; On the form (optional . Header)
5211                           (cdr header))
5212                          ((consp header)
5213                           ;; On the form (Header . function)
5214                           (car header))
5215                          (t
5216                           ;; Just a Header.
5217                           header)))
5218       (when (and (not (memq header-name excluded-headers))
5219                  (or (eq included-headers t)
5220                      (memq header-name included-headers)))
5221         (push header result)))
5222     (nreverse result)))
5223
5224 (defun message-setup-1 (headers &optional replybuffer actions)
5225   (dolist (action actions)
5226     (condition-case nil
5227         (add-to-list 'message-send-actions
5228                      `(apply ',(car action) ',(cdr action)))))
5229   (setq message-reply-buffer replybuffer)
5230   (goto-char (point-min))
5231   ;; Insert all the headers.
5232   (mail-header-format
5233    (let ((h headers)
5234          (alist message-header-format-alist))
5235      (while h
5236        (unless (assq (caar h) message-header-format-alist)
5237          (push (list (caar h)) alist))
5238        (pop h))
5239      alist)
5240    headers)
5241   (delete-region (point) (progn (forward-line -1) (point)))
5242   (when message-default-headers
5243     (insert message-default-headers)
5244     (or (bolp) (insert ?\n)))
5245   (put-text-property
5246    (point)
5247    (progn
5248      (insert mail-header-separator "\n")
5249      (1- (point)))
5250    'read-only nil)
5251   (forward-line -1)
5252   (when (message-news-p)
5253     (when message-default-news-headers
5254       (insert message-default-news-headers)
5255       (or (bolp) (insert ?\n)))
5256     (when message-generate-headers-first
5257       (message-generate-headers
5258        (message-headers-to-generate
5259         (append message-required-news-headers
5260                 message-required-headers)
5261         message-generate-headers-first
5262         '(Lines Subject)))))
5263   (when (message-mail-p)
5264     (when message-default-mail-headers
5265       (insert message-default-mail-headers)
5266       (or (bolp) (insert ?\n)))
5267     (save-restriction
5268       (message-narrow-to-headers)
5269       (if message-alternative-emails
5270           (message-use-alternative-email-as-from)))
5271     (when message-generate-headers-first
5272       (message-generate-headers
5273        (message-headers-to-generate
5274         (append message-required-mail-headers
5275                 message-required-headers)
5276         message-generate-headers-first
5277         '(Lines Subject)))))
5278   (run-hooks 'message-signature-setup-hook)
5279   (message-insert-signature)
5280   (save-restriction
5281     (message-narrow-to-headers)
5282     (run-hooks 'message-header-setup-hook))
5283   (set-buffer-modified-p nil)
5284   (setq buffer-undo-list nil)
5285   (run-hooks 'message-setup-hook)
5286   (message-position-point)
5287   (undo-boundary))
5288
5289 (defun message-set-auto-save-file-name ()
5290   "Associate the message buffer with a file in the drafts directory."
5291   (when message-auto-save-directory
5292     (unless (file-directory-p
5293              (directory-file-name message-auto-save-directory))
5294       (make-directory message-auto-save-directory t))
5295     (if (gnus-alive-p)
5296         (setq message-draft-article
5297               (nndraft-request-associate-buffer "drafts"))
5298       (setq buffer-file-name (expand-file-name
5299                               (if (memq system-type
5300                                         '(ms-dos ms-windows windows-nt
5301                                                  cygwin cygwin32 win32 w32
5302                                                  mswindows))
5303                                   "message"
5304                                 "*message*")
5305                               message-auto-save-directory))
5306       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
5307     (clear-visited-file-modtime)
5308     (setq buffer-file-coding-system message-draft-coding-system)))
5309
5310 (defun message-disassociate-draft ()
5311   "Disassociate the message buffer from the drafts directory."
5312   (when message-draft-article
5313     (nndraft-request-expire-articles
5314      (list message-draft-article) "drafts" nil t)))
5315
5316 (defun message-insert-headers ()
5317   "Generate the headers for the article."
5318   (interactive)
5319   (save-excursion
5320     (save-restriction
5321       (message-narrow-to-headers)
5322       (when (message-news-p)
5323         (message-generate-headers
5324          (delq 'Lines
5325                (delq 'Subject
5326                      (copy-sequence message-required-news-headers)))))
5327       (when (message-mail-p)
5328         (message-generate-headers
5329          (delq 'Lines
5330                (delq 'Subject
5331                      (copy-sequence message-required-mail-headers))))))))
5332
5333 \f
5334
5335 ;;;
5336 ;;; Commands for interfacing with message
5337 ;;;
5338
5339 ;;;###autoload
5340 (defun message-mail (&optional to subject
5341                                other-headers continue switch-function
5342                                yank-action send-actions)
5343   "Start editing a mail message to be sent.
5344 OTHER-HEADERS is an alist of header/value pairs."
5345   (interactive)
5346   (let ((message-this-is-mail t) replybuffer)
5347     (unless (message-mail-user-agent)
5348       (message-pop-to-buffer (message-buffer-name "mail" to)))
5349     ;; FIXME: message-mail should do something if YANK-ACTION is not
5350     ;; insert-buffer.
5351     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
5352          (setq replybuffer (nth 1 yank-action)))
5353     (message-setup
5354      (nconc
5355       `((To . ,(or to "")) (Subject . ,(or subject "")))
5356       (when other-headers other-headers))
5357      replybuffer send-actions)
5358     ;; FIXME: Should return nil if failure.
5359     t))
5360
5361 ;;;###autoload
5362 (defun message-news (&optional newsgroups subject)
5363   "Start editing a news article to be sent."
5364   (interactive)
5365   (let ((message-this-is-news t))
5366     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
5367     (message-setup `((Newsgroups . ,(or newsgroups ""))
5368                      (Subject . ,(or subject ""))))))
5369
5370 (defun message-get-reply-headers (wide &optional to-address address-headers)
5371   (let (follow-to mct never-mct to cc author mft recipients)
5372     ;; Find all relevant headers we need.
5373     (setq to (message-fetch-field "to")
5374           cc (message-fetch-field "cc")
5375           mct (message-fetch-field "mail-copies-to")
5376           author (or (message-fetch-field "mail-reply-to")
5377                      (message-fetch-field "reply-to")
5378                      (message-fetch-field "from")
5379                      "")
5380           mft (and message-use-mail-followup-to
5381                    (message-fetch-field "mail-followup-to")))
5382
5383     ;; Handle special values of Mail-Copies-To.
5384     (when mct
5385       (cond ((or (equal (downcase mct) "never")
5386                  (equal (downcase mct) "nobody"))
5387              (setq never-mct t)
5388              (setq mct nil))
5389             ((or (equal (downcase mct) "always")
5390                  (equal (downcase mct) "poster"))
5391              (setq mct author))))
5392
5393     (save-match-data
5394       ;; Build (textual) list of new recipient addresses.
5395       (cond
5396        ((not wide)
5397         (setq recipients (concat ", " author)))
5398        (address-headers
5399         (dolist (header address-headers)
5400           (let ((value (message-fetch-field header)))
5401             (when value
5402               (setq recipients (concat recipients ", " value))))))
5403        ((and mft
5404              (string-match "[^ \t,]" mft)
5405              (or (not (eq message-use-mail-followup-to 'ask))
5406                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
5407 You should normally obey the Mail-Followup-To: header.  In this
5408 article, it has the value of
5409
5410 " mft "
5411
5412 which directs your response to " (if (string-match "," mft)
5413                                      "the specified addresses"
5414                                    "that address only") ".
5415
5416 Most commonly, Mail-Followup-To is used by a mailing list poster to
5417 express that responses should be sent to just the list, and not the
5418 poster as well.
5419
5420 If a message is posted to several mailing lists, Mail-Followup-To may
5421 also be used to direct the following discussion to one list only,
5422 because discussions that are spread over several lists tend to be
5423 fragmented and very difficult to follow.
5424
5425 Also, some source/announcement lists are not intended for discussion;
5426 responses here are directed to other addresses.")))
5427         (setq recipients (concat ", " mft)))
5428        (to-address
5429         (setq recipients (concat ", " to-address))
5430         ;; If the author explicitly asked for a copy, we don't deny it to them.
5431         (if mct (setq recipients (concat recipients ", " mct))))
5432        (t
5433         (setq recipients (if never-mct "" (concat ", " author)))
5434         (if to  (setq recipients (concat recipients ", " to)))
5435         (if cc  (setq recipients (concat recipients ", " cc)))
5436         (if mct (setq recipients (concat recipients ", " mct)))))
5437       (if (>= (length recipients) 2)
5438           ;; Strip the leading ", ".
5439           (setq recipients (substring recipients 2)))
5440       ;; Squeeze whitespace.
5441       (while (string-match "[ \t][ \t]+" recipients)
5442         (setq recipients (replace-match " " t t recipients)))
5443       ;; Remove addresses that match `rmail-dont-reply-to-names'.
5444       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
5445         (setq recipients (rmail-dont-reply-to recipients)))
5446       ;; Perhaps "Mail-Copies-To: never" removed the only address?
5447       (if (string-equal recipients "")
5448           (setq recipients author))
5449       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
5450       (setq recipients
5451             (mapcar
5452              (lambda (addr)
5453                (cons (downcase (mail-strip-quoted-names addr)) addr))
5454              (message-tokenize-header recipients)))
5455       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
5456       (let ((s recipients))
5457         (while s
5458           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
5459
5460       ;; Remove hierarchical lists that are contained within each other,
5461       ;; if message-hierarchical-addresses is defined.
5462       (when message-hierarchical-addresses
5463         (let ((plain-addrs (mapcar 'car recipients))
5464               subaddrs recip)
5465           (while plain-addrs
5466             (setq subaddrs (assoc (car plain-addrs)
5467                                   message-hierarchical-addresses)
5468                   plain-addrs (cdr plain-addrs))
5469             (when subaddrs
5470               (setq subaddrs (cdr subaddrs))
5471               (while subaddrs
5472                 (setq recip (assoc (car subaddrs) recipients)
5473                       subaddrs (cdr subaddrs))
5474                 (if recip
5475                     (setq recipients (delq recip recipients))))))))
5476
5477       ;; Build the header alist.  Allow the user to be asked whether
5478       ;; or not to reply to all recipients in a wide reply.
5479       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
5480       (when (and recipients
5481                  (or (not message-wide-reply-confirm-recipients)
5482                      (y-or-n-p "Reply to all recipients? ")))
5483         (setq recipients (mapconcat
5484                           (lambda (addr) (cdr addr)) recipients ", "))
5485         (if (string-match "^ +" recipients)
5486             (setq recipients (substring recipients (match-end 0))))
5487         (push (cons 'Cc recipients) follow-to)))
5488     follow-to))
5489
5490 ;;;###autoload
5491 (defun message-reply (&optional to-address wide)
5492   "Start editing a reply to the article in the current buffer."
5493   (interactive)
5494   (require 'gnus-sum)                   ; for gnus-list-identifiers
5495   (let ((cur (current-buffer))
5496         from subject date reply-to to cc
5497         references message-id follow-to
5498         (inhibit-point-motion-hooks t)
5499         (message-this-is-mail t)
5500         gnus-warning)
5501     (save-restriction
5502       (message-narrow-to-head-1)
5503       ;; Allow customizations to have their say.
5504       (if (not wide)
5505           ;; This is a regular reply.
5506           (when (message-functionp message-reply-to-function)
5507             (save-excursion
5508               (setq follow-to (funcall message-reply-to-function))))
5509         ;; This is a followup.
5510         (when (message-functionp message-wide-reply-to-function)
5511           (save-excursion
5512             (setq follow-to
5513                   (funcall message-wide-reply-to-function)))))
5514       (setq message-id (message-fetch-field "message-id" t)
5515             references (message-fetch-field "references")
5516             date (message-fetch-field "date")
5517             from (message-fetch-field "from")
5518             subject (or (message-fetch-field "subject") "none"))
5519       (when gnus-list-identifiers
5520         (setq subject (message-strip-list-identifiers subject)))
5521       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5522       (when message-subject-trailing-was-query
5523         (setq subject (message-strip-subject-trailing-was subject)))
5524
5525       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5526                  (string-match "<[^>]+>" gnus-warning))
5527         (setq message-id (match-string 0 gnus-warning)))
5528
5529       (unless follow-to
5530         (setq follow-to (message-get-reply-headers wide to-address))))
5531
5532     (unless (message-mail-user-agent)
5533       (message-pop-to-buffer
5534        (message-buffer-name
5535         (if wide "wide reply" "reply") from
5536         (if wide to-address nil))))
5537
5538     (setq message-reply-headers
5539           (vector 0 subject from date message-id references 0 0 ""))
5540
5541     (message-setup
5542      `((Subject . ,subject)
5543        ,@follow-to)
5544      cur)))
5545
5546 ;;;###autoload
5547 (defun message-wide-reply (&optional to-address)
5548   "Make a \"wide\" reply to the message in the current buffer."
5549   (interactive)
5550   (message-reply to-address t))
5551
5552 ;;;###autoload
5553 (defun message-followup (&optional to-newsgroups)
5554   "Follow up to the message in the current buffer.
5555 If TO-NEWSGROUPS, use that as the new Newsgroups line."
5556   (interactive)
5557   (require 'gnus-sum)                   ; for gnus-list-identifiers
5558   (let ((cur (current-buffer))
5559         from subject date reply-to mrt mct
5560         references message-id follow-to
5561         (inhibit-point-motion-hooks t)
5562         (message-this-is-news t)
5563         followup-to distribution newsgroups gnus-warning posted-to)
5564     (save-restriction
5565       (narrow-to-region
5566        (goto-char (point-min))
5567        (if (search-forward "\n\n" nil t)
5568            (1- (point))
5569          (point-max)))
5570       (when (message-functionp message-followup-to-function)
5571         (setq follow-to
5572               (funcall message-followup-to-function)))
5573       (setq from (message-fetch-field "from")
5574             date (message-fetch-field "date")
5575             subject (or (message-fetch-field "subject") "none")
5576             references (message-fetch-field "references")
5577             message-id (message-fetch-field "message-id" t)
5578             followup-to (message-fetch-field "followup-to")
5579             newsgroups (message-fetch-field "newsgroups")
5580             posted-to (message-fetch-field "posted-to")
5581             reply-to (message-fetch-field "reply-to")
5582             mrt (message-fetch-field "mail-reply-to")
5583             distribution (message-fetch-field "distribution")
5584             mct (message-fetch-field "mail-copies-to"))
5585       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
5586                  (string-match "<[^>]+>" gnus-warning))
5587         (setq message-id (match-string 0 gnus-warning)))
5588       ;; Remove bogus distribution.
5589       (when (and (stringp distribution)
5590                  (let ((case-fold-search t))
5591                    (string-match "world" distribution)))
5592         (setq distribution nil))
5593       (if gnus-list-identifiers
5594           (setq subject (message-strip-list-identifiers subject)))
5595       (setq subject (concat "Re: " (message-strip-subject-re subject)))
5596       (when message-subject-trailing-was-query
5597         (setq subject (message-strip-subject-trailing-was subject)))
5598       (widen))
5599
5600     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
5601
5602     (setq message-reply-headers
5603           (vector 0 subject from date message-id references 0 0 ""))
5604
5605     (message-setup
5606      `((Subject . ,subject)
5607        ,@(cond
5608           (to-newsgroups
5609            (list (cons 'Newsgroups to-newsgroups)))
5610           (follow-to follow-to)
5611           ((and followup-to message-use-followup-to)
5612            (list
5613             (cond
5614              ((equal (downcase followup-to) "poster")
5615               (if (or (eq message-use-followup-to 'use)
5616                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
5617 You should normally obey the Followup-To: header.
5618
5619 `Followup-To: poster' sends your response via e-mail instead of news.
5620
5621 A typical situation where `Followup-To: poster' is used is when the poster
5622 does not read the newsgroup, so he wouldn't see any replies sent to it."))
5623                   (progn
5624                     (setq message-this-is-news nil)
5625                     (cons 'To (or mrt reply-to from "")))
5626                 (cons 'Newsgroups newsgroups)))
5627              (t
5628               (if (or (equal followup-to newsgroups)
5629                       (not (eq message-use-followup-to 'ask))
5630                       (message-y-or-n-p
5631                        (concat "Obey Followup-To: " followup-to "? ") t "\
5632 You should normally obey the Followup-To: header.
5633
5634         `Followup-To: " followup-to "'
5635 directs your response to " (if (string-match "," followup-to)
5636                                "the specified newsgroups"
5637                              "that newsgroup only") ".
5638
5639 If a message is posted to several newsgroups, Followup-To is often
5640 used to direct the following discussion to one newsgroup only,
5641 because discussions that are spread over several newsgroup tend to
5642 be fragmented and very difficult to follow.
5643
5644 Also, some source/announcement newsgroups are not intended for discussion;
5645 responses here are directed to other newsgroups."))
5646                   (cons 'Newsgroups followup-to)
5647                 (cons 'Newsgroups newsgroups))))))
5648           (posted-to
5649            `((Newsgroups . ,posted-to)))
5650           (t
5651            `((Newsgroups . ,newsgroups))))
5652        ,@(and distribution (list (cons 'Distribution distribution)))
5653        ,@(when (and mct
5654                     (not (or (equal (downcase mct) "never")
5655                              (equal (downcase mct) "nobody"))))
5656            (list (cons 'Cc (if (or (equal (downcase mct) "always")
5657                                    (equal (downcase mct) "poster"))
5658                                (or mrt reply-to from "")
5659                              mct)))))
5660
5661      cur)))
5662
5663
5664 ;;;###autoload
5665 (defun message-cancel-news (&optional arg)
5666   "Cancel an article you posted.
5667 If ARG, allow editing of the cancellation message."
5668   (interactive "P")
5669   (unless (message-news-p)
5670     (error "This is not a news article; canceling is impossible"))
5671   (let (from newsgroups message-id distribution buf sender)
5672     (save-excursion
5673       ;; Get header info from original article.
5674       (save-restriction
5675         (message-narrow-to-head-1)
5676         (setq from (message-fetch-field "from")
5677               sender (message-fetch-field "sender")
5678               newsgroups (message-fetch-field "newsgroups")
5679               message-id (message-fetch-field "message-id" t)
5680               distribution (message-fetch-field "distribution")))
5681       ;; Make sure that this article was written by the user.
5682       (unless (or
5683                ;; Canlock-logic as suggested by Per Abrahamsen
5684                ;; <abraham@dina.kvl.dk>
5685                ;;
5686                ;; IF article has cancel-lock THEN
5687                ;;   IF we can verify it THEN
5688                ;;     issue cancel
5689                ;;   ELSE
5690                ;;     error: cancellock: article is not yours
5691                ;; ELSE
5692                ;;   Use old rules, comparing sender...
5693                (if (message-fetch-field "Cancel-Lock")
5694                    (if (null (canlock-verify))
5695                        t
5696                      (error "Failed to verify Cancel-lock: This article is not yours"))
5697                  nil)
5698                (message-gnksa-enable-p 'cancel-messages)
5699                (and sender
5700                     (string-equal
5701                      (downcase sender)
5702                      (downcase (message-make-sender))))
5703                (string-equal
5704                 (downcase (cadr (mail-extract-address-components from)))
5705                 (downcase (cadr (mail-extract-address-components
5706                                  (message-make-from))))))
5707         (error "This article is not yours"))
5708       (when (yes-or-no-p "Do you really want to cancel this article? ")
5709         ;; Make control message.
5710         (if arg
5711             (message-news)
5712           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
5713         (erase-buffer)
5714         (insert "Newsgroups: " newsgroups "\n"
5715                 "From: " from "\n"
5716                 "Subject: cmsg cancel " message-id "\n"
5717                 "Control: cancel " message-id "\n"
5718                 (if distribution
5719                     (concat "Distribution: " distribution "\n")
5720                   "")
5721                 mail-header-separator "\n"
5722                 message-cancel-message)
5723         (run-hooks 'message-cancel-hook)
5724         (unless arg
5725           (message "Canceling your article...")
5726           (if (let ((message-syntax-checks
5727                      'dont-check-for-anything-just-trust-me))
5728                 (funcall message-send-news-function))
5729               (message "Canceling your article...done"))
5730           (kill-buffer buf))))))
5731
5732 ;;;###autoload
5733 (defun message-supersede ()
5734   "Start composing a message to supersede the current message.
5735 This is done simply by taking the old article and adding a Supersedes
5736 header line with the old Message-ID."
5737   (interactive)
5738   (let ((cur (current-buffer))
5739         (sender (message-fetch-field "sender"))
5740         (from (message-fetch-field "from")))
5741     ;; Check whether the user owns the article that is to be superseded.
5742     (unless (or
5743              ;; Canlock-logic as suggested by Per Abrahamsen
5744              ;; <abraham@dina.kvl.dk>
5745              ;;
5746              ;; IF article has cancel-lock THEN
5747              ;;   IF we can verify it THEN
5748              ;;     issue cancel
5749              ;;   ELSE
5750              ;;     error: cancellock: article is not yours
5751              ;; ELSE
5752              ;;   Use old rules, comparing sender...
5753              (if (message-fetch-field "Cancel-Lock")
5754                  (if (null (canlock-verify))
5755                      t
5756                    (error "Failed to verify Cancel-lock: This article is not yours"))
5757                nil)
5758              (message-gnksa-enable-p 'cancel-messages)
5759                 (and sender
5760                      (string-equal
5761                       (downcase sender)
5762                       (downcase (message-make-sender))))
5763                 (string-equal
5764                  (downcase (cadr (mail-extract-address-components from)))
5765                  (downcase (cadr (mail-extract-address-components
5766                                   (message-make-from))))))
5767       (error "This article is not yours"))
5768     ;; Get a normal message buffer.
5769     (message-pop-to-buffer (message-buffer-name "supersede"))
5770     (insert-buffer-substring cur)
5771     (mime-to-mml)
5772     (message-narrow-to-head-1)
5773     ;; Remove unwanted headers.
5774     (when message-ignored-supersedes-headers
5775       (message-remove-header message-ignored-supersedes-headers t))
5776     (goto-char (point-min))
5777     (if (not (re-search-forward "^Message-ID: " nil t))
5778         (error "No Message-ID in this article")
5779       (replace-match "Supersedes: " t t))
5780     (goto-char (point-max))
5781     (insert mail-header-separator)
5782     (widen)
5783     (forward-line 1)))
5784
5785 ;;;###autoload
5786 (defun message-recover ()
5787   "Reread contents of current buffer from its last auto-save file."
5788   (interactive)
5789   (let ((file-name (make-auto-save-file-name)))
5790     (cond ((save-window-excursion
5791              (if (not (eq system-type 'vax-vms))
5792                  (with-output-to-temp-buffer "*Directory*"
5793                    (with-current-buffer standard-output
5794                      (fundamental-mode)) ; for Emacs 20.4+
5795                    (buffer-disable-undo standard-output)
5796                    (let ((default-directory "/"))
5797                      (call-process
5798                       "ls" nil standard-output nil "-l" file-name))))
5799              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
5800            (let ((buffer-read-only nil))
5801              (erase-buffer)
5802              (insert-file-contents file-name nil)))
5803           (t (error "message-recover cancelled")))))
5804
5805 ;;; Washing Subject:
5806
5807 (defun message-wash-subject (subject)
5808   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
5809 Previous forwarders, replyers, etc. may add it."
5810   (with-temp-buffer
5811     (insert subject)
5812     (goto-char (point-min))
5813     ;; strip Re/Fwd stuff off the beginning
5814     (while (re-search-forward
5815             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
5816       (replace-match ""))
5817
5818     ;; and gnus-style forwards [foo@bar.com] subject
5819     (goto-char (point-min))
5820     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
5821       (replace-match ""))
5822
5823     ;; and off the end
5824     (goto-char (point-max))
5825     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
5826       (replace-match ""))
5827
5828     ;; and finally, any whitespace that was left-over
5829     (goto-char (point-min))
5830     (while (re-search-forward "^[ \t]+" nil t)
5831       (replace-match ""))
5832     (goto-char (point-max))
5833     (while (re-search-backward "[ \t]+$" nil t)
5834       (replace-match ""))
5835
5836     (buffer-string)))
5837
5838 ;;; Forwarding messages.
5839
5840 (defvar message-forward-decoded-p nil
5841   "Non-nil means the original message is decoded.")
5842
5843 (defun message-forward-subject-author-subject (subject)
5844   "Generate a SUBJECT for a forwarded message.
5845 The form is: [Source] Subject, where if the original message was mail,
5846 Source is the sender, and if the original message was news, Source is
5847 the list of newsgroups is was posted to."
5848   (concat "["
5849           (let ((prefix
5850                  (or (message-fetch-field "newsgroups")
5851                      (message-fetch-field "from")
5852                      "(nowhere)")))
5853             (if message-forward-decoded-p
5854                 prefix
5855               (mail-decode-encoded-word-string prefix)))
5856           "] " subject))
5857
5858 (defun message-forward-subject-name-subject (subject)
5859   "Generate a SUBJECT for a forwarded message.
5860 The form is: [Source] Subject, where if the original message was mail,
5861 Source is the name of the sender, and if the original message was
5862 news, Source is the list of newsgroups is was posted to."
5863   (concat "["
5864           (let ((prefix
5865                  (or (message-fetch-field "newsgroups")
5866                      (let ((from (message-fetch-field "from")))
5867                        (and from
5868                             (cdr (mail-header-parse-address from))))
5869                      "(nowhere)")))
5870             (if message-forward-decoded-p
5871                 prefix
5872               (mail-decode-encoded-word-string prefix)))
5873           "] " subject))
5874
5875 (defun message-forward-subject-fwd (subject)
5876   "Generate a SUBJECT for a forwarded message.
5877 The form is: Fwd: Subject, where Subject is the original subject of
5878 the message."
5879   (concat "Fwd: " subject))
5880
5881 (defun message-make-forward-subject ()
5882   "Return a Subject header suitable for the message in the current buffer."
5883   (save-excursion
5884     (save-restriction
5885       (message-narrow-to-head-1)
5886       (let ((funcs message-make-forward-subject-function)
5887             (subject (message-fetch-field "Subject")))
5888         (setq subject
5889               (if subject
5890                   (if message-forward-decoded-p
5891                       subject
5892                     (mail-decode-encoded-word-string subject))
5893                 ""))
5894         (if message-wash-forwarded-subjects
5895             (setq subject (message-wash-subject subject)))
5896         ;; Make sure funcs is a list.
5897         (and funcs
5898              (not (listp funcs))
5899              (setq funcs (list funcs)))
5900         ;; Apply funcs in order, passing subject generated by previous
5901         ;; func to the next one.
5902         (while funcs
5903           (when (message-functionp (car funcs))
5904             (setq subject (funcall (car funcs) subject)))
5905           (setq funcs (cdr funcs)))
5906         subject))))
5907
5908 (eval-when-compile
5909   (defvar gnus-article-decoded-p))
5910
5911
5912 ;;;###autoload
5913 (defun message-forward (&optional news digest)
5914   "Forward the current message via mail.
5915 Optional NEWS will use news to forward instead of mail.
5916 Optional DIGEST will use digest to forward."
5917   (interactive "P")
5918   (let* ((cur (current-buffer))
5919          (message-forward-decoded-p
5920           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
5921               gnus-article-decoded-p ;; In an article buffer.
5922             message-forward-decoded-p))
5923          (subject (message-make-forward-subject)))
5924     (if news
5925         (message-news nil subject)
5926       (message-mail nil subject))
5927     (message-forward-make-body cur digest)))
5928
5929 ;;;###autoload
5930 (defun message-forward-make-body (forward-buffer &optional digest)
5931   ;; Put point where we want it before inserting the forwarded
5932   ;; message.
5933   (if message-forward-before-signature
5934       (message-goto-body)
5935     (goto-char (point-max)))
5936   (if message-forward-as-mime
5937       (if digest
5938           (insert "\n<#multipart type=digest>\n")
5939         (if message-forward-show-mml
5940             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
5941           (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
5942     (insert "\n-------------------- Start of forwarded message --------------------\n"))
5943   (let ((b (point)) e)
5944     (if digest
5945         (if message-forward-as-mime
5946             (insert-buffer-substring forward-buffer)
5947           (mml-insert-buffer forward-buffer))
5948       (if (and message-forward-show-mml
5949                (not message-forward-decoded-p))
5950           (insert
5951            (with-temp-buffer
5952              (mm-disable-multibyte)
5953              (insert
5954               (with-current-buffer forward-buffer
5955                 (mm-with-unibyte-current-buffer (buffer-string))))
5956              (mm-enable-multibyte)
5957              (mime-to-mml)
5958              (goto-char (point-min))
5959              (when (looking-at "From ")
5960                (replace-match "X-From-Line: "))
5961              (buffer-string)))
5962         (save-restriction
5963           (narrow-to-region (point) (point))
5964           (mml-insert-buffer forward-buffer)
5965           (goto-char (point-min))
5966           (when (looking-at "From ")
5967             (replace-match "X-From-Line: "))
5968           (goto-char (point-max)))))
5969     (setq e (point))
5970     (if message-forward-as-mime
5971         (if digest
5972             (insert "<#/multipart>\n")
5973           (if message-forward-show-mml
5974               (insert "<#/mml>\n")
5975             (insert "<#/part>\n")))
5976       (insert "\n-------------------- End of forwarded message --------------------\n"))
5977     (if (and digest message-forward-as-mime)
5978         (save-restriction
5979           (narrow-to-region b e)
5980           (goto-char b)
5981           (narrow-to-region (point)
5982                             (or (search-forward "\n\n" nil t) (point)))
5983           (delete-region (point-min) (point-max)))
5984       (when (and (not current-prefix-arg)
5985                  message-forward-ignored-headers
5986                  ;; don't remove CTE, X-Gnus etc when doing "raw" forward:
5987                  message-forward-show-mml)
5988         (save-restriction
5989           (narrow-to-region b e)
5990           (goto-char b)
5991           (narrow-to-region (point)
5992                             (or (search-forward "\n\n" nil t) (point)))
5993           (message-remove-header message-forward-ignored-headers t)))))
5994   (message-position-point))
5995
5996 ;;;###autoload
5997 (defun message-forward-rmail-make-body (forward-buffer)
5998   (save-window-excursion
5999     (set-buffer forward-buffer)
6000     ;; Rmail doesn't have rmail-msg-restore-non-pruned-header in Emacs
6001     ;; 20.  FIXIT, or we drop support for rmail in Emacs 20.
6002     (if (rmail-msg-is-pruned)
6003         (rmail-msg-restore-non-pruned-header)))
6004   (message-forward-make-body forward-buffer))
6005
6006 ;;;###autoload
6007 (defun message-insinuate-rmail ()
6008   "Let RMAIL uses message to forward."
6009   (interactive)
6010   (setq rmail-enable-mime-composing t)
6011   (setq rmail-insert-mime-forwarded-message-function
6012         'message-forward-rmail-make-body))
6013
6014 ;;;###autoload
6015 (defun message-resend (address)
6016   "Resend the current article to ADDRESS."
6017   (interactive
6018    (list (message-read-from-minibuffer "Resend message to: ")))
6019   (message "Resending message to %s..." address)
6020   (save-excursion
6021     (let ((cur (current-buffer))
6022           beg)
6023       ;; We first set up a normal mail buffer.
6024       (unless (message-mail-user-agent)
6025         (set-buffer (get-buffer-create " *message resend*"))
6026         (erase-buffer))
6027       (let ((message-this-is-mail t)
6028             message-setup-hook)
6029         (message-setup `((To . ,address))))
6030       ;; Insert our usual headers.
6031       (message-generate-headers '(From Date To))
6032       (message-narrow-to-headers)
6033       ;; Remove X-Draft-From header etc.
6034       (message-remove-header message-ignored-mail-headers t)
6035       ;; Rename them all to "Resent-*".
6036       (goto-char (point-min))
6037       (while (re-search-forward "^[A-Za-z]" nil t)
6038         (forward-char -1)
6039         (insert "Resent-"))
6040       (widen)
6041       (forward-line)
6042       (delete-region (point) (point-max))
6043       (setq beg (point))
6044       ;; Insert the message to be resent.
6045       (insert-buffer-substring cur)
6046       (goto-char (point-min))
6047       (search-forward "\n\n")
6048       (forward-char -1)
6049       (save-restriction
6050         (narrow-to-region beg (point))
6051         (message-remove-header message-ignored-resent-headers t)
6052         (goto-char (point-max)))
6053       (insert mail-header-separator)
6054       ;; Rename all old ("Also-")Resent headers.
6055       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
6056         (beginning-of-line)
6057         (insert "Also-"))
6058       ;; Quote any "From " lines at the beginning.
6059       (goto-char beg)
6060       (when (looking-at "From ")
6061         (replace-match "X-From-Line: "))
6062       ;; Send it.
6063       (let ((message-inhibit-body-encoding t)
6064             message-required-mail-headers)
6065         (message-send-mail))
6066       (kill-buffer (current-buffer)))
6067     (message "Resending message to %s...done" address)))
6068
6069 ;;;###autoload
6070 (defun message-bounce ()
6071   "Re-mail the current message.
6072 This only makes sense if the current message is a bounce message that
6073 contains some mail you have written which has been bounced back to
6074 you."
6075   (interactive)
6076   (let ((handles (mm-dissect-buffer t))
6077         boundary)
6078     (message-pop-to-buffer (message-buffer-name "bounce"))
6079     (if (stringp (car handles))
6080         ;; This is a MIME bounce.
6081         (mm-insert-part (car (last handles)))
6082       ;; This is a non-MIME bounce, so we try to remove things
6083       ;; manually.
6084       (mm-insert-part handles)
6085       (undo-boundary)
6086       (goto-char (point-min))
6087       (search-forward "\n\n" nil t)
6088       (if (or (and (re-search-forward message-unsent-separator nil t)
6089                    (forward-line 1))
6090               (re-search-forward "^Return-Path:.*\n" nil t))
6091           ;; We remove everything before the bounced mail.
6092           (delete-region
6093            (point-min)
6094            (if (re-search-forward "^[^ \n\t]+:" nil t)
6095                (match-beginning 0)
6096              (point)))
6097         (when (re-search-backward "^.?From .*\n" nil t)
6098           (delete-region (match-beginning 0) (match-end 0)))))
6099     (mm-enable-multibyte)
6100     (mime-to-mml)
6101     (save-restriction
6102       (message-narrow-to-head-1)
6103       (message-remove-header message-ignored-bounced-headers t)
6104       (goto-char (point-max))
6105       (insert mail-header-separator))
6106     (message-position-point)))
6107
6108 ;;;
6109 ;;; Interactive entry points for new message buffers.
6110 ;;;
6111
6112 ;;;###autoload
6113 (defun message-mail-other-window (&optional to subject)
6114   "Like `message-mail' command, but display mail buffer in another window."
6115   (interactive)
6116   (unless (message-mail-user-agent)
6117     (let ((pop-up-windows t)
6118           (special-display-buffer-names nil)
6119           (special-display-regexps nil)
6120           (same-window-buffer-names nil)
6121           (same-window-regexps nil))
6122       (message-pop-to-buffer (message-buffer-name "mail" to))))
6123   (let ((message-this-is-mail t))
6124     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6125                    nil nil 'switch-to-buffer-other-window)))
6126
6127 ;;;###autoload
6128 (defun message-mail-other-frame (&optional to subject)
6129   "Like `message-mail' command, but display mail buffer in another frame."
6130   (interactive)
6131   (unless (message-mail-user-agent)
6132     (let ((pop-up-frames t)
6133           (special-display-buffer-names nil)
6134           (special-display-regexps nil)
6135           (same-window-buffer-names nil)
6136           (same-window-regexps nil))
6137       (message-pop-to-buffer (message-buffer-name "mail" to))))
6138   (let ((message-this-is-mail t))
6139     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
6140                    nil nil 'switch-to-buffer-other-frame)))
6141
6142 ;;;###autoload
6143 (defun message-news-other-window (&optional newsgroups subject)
6144   "Start editing a news article to be sent."
6145   (interactive)
6146   (let ((pop-up-windows t)
6147         (special-display-buffer-names nil)
6148         (special-display-regexps nil)
6149         (same-window-buffer-names nil)
6150         (same-window-regexps nil))
6151     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6152   (let ((message-this-is-news t))
6153     (message-setup `((Newsgroups . ,(or newsgroups ""))
6154                      (Subject . ,(or subject ""))))))
6155
6156 ;;;###autoload
6157 (defun message-news-other-frame (&optional newsgroups subject)
6158   "Start editing a news article to be sent."
6159   (interactive)
6160   (let ((pop-up-frames t)
6161         (special-display-buffer-names nil)
6162         (special-display-regexps nil)
6163         (same-window-buffer-names nil)
6164         (same-window-regexps nil))
6165     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
6166   (let ((message-this-is-news t))
6167     (message-setup `((Newsgroups . ,(or newsgroups ""))
6168                      (Subject . ,(or subject ""))))))
6169
6170 ;;; underline.el
6171
6172 ;; This code should be moved to underline.el (from which it is stolen).
6173
6174 ;;;###autoload
6175 (defun bold-region (start end)
6176   "Bold all nonblank characters in the region.
6177 Works by overstriking characters.
6178 Called from program, takes two arguments START and END
6179 which specify the range to operate on."
6180   (interactive "r")
6181   (save-excursion
6182     (let ((end1 (make-marker)))
6183       (move-marker end1 (max start end))
6184       (goto-char (min start end))
6185       (while (< (point) end1)
6186         (or (looking-at "[_\^@- ]")
6187             (insert (char-after) "\b"))
6188         (forward-char 1)))))
6189
6190 ;;;###autoload
6191 (defun unbold-region (start end)
6192   "Remove all boldness (overstruck characters) in the region.
6193 Called from program, takes two arguments START and END
6194 which specify the range to operate on."
6195   (interactive "r")
6196   (save-excursion
6197     (let ((end1 (make-marker)))
6198       (move-marker end1 (max start end))
6199       (goto-char (min start end))
6200       (while (re-search-forward "\b" end1 t)
6201         (if (eq (char-after) (char-after (- (point) 2)))
6202             (delete-char -2))))))
6203
6204 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
6205 (defalias 'message-make-overlay 'make-overlay)
6206 (defalias 'message-delete-overlay 'delete-overlay)
6207 (defalias 'message-overlay-put 'overlay-put)
6208
6209 ;; Support for toolbar
6210 (eval-when-compile
6211   (defvar tool-bar-map)
6212   (defvar tool-bar-mode))
6213
6214 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
6215   ;; We need to make tool bar entries in local keymaps with
6216   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
6217   (if (fboundp 'tool-bar-local-item-from-menu)
6218       ;; This is for Emacs 21.3
6219       (tool-bar-local-item-from-menu command icon in-map from-map props)
6220     (tool-bar-add-item-from-menu command icon from-map props)))
6221
6222 (defun message-tool-bar-map ()
6223   (or message-tool-bar-map
6224       (setq message-tool-bar-map
6225             (and
6226              (condition-case nil (require 'tool-bar) (error nil))
6227              (fboundp 'tool-bar-add-item-from-menu)
6228              tool-bar-mode
6229              (let ((tool-bar-map (copy-keymap tool-bar-map))
6230                    (load-path (mm-image-load-path)))
6231                ;; Zap some items which aren't so relevant and take
6232                ;; up space.
6233                (dolist (key '(print-buffer kill-buffer save-buffer
6234                                            write-file dired open-file))
6235                  (define-key tool-bar-map (vector key) nil))
6236                (message-tool-bar-local-item-from-menu
6237                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
6238                (message-tool-bar-local-item-from-menu
6239                 'message-kill-buffer "close" tool-bar-map message-mode-map)
6240                (message-tool-bar-local-item-from-menu
6241                     'message-dont-send "cancel" tool-bar-map message-mode-map)
6242                (message-tool-bar-local-item-from-menu
6243                 'mml-attach-file "attach" tool-bar-map mml-mode-map)
6244                (message-tool-bar-local-item-from-menu
6245                 'ispell-message "spell" tool-bar-map message-mode-map)
6246                (message-tool-bar-local-item-from-menu
6247                 'mml-preview "preview"
6248                 tool-bar-map mml-mode-map)
6249                (message-tool-bar-local-item-from-menu
6250                 'message-insert-importance-high "important"
6251                 tool-bar-map message-mode-map)
6252                (message-tool-bar-local-item-from-menu
6253                 'message-insert-importance-low "unimportant"
6254                 tool-bar-map message-mode-map)
6255                (message-tool-bar-local-item-from-menu
6256                 'message-insert-disposition-notification-to "receipt"
6257                 tool-bar-map message-mode-map)
6258                tool-bar-map)))))
6259
6260 ;;; Group name completion.
6261
6262 (defcustom message-newgroups-header-regexp
6263   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
6264   "Regexp that match headers that lists groups."
6265   :group 'message
6266   :type 'regexp)
6267
6268 (defcustom message-completion-alist
6269   (list (cons message-newgroups-header-regexp 'message-expand-group)
6270         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
6271         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
6272           . message-expand-name)
6273         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
6274           . message-expand-name))
6275   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
6276   :group 'message
6277   :type '(alist :key-type regexp :value-type function))
6278
6279 (defcustom message-tab-body-function nil
6280   "*Function to execute when `message-tab' (TAB) is executed in the body.
6281 If nil, the function bound in `text-mode-map' or `global-map' is executed."
6282   :group 'message
6283   :type 'function)
6284
6285 (defun message-tab ()
6286   "Complete names according to `message-completion-alist'.
6287 Execute function specified by `message-tab-body-function' when not in
6288 those headers."
6289   (interactive)
6290   (let ((alist message-completion-alist))
6291     (while (and alist
6292                 (let ((mail-abbrev-mode-regexp (caar alist)))
6293                   (not (mail-abbrev-in-expansion-header-p))))
6294       (setq alist (cdr alist)))
6295     (funcall (or (cdar alist) message-tab-body-function
6296                  (lookup-key text-mode-map "\t")
6297                  (lookup-key global-map "\t")
6298                  'indent-relative))))
6299
6300 (defun message-expand-group ()
6301   "Expand the group name under point."
6302   (let* ((b (save-excursion
6303               (save-restriction
6304                 (narrow-to-region
6305                  (save-excursion
6306                    (beginning-of-line)
6307                    (skip-chars-forward "^:")
6308                    (1+ (point)))
6309                  (point))
6310                 (skip-chars-backward "^, \t\n") (point))))
6311          (completion-ignore-case t)
6312          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
6313                                             (point))))
6314          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
6315          (completions (all-completions string hashtb))
6316          comp)
6317     (delete-region b (point))
6318     (cond
6319      ((= (length completions) 1)
6320       (if (string= (car completions) string)
6321           (progn
6322             (insert string)
6323             (message "Only matching group"))
6324         (insert (car completions))))
6325      ((and (setq comp (try-completion string hashtb))
6326            (not (string= comp string)))
6327       (insert comp))
6328      (t
6329       (insert string)
6330       (if (not comp)
6331           (message "No matching groups")
6332         (save-selected-window
6333           (pop-to-buffer "*Completions*")
6334           (buffer-disable-undo)
6335           (let ((buffer-read-only nil))
6336             (erase-buffer)
6337             (let ((standard-output (current-buffer)))
6338               (display-completion-list (sort completions 'string<)))
6339             (goto-char (point-min))
6340             (delete-region (point) (progn (forward-line 3) (point))))))))))
6341
6342 (defun message-expand-name ()
6343   (if (fboundp 'bbdb-complete-name)
6344       (bbdb-complete-name)
6345     (expand-abbrev)))
6346
6347 ;;; Help stuff.
6348
6349 (defun message-talkative-question (ask question show &rest text)
6350   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
6351 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
6352 The following arguments may contain lists of values."
6353   (if (and show
6354            (setq text (message-flatten-list text)))
6355       (save-window-excursion
6356         (save-excursion
6357           (with-output-to-temp-buffer " *MESSAGE information message*"
6358             (set-buffer " *MESSAGE information message*")
6359             (fundamental-mode)          ; for Emacs 20.4+
6360             (mapcar 'princ text)
6361             (goto-char (point-min))))
6362         (funcall ask question))
6363     (funcall ask question)))
6364
6365 (defun message-flatten-list (list)
6366   "Return a new, flat list that contains all elements of LIST.
6367
6368 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
6369 => (1 2 3 4 5 6 7)"
6370   (cond ((consp list)
6371          (apply 'append (mapcar 'message-flatten-list list)))
6372         (list
6373          (list list))))
6374
6375 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
6376   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
6377 Then clone the local variables and values from the old buffer to the
6378 new one, cloning only the locals having a substring matching the
6379 regexp varstr."
6380   (let ((oldbuf (current-buffer)))
6381     (save-excursion
6382       (set-buffer (generate-new-buffer name))
6383       (message-clone-locals oldbuf varstr)
6384       (current-buffer))))
6385
6386 (defun message-clone-locals (buffer &optional varstr)
6387   "Clone the local variables from BUFFER to the current buffer."
6388   (let ((locals (save-excursion
6389                   (set-buffer buffer)
6390                   (buffer-local-variables)))
6391         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
6392     (mapcar
6393      (lambda (local)
6394        (when (and (consp local)
6395                   (car local)
6396                   (string-match regexp (symbol-name (car local)))
6397                   (or (null varstr)
6398                       (string-match varstr (symbol-name (car local)))))
6399          (ignore-errors
6400            (set (make-local-variable (car local))
6401                 (cdr local)))))
6402      locals)))
6403
6404 ;;;
6405 ;;; MIME functions
6406 ;;;
6407
6408 (defvar message-inhibit-body-encoding nil)
6409
6410 (defun message-encode-message-body ()
6411   (unless message-inhibit-body-encoding
6412     (let ((mail-parse-charset (or mail-parse-charset
6413                                   message-default-charset))
6414           (case-fold-search t)
6415           lines content-type-p)
6416       (message-goto-body)
6417       (save-restriction
6418         (narrow-to-region (point) (point-max))
6419         (let ((new (mml-generate-mime)))
6420           (when new
6421             (delete-region (point-min) (point-max))
6422             (insert new)
6423             (goto-char (point-min))
6424             (if (eq (aref new 0) ?\n)
6425                 (delete-char 1)
6426               (search-forward "\n\n")
6427               (setq lines (buffer-substring (point-min) (1- (point))))
6428               (delete-region (point-min) (point))))))
6429       (save-restriction
6430         (message-narrow-to-headers-or-head)
6431         (message-remove-header "Mime-Version")
6432         (goto-char (point-max))
6433         (insert "MIME-Version: 1.0\n")
6434         (when lines
6435           (insert lines))
6436         (setq content-type-p
6437               (or mml-boundary
6438                   (re-search-backward "^Content-Type:" nil t))))
6439       (save-restriction
6440         (message-narrow-to-headers-or-head)
6441         (message-remove-first-header "Content-Type")
6442         (message-remove-first-header "Content-Transfer-Encoding"))
6443       ;; We always make sure that the message has a Content-Type
6444       ;; header.  This is because some broken MTAs and MUAs get
6445       ;; awfully confused when confronted with a message with a
6446       ;; MIME-Version header and without a Content-Type header.  For
6447       ;; instance, Solaris' /usr/bin/mail.
6448       (unless content-type-p
6449         (goto-char (point-min))
6450         ;; For unknown reason, MIME-Version doesn't exist.
6451         (when (re-search-forward "^MIME-Version:" nil t)
6452           (forward-line 1)
6453           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
6454
6455 (defun message-read-from-minibuffer (prompt &optional initial-contents)
6456   "Read from the minibuffer while providing abbrev expansion."
6457   (if (fboundp 'mail-abbrevs-setup)
6458       (let ((mail-abbrev-mode-regexp "")
6459             (minibuffer-setup-hook 'mail-abbrevs-setup)
6460             (minibuffer-local-map message-minibuffer-local-map))
6461         (read-from-minibuffer prompt initial-contents))
6462     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
6463           (minibuffer-local-map message-minibuffer-local-map))
6464       (read-string prompt initial-contents))))
6465
6466 (defun message-use-alternative-email-as-from ()
6467   (require 'mail-utils)
6468   (let* ((fields '("To" "Cc"))
6469          (emails
6470           (split-string
6471            (mail-strip-quoted-names
6472             (mapconcat 'message-fetch-reply-field fields ","))
6473            "[ \f\t\n\r\v,]+"))
6474          email)
6475     (while emails
6476       (if (string-match message-alternative-emails (car emails))
6477           (setq email (car emails)
6478                 emails nil))
6479       (pop emails))
6480     (unless (or (not email) (equal email user-mail-address))
6481       (goto-char (point-max))
6482       (insert "From: " email "\n"))))
6483
6484 (defun message-options-get (symbol)
6485   (cdr (assq symbol message-options)))
6486
6487 (defun message-options-set (symbol value)
6488   (let ((the-cons (assq symbol message-options)))
6489     (if the-cons
6490         (if value
6491             (setcdr the-cons value)
6492           (setq message-options (delq the-cons message-options)))
6493       (and value
6494            (push (cons symbol value) message-options))))
6495   value)
6496
6497 (defun message-options-set-recipient ()
6498   (save-restriction
6499     (message-narrow-to-headers-or-head)
6500     (message-options-set 'message-sender
6501                          (mail-strip-quoted-names
6502                           (message-fetch-field "from")))
6503     (message-options-set 'message-recipients
6504                          (mail-strip-quoted-names
6505                           (let ((to (message-fetch-field "to"))
6506                                 (cc (message-fetch-field "cc"))
6507                                 (bcc (message-fetch-field "bcc")))
6508                             (concat
6509                              (or to "")
6510                              (if (and to cc) ", ")
6511                              (or cc "")
6512                              (if (and (or to cc) bcc) ", ")
6513                              (or bcc "")))))))
6514
6515 (defun message-hide-headers ()
6516   "Hide headers based on the `message-hidden-headers' variable."
6517   (let ((regexps (if (stringp message-hidden-headers)
6518                      (list message-hidden-headers)
6519                    message-hidden-headers))
6520         (inhibit-point-motion-hooks t)
6521         (after-change-functions nil))
6522     (when regexps
6523       (save-excursion
6524         (save-restriction
6525           (message-narrow-to-headers)
6526           (goto-char (point-min))
6527           (while (not (eobp))
6528             (if (not (message-hide-header-p regexps))
6529                 (message-next-header)
6530               (let ((begin (point)))
6531                 (message-next-header)
6532                 (add-text-properties
6533                  begin (point)
6534                  '(invisible t message-hidden t))))))))))
6535
6536 (defun message-hide-header-p (regexps)
6537   (let ((result nil)
6538         (reverse nil))
6539     (when (eq (car regexps) 'not)
6540       (setq reverse t)
6541       (pop regexps))
6542     (dolist (regexp regexps)
6543       (setq result (or result (looking-at regexp))))
6544     (if reverse
6545         (not result)
6546       result)))
6547
6548 (when (featurep 'xemacs)
6549   (require 'messagexmas)
6550   (message-xmas-redefine))
6551
6552 (provide 'message)
6553
6554 (run-hooks 'message-load-hook)
6555
6556 ;; Local Variables:
6557 ;; coding: iso-8859-1
6558 ;; End:
6559
6560 ;;; message.el ends here