Change default to `unsent'.
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: mail, news
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-and-compile
33   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
34 (eval-when-compile
35   (require 'cl))
36
37 (require 'mailheader)
38 (require 'gmm-utils)
39 (require 'mail-utils)
40 ;; Only for the trivial macros mail-header-from, mail-header-date
41 ;; mail-header-references, mail-header-subject, mail-header-id
42 (eval-when-compile (require 'nnheader))
43 ;; This is apparently necessary even though things are autoloaded.
44 ;; Because we dynamically bind mail-abbrev-mode-regexp, we'd better
45 ;; require mailabbrev here.
46 (if (featurep 'xemacs)
47     (require 'mail-abbrevs)
48   (require 'mailabbrev))
49 (require 'mail-parse)
50 (require 'mml)
51 (require 'rfc822)
52
53 (autoload 'mailclient-send-it "mailclient") ;; Emacs 22 or contrib/
54
55 (defvar gnus-message-group-art)
56 (defvar gnus-list-identifiers) ; gnus-sum is required where necessary
57 (defvar rmail-enable-mime-composing)
58
59 (defgroup message '((user-mail-address custom-variable)
60                     (user-full-name custom-variable))
61   "Mail and news message composing."
62   :link '(custom-manual "(message)Top")
63   :group 'mail
64   :group 'news)
65
66 (put 'user-mail-address 'custom-type 'string)
67 (put 'user-full-name 'custom-type 'string)
68
69 (defgroup message-various nil
70   "Various Message Variables."
71   :link '(custom-manual "(message)Various Message Variables")
72   :group 'message)
73
74 (defgroup message-buffers nil
75   "Message Buffers."
76   :link '(custom-manual "(message)Message Buffers")
77   :group 'message)
78
79 (defgroup message-sending nil
80   "Message Sending."
81   :link '(custom-manual "(message)Sending Variables")
82   :group 'message)
83
84 (defgroup message-interface nil
85   "Message Interface."
86   :link '(custom-manual "(message)Interface")
87   :group 'message)
88
89 (defgroup message-forwarding nil
90   "Message Forwarding."
91   :link '(custom-manual "(message)Forwarding")
92   :group 'message-interface)
93
94 (defgroup message-insertion nil
95   "Message Insertion."
96   :link '(custom-manual "(message)Insertion")
97   :group 'message)
98
99 (defgroup message-headers nil
100   "Message Headers."
101   :link '(custom-manual "(message)Message Headers")
102   :group 'message)
103
104 (defgroup message-news nil
105   "Composing News Messages."
106   :group 'message)
107
108 (defgroup message-mail nil
109   "Composing Mail Messages."
110   :group 'message)
111
112 (defgroup message-faces nil
113   "Faces used for message composing."
114   :group 'message
115   :group 'faces)
116
117 (defcustom message-directory "~/Mail/"
118   "*Directory from which all other mail file variables are derived."
119   :group 'message-various
120   :type 'directory)
121
122 (defcustom message-max-buffers 10
123   "*How many buffers to keep before starting to kill them off."
124   :group 'message-buffers
125   :type 'integer)
126
127 (defcustom message-send-rename-function nil
128   "Function called to rename the buffer after sending it."
129   :group 'message-buffers
130   :type '(choice function (const nil)))
131
132 (defcustom message-fcc-handler-function 'message-output
133   "*A function called to save outgoing articles.
134 This function will be called with the name of the file to store the
135 article in.  The default function is `message-output' which saves in Unix
136 mailbox format."
137   :type '(radio (function-item message-output)
138                 (function :tag "Other"))
139   :group 'message-sending)
140
141 (defcustom message-fcc-externalize-attachments nil
142   "If non-nil, attachments are included as external parts in Fcc copies."
143   :version "22.1"
144   :type 'boolean
145   :group 'message-sending)
146
147 (defcustom message-courtesy-message
148   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
149   "*This is inserted at the start of a mailed copy of a posted message.
150 If the string contains the format spec \"%s\", the Newsgroups
151 the article has been posted to will be inserted there.
152 If this variable is nil, no such courtesy message will be added."
153   :group 'message-sending
154   :type '(radio string (const nil)))
155
156 (defcustom message-ignored-bounced-headers
157   "^\\(Received\\|Return-Path\\|Delivered-To\\):"
158   "*Regexp that matches headers to be removed in resent bounced mail."
159   :group 'message-interface
160   :type 'regexp)
161
162 (defcustom message-from-style 'default
163   "*Specifies how \"From\" headers look.
164
165 If nil, they contain just the return address like:
166         king@grassland.com
167 If `parens', they look like:
168         king@grassland.com (Elvis Parsley)
169 If `angles', they look like:
170         Elvis Parsley <king@grassland.com>
171
172 Otherwise, most addresses look like `angles', but they look like
173 `parens' if `angles' would need quoting and `parens' would not."
174   :version "23.2"
175   :type '(choice (const :tag "simple" nil)
176                  (const parens)
177                  (const angles)
178                  (const default))
179   :group 'message-headers)
180
181 (defcustom message-insert-canlock t
182   "Whether to insert a Cancel-Lock header in news postings."
183   :version "22.1"
184   :group 'message-headers
185   :type 'boolean)
186
187 (defcustom message-syntax-checks
188   (if message-insert-canlock '((sender . disabled)) nil)
189   ;; Guess this one shouldn't be easy to customize...
190   "*Controls what syntax checks should not be performed on outgoing posts.
191 To disable checking of long signatures, for instance, add
192  `(signature . disabled)' to this list.
193
194 Don't touch this variable unless you really know what you're doing.
195
196 Checks include `approved', `bogus-recipient', `continuation-headers',
197 `control-chars', `empty', `existing-newsgroups', `from', `illegible-text',
198 `invisible-text', `long-header-lines', `long-lines', `message-id',
199 `multiple-headers', `new-text', `newsgroups', `quoting-style',
200 `repeated-newsgroups', `reply-to', `sender', `sendsys', `shoot',
201 `shorten-followup-to', `signature', `size', `subject', `subject-cmsg'
202 and `valid-newsgroups'."
203   :group 'message-news
204   :type '(repeat sexp))                 ; Fixme: improve this
205
206 (defcustom message-required-headers '((optional . References)
207                                       From)
208   "*Headers to be generated or prompted for when sending a message.
209 Also see `message-required-news-headers' and
210 `message-required-mail-headers'."
211   :version "22.1"
212   :group 'message-news
213   :group 'message-headers
214   :link '(custom-manual "(message)Message Headers")
215   :type '(repeat sexp))
216
217 (defcustom message-draft-headers '(References From Date)
218   "*Headers to be generated when saving a draft message."
219   :version "22.1"
220   :group 'message-news
221   :group 'message-headers
222   :link '(custom-manual "(message)Message Headers")
223   :type '(repeat sexp))
224
225 (defcustom message-required-news-headers
226   '(From Newsgroups Subject Date Message-ID
227          (optional . Organization)
228          (optional . User-Agent))
229   "*Headers to be generated or prompted for when posting an article.
230 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
231 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
232 User-Agent are optional.  If you don't want message to insert some
233 header, remove it from this list."
234   :group 'message-news
235   :group 'message-headers
236   :link '(custom-manual "(message)Message Headers")
237   :type '(repeat sexp))
238
239 (defcustom message-required-mail-headers
240   '(From Subject Date (optional . In-Reply-To) Message-ID
241          (optional . User-Agent))
242   "*Headers to be generated or prompted for when mailing a message.
243 It is recommended that From, Date, To, Subject and Message-ID be
244 included.  Organization and User-Agent are optional."
245   :group 'message-mail
246   :group 'message-headers
247   :link '(custom-manual "(message)Message Headers")
248   :type '(repeat sexp))
249
250 (defcustom message-prune-recipient-rules nil
251   "Rules for how to prune the list of recipients when doing wide replies.
252 This is a list of regexps and regexp matches."
253   :version "24.1"
254   :group 'message-mail
255   :group 'message-headers
256   :link '(custom-manual "(message)Wide Reply")
257   :type '(repeat regexp))
258
259 (defcustom message-deletable-headers '(Message-ID Date Lines)
260   "Headers to be deleted if they already exist and were generated by message previously."
261   :group 'message-headers
262   :link '(custom-manual "(message)Message Headers")
263   :type 'sexp)
264
265 (defcustom message-ignored-news-headers
266   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
267   "*Regexp of headers to be removed unconditionally before posting."
268   :group 'message-news
269   :group 'message-headers
270   :link '(custom-manual "(message)Message Headers")
271   :type '(repeat :value-to-internal (lambda (widget value)
272                                       (custom-split-regexp-maybe value))
273                  :match (lambda (widget value)
274                           (or (stringp value)
275                               (widget-editable-list-match widget value)))
276                  regexp))
277
278 (defcustom message-ignored-mail-headers
279   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
280   "*Regexp of headers to be removed unconditionally before mailing."
281   :group 'message-mail
282   :group 'message-headers
283   :link '(custom-manual "(message)Mail Headers")
284   :type 'regexp)
285
286 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-ID:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:\\|^X-Hashcash:\\|^X-Payment:\\|^Approved:"
287   "*Header lines matching this regexp will be deleted before posting.
288 It's best to delete old Path and Date headers before posting to avoid
289 any confusion."
290   :group 'message-interface
291   :link '(custom-manual "(message)Superseding")
292   :type '(repeat :value-to-internal (lambda (widget value)
293                                       (custom-split-regexp-maybe value))
294                  :match (lambda (widget value)
295                           (or (stringp value)
296                               (widget-editable-list-match widget value)))
297                  regexp))
298
299 (defcustom message-subject-re-regexp
300   "^[ \t]*\\([Rr][Ee]\\(\\[[0-9]*\\]\\)*:[ \t]*\\)*[ \t]*"
301   "*Regexp matching \"Re: \" in the subject line."
302   :group 'message-various
303   :link '(custom-manual "(message)Message Headers")
304   :type 'regexp)
305
306 ;;; Start of variables adopted from `message-utils.el'.
307
308 (defcustom message-subject-trailing-was-query 'ask
309   "*What to do with trailing \"(was: <old subject>)\" in subject lines.
310 If nil, leave the subject unchanged.  If it is the symbol `ask', query
311 the user what do do.  In this case, the subject is matched against
312 `message-subject-trailing-was-ask-regexp'.  If
313 `message-subject-trailing-was-query' is t, always strip the trailing
314 old subject.  In this case, `message-subject-trailing-was-regexp' is
315 used."
316   :version "22.1"
317   :type '(choice (const :tag "never" nil)
318                  (const :tag "always strip" t)
319                  (const ask))
320   :link '(custom-manual "(message)Message Headers")
321   :group 'message-various)
322
323 (defcustom message-subject-trailing-was-ask-regexp
324   "[ \t]*\\([[(]+[Ww][Aa][Ss][ \t]*.*[\])]+\\)"
325   "*Regexp matching \"(was: <old subject>)\" in the subject line.
326
327 The function `message-strip-subject-trailing-was' uses this regexp if
328 `message-subject-trailing-was-query' is set to the symbol `ask'.  If
329 the variable is t instead of `ask', use
330 `message-subject-trailing-was-regexp' instead.
331
332 It is okay to create some false positives here, as the user is asked."
333   :version "22.1"
334   :group 'message-various
335   :link '(custom-manual "(message)Message Headers")
336   :type 'regexp)
337
338 (defcustom message-subject-trailing-was-regexp
339   "[ \t]*\\((*[Ww][Aa][Ss]:[ \t]*.*)\\)"
340   "*Regexp matching \"(was: <old subject>)\" in the subject line.
341
342 If `message-subject-trailing-was-query' is set to t, the subject is
343 matched against `message-subject-trailing-was-regexp' in
344 `message-strip-subject-trailing-was'.  You should use a regexp creating very
345 few false positives here."
346   :version "22.1"
347   :group 'message-various
348   :link '(custom-manual "(message)Message Headers")
349   :type 'regexp)
350
351 ;;; marking inserted text
352
353 (defcustom message-mark-insert-begin
354   "--8<---------------cut here---------------start------------->8---\n"
355   "How to mark the beginning of some inserted text."
356   :version "22.1"
357   :type 'string
358   :link '(custom-manual "(message)Insertion Variables")
359   :group 'message-various)
360
361 (defcustom message-mark-insert-end
362   "--8<---------------cut here---------------end--------------->8---\n"
363   "How to mark the end of some inserted text."
364   :version "22.1"
365   :type 'string
366   :link '(custom-manual "(message)Insertion Variables")
367   :group 'message-various)
368
369 (defcustom message-archive-header "X-No-Archive: Yes\n"
370   "Header to insert when you don't want your article to be archived.
371 Archives \(such as groups.google.com\) respect this header."
372   :version "22.1"
373   :type 'string
374   :link '(custom-manual "(message)Header Commands")
375   :group 'message-various)
376
377 (defcustom message-archive-note
378   "X-No-Archive: Yes - save http://groups.google.com/"
379   "Note to insert why you wouldn't want this posting archived.
380 If nil, don't insert any text in the body."
381   :version "22.1"
382   :type '(radio string (const nil))
383   :link '(custom-manual "(message)Header Commands")
384   :group 'message-various)
385
386 ;;; Crossposts and Followups
387 ;; inspired by JoH-followup-to by Jochem Huhman <joh  at gmx.de>
388 ;; new suggestions by R. Weikusat <rw at another.de>
389
390 (defvar message-cross-post-old-target nil
391   "Old target for cross-posts or follow-ups.")
392 (make-variable-buffer-local 'message-cross-post-old-target)
393
394 (defcustom message-cross-post-default t
395   "When non-nil `message-cross-post-followup-to' will perform a crosspost.
396 If nil, `message-cross-post-followup-to' will only do a followup.  Note that
397 you can explicitly override this setting by calling
398 `message-cross-post-followup-to' with a prefix."
399   :version "22.1"
400   :type 'boolean
401   :group 'message-various)
402
403 (defcustom message-cross-post-note "Crosspost & Followup-To: "
404   "Note to insert before signature to notify of cross-post and follow-up."
405   :version "22.1"
406   :type 'string
407   :group 'message-various)
408
409 (defcustom message-followup-to-note "Followup-To: "
410   "Note to insert before signature to notify of follow-up only."
411   :version "22.1"
412   :type 'string
413   :group 'message-various)
414
415 (defcustom message-cross-post-note-function 'message-cross-post-insert-note
416   "Function to use to insert note about Crosspost or Followup-To.
417 The function will be called with four arguments.  The function should not only
418 insert a note, but also ensure old notes are deleted.  See the documentation
419 for `message-cross-post-insert-note'."
420   :version "22.1"
421   :type 'function
422   :group 'message-various)
423
424 ;;; End of variables adopted from `message-utils.el'.
425
426 (defcustom message-signature-separator "^-- $"
427   "Regexp matching the signature separator.
428 This variable is used to strip off the signature from quoted text
429 when `message-cite-function' is
430 `message-cite-original-without-signature'.  Most useful values
431 are \"^-- $\" (strict) and \"^-- *$\" (loose; allow missing
432 whitespace)."
433   :type '(choice (const :tag "strict" "^-- $")
434                  (const :tag "loose" "^-- *$")
435                  regexp)
436   :version "22.3" ;; Gnus 5.10.12 (changed default)
437   :link '(custom-manual "(message)Various Message Variables")
438   :group 'message-various)
439
440 (defcustom message-elide-ellipsis "\n[...]\n\n"
441   "*The string which is inserted for elided text."
442   :type 'string
443   :link '(custom-manual "(message)Various Commands")
444   :group 'message-various)
445
446 (defcustom message-interactive t
447   "Non-nil means when sending a message wait for and display errors.
448 A value of nil means let mailer mail back a message to report errors."
449   :version "23.2"
450   :group 'message-sending
451   :group 'message-mail
452   :link '(custom-manual "(message)Sending Variables")
453   :type 'boolean)
454
455 (defcustom message-confirm-send nil
456   "When non-nil, ask for confirmation when sending a message."
457   :group 'message-sending
458   :group 'message-mail
459   :version "23.1" ;; No Gnus
460   :link '(custom-manual "(message)Sending Variables")
461   :type 'boolean)
462
463 (defcustom message-generate-new-buffers 'unsent
464   "*Say whether to create a new message buffer to compose a message.
465 Valid values include:
466
467 nil
468   Generate the buffer name in the Message way (e.g., *mail*, *news*,
469   *mail to whom*, *news on group*, etc.) and continue editing in the
470   existing buffer of that name.  If there is no such buffer, it will
471   be newly created.
472
473 `unique' or t
474   Create the new buffer with the name generated in the Message way.
475
476 `unsent'
477   Similar to `unique' but the buffer name begins with \"*unsent \".
478
479 `standard'
480   Similar to nil but the buffer name is simpler like *mail message*.
481
482 function
483   If this is a function, call that function with three parameters:
484   The type, the To address and the group name (any of these may be nil).
485   The function should return the new buffer name."
486   :version "24.1"
487   :group 'message-buffers
488   :link '(custom-manual "(message)Message Buffers")
489   :type '(choice (const nil)
490                  (sexp :tag "unique" :format "unique\n" :value unique
491                        :match (lambda (widget value) (memq value '(unique t))))
492                  (const unsent)
493                  (const standard)
494                  (function :format "\n    %{%t%}: %v")))
495
496 (defcustom message-kill-buffer-on-exit nil
497   "*Non-nil means that the message buffer will be killed after sending a message."
498   :group 'message-buffers
499   :link '(custom-manual "(message)Message Buffers")
500   :type 'boolean)
501
502 (defcustom message-kill-buffer-query t
503   "*Non-nil means that killing a modified message buffer has to be confirmed.
504 This is used by `message-kill-buffer'."
505   :version "23.1" ;; No Gnus
506   :group 'message-buffers
507   :type 'boolean)
508
509 (defvar gnus-local-organization)
510 (defcustom message-user-organization
511   (or (and (boundp 'gnus-local-organization)
512            (stringp gnus-local-organization)
513            gnus-local-organization)
514       (getenv "ORGANIZATION")
515       t)
516   "*String to be used as an Organization header.
517 If t, use `message-user-organization-file'."
518   :group 'message-headers
519   :type '(choice string
520                  (const :tag "consult file" t)))
521
522 (defcustom message-user-organization-file
523   (let (orgfile)
524     (dolist (f (list "/etc/organization"
525                      "/etc/news/organization"
526                      "/usr/lib/news/organization"))
527       (when (file-readable-p f)
528         (setq orgfile f)))
529     orgfile)
530   "*Local news organization file."
531   :type 'file
532   :link '(custom-manual "(message)News Headers")
533   :group 'message-headers)
534
535 (defcustom message-make-forward-subject-function
536   #'message-forward-subject-name-subject
537   "*List of functions called to generate subject headers for forwarded messages.
538 The subject generated by the previous function is passed into each
539 successive function.
540
541 The provided functions are:
542
543 * `message-forward-subject-author-subject' Source of article (author or
544       newsgroup), in brackets followed by the subject
545 * `message-forward-subject-name-subject' Source of article (name of author
546       or newsgroup), in brackets followed by the subject
547 * `message-forward-subject-fwd' Subject of article with 'Fwd:' prepended
548       to it."
549   :group 'message-forwarding
550   :link '(custom-manual "(message)Forwarding")
551   :type '(radio (function-item message-forward-subject-author-subject)
552                 (function-item message-forward-subject-fwd)
553                 (function-item message-forward-subject-name-subject)
554                 (repeat :tag "List of functions" function)))
555
556 (defcustom message-forward-as-mime t
557   "*Non-nil means forward messages as an inline/rfc822 MIME section.
558 Otherwise, directly inline the old message in the forwarded message."
559   :version "21.1"
560   :group 'message-forwarding
561   :link '(custom-manual "(message)Forwarding")
562   :type 'boolean)
563
564 (defcustom message-forward-show-mml 'best
565   "*Non-nil means show forwarded messages as MML (decoded from MIME).
566 Otherwise, forwarded messages are unchanged.
567 Can also be the symbol `best' to indicate that MML should be
568 used, except when it is a bad idea to use MML.  One example where
569 it is a bad idea is when forwarding a signed or encrypted
570 message, because converting MIME to MML would invalidate the
571 digital signature."
572   :version "21.1"
573   :group 'message-forwarding
574   :type '(choice (const :tag "use MML" t)
575                  (const :tag "don't use MML " nil)
576                  (const :tag "use MML when appropriate" best)))
577
578 (defcustom message-forward-before-signature t
579   "*Non-nil means put forwarded message before signature, else after."
580   :group 'message-forwarding
581   :type 'boolean)
582
583 (defcustom message-wash-forwarded-subjects nil
584   "*Non-nil means try to remove as much cruft as possible from the subject.
585 Done before generating the new subject of a forward."
586   :group 'message-forwarding
587   :link '(custom-manual "(message)Forwarding")
588   :type 'boolean)
589
590 (defcustom message-ignored-resent-headers
591   ;; `Delivered-To' needs to be removed because some mailers use it to
592   ;; detect loops, so if you resend a message to an address that ultimately
593   ;; comes back to you (e.g. a mailing-list to which you subscribe, in which
594   ;; case you may be removed from the list on the grounds that mail to you
595   ;; bounced with a "mailing loop" error).
596   "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:\\|^>?From \\|^Delivered-To:"
597   "*All headers that match this regexp will be deleted when resending a message."
598   :group 'message-interface
599   :link '(custom-manual "(message)Resending")
600   :type '(repeat :value-to-internal (lambda (widget value)
601                                       (custom-split-regexp-maybe value))
602                  :match (lambda (widget value)
603                           (or (stringp value)
604                               (widget-editable-list-match widget value)))
605                  regexp))
606
607 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
608   "*All headers that match this regexp will be deleted when forwarding a message."
609   :version "21.1"
610   :group 'message-forwarding
611   :type '(repeat :value-to-internal (lambda (widget value)
612                                       (custom-split-regexp-maybe value))
613                  :match (lambda (widget value)
614                           (or (stringp value)
615                               (widget-editable-list-match widget value)))
616                  regexp))
617
618 (defcustom message-ignored-cited-headers "."
619   "*Delete these headers from the messages you yank."
620   :group 'message-insertion
621   :link '(custom-manual "(message)Insertion Variables")
622   :type 'regexp)
623
624 (defcustom message-cite-prefix-regexp
625   (if (string-match "[[:digit:]]" "1")
626       ;; Support POSIX?  XEmacs 21.5.27 doesn't.
627       "\\([ \t]*[_.[:word:]]+>+\\|[ \t]*[]>|}]\\)+"
628     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
629     (let (non-word-constituents)
630       (with-syntax-table text-mode-syntax-table
631         (setq non-word-constituents
632               (concat
633                (if (string-match "\\w" "_")  "" "_")
634                (if (string-match "\\w" ".")  "" "."))))
635       (if (equal non-word-constituents "")
636           "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>|}]\\)+"
637         (concat "\\([ \t]*\\(\\w\\|["
638                 non-word-constituents
639                 "]\\)+>+\\|[ \t]*[]>|}]\\)+"))))
640   "*Regexp matching the longest possible citation prefix on a line."
641   :version "23.2"
642   :group 'message-insertion
643   :link '(custom-manual "(message)Insertion Variables")
644   :type 'regexp
645   :set (lambda (symbol value)
646          (prog1
647              (custom-set-default symbol value)
648            (if (boundp 'gnus-message-cite-prefix-regexp)
649                (setq gnus-message-cite-prefix-regexp
650                      (concat "^\\(?:" value "\\)"))))))
651
652 (defcustom message-cancel-message "I am canceling my own article.\n"
653   "Message to be inserted in the cancel message."
654   :group 'message-interface
655   :link '(custom-manual "(message)Canceling News")
656   :type 'string)
657
658 (defun message-send-mail-function ()
659   "Return suitable value for the variable `message-send-mail-function'."
660   (cond ((and (require 'sendmail)
661               (boundp 'sendmail-program)
662               sendmail-program
663               (executable-find sendmail-program))
664          'message-send-mail-with-sendmail)
665         ((and (locate-library "smtpmail")
666               (boundp 'smtpmail-default-smtp-server)
667               smtpmail-default-smtp-server)
668          'message-smtpmail-send-it)
669         ((locate-library "mailclient")
670          'message-send-mail-with-mailclient)
671         (t
672          (error "Don't know how to send mail.  Please customize `message-send-mail-function'"))))
673
674 ;; Useful to set in site-init.el
675 (defcustom message-send-mail-function
676   (cond ((eq send-mail-function 'smtpmail-send-it) 'message-smtpmail-send-it)
677         ((eq send-mail-function 'feedmail-send-it) 'feedmail-send-it)
678         ((eq send-mail-function 'mailclient-send-it)
679          'message-send-mail-with-mailclient)
680         (t (message-send-mail-function)))
681   "Function to call to send the current buffer as mail.
682 The headers should be delimited by a line whose contents match the
683 variable `mail-header-separator'.
684
685 Valid values include `message-send-mail-with-sendmail'
686 `message-send-mail-with-mh', `message-send-mail-with-qmail',
687 `message-smtpmail-send-it', `smtpmail-send-it',
688 `feedmail-send-it' and `message-send-mail-with-mailclient'.  The
689 default is system dependent and determined by the function
690 `message-send-mail-function'.
691
692 See also `send-mail-function'."
693   :type '(radio (function-item message-send-mail-with-sendmail)
694                 (function-item message-send-mail-with-mh)
695                 (function-item message-send-mail-with-qmail)
696                 (function-item message-smtpmail-send-it)
697                 (function-item smtpmail-send-it)
698                 (function-item feedmail-send-it)
699                 (function-item message-send-mail-with-mailclient
700                                :tag "Use Mailclient package")
701                 (function :tag "Other"))
702   :group 'message-sending
703   :version "23.2"
704   :initialize 'custom-initialize-default
705   :link '(custom-manual "(message)Mail Variables")
706   :group 'message-mail)
707
708 (defcustom message-send-news-function 'message-send-news
709   "Function to call to send the current buffer as news.
710 The headers should be delimited by a line whose contents match the
711 variable `mail-header-separator'."
712   :group 'message-sending
713   :group 'message-news
714   :link '(custom-manual "(message)News Variables")
715   :type 'function)
716
717 (defcustom message-reply-to-function nil
718   "If non-nil, function that should return a list of headers.
719 This function should pick out addresses from the To, Cc, and From headers
720 and respond with new To and Cc headers."
721   :group 'message-interface
722   :link '(custom-manual "(message)Reply")
723   :type '(choice function (const nil)))
724
725 (defcustom message-wide-reply-to-function nil
726   "If non-nil, function that should return a list of headers.
727 This function should pick out addresses from the To, Cc, and From headers
728 and respond with new To and Cc headers."
729   :group 'message-interface
730   :link '(custom-manual "(message)Wide Reply")
731   :type '(choice function (const nil)))
732
733 (defcustom message-followup-to-function nil
734   "If non-nil, function that should return a list of headers.
735 This function should pick out addresses from the To, Cc, and From headers
736 and respond with new To and Cc headers."
737   :group 'message-interface
738   :link '(custom-manual "(message)Followup")
739   :type '(choice function (const nil)))
740
741 (defcustom message-extra-wide-headers nil
742   "If non-nil, a list of additional address headers.
743 These are used when composing a wide reply."
744   :group 'message-sending
745   :type '(repeat string))
746
747 (defcustom message-use-followup-to 'ask
748   "*Specifies what to do with Followup-To header.
749 If nil, always ignore the header.  If it is t, use its value, but
750 query before using the \"poster\" value.  If it is the symbol `ask',
751 always query the user whether to use the value.  If it is the symbol
752 `use', always use the value."
753   :group 'message-interface
754   :link '(custom-manual "(message)Followup")
755   :type '(choice (const :tag "ignore" nil)
756                  (const :tag "use & query" t)
757                  (const use)
758                  (const ask)))
759
760 (defcustom message-use-mail-followup-to 'use
761   "*Specifies what to do with Mail-Followup-To header.
762 If nil, always ignore the header.  If it is the symbol `ask', always
763 query the user whether to use the value.  If it is the symbol `use',
764 always use the value."
765   :version "22.1"
766   :group 'message-interface
767   :link '(custom-manual "(message)Mailing Lists")
768   :type '(choice (const :tag "ignore" nil)
769                  (const use)
770                  (const ask)))
771
772 (defcustom message-subscribed-address-functions nil
773   "*Specifies functions for determining list subscription.
774 If nil, do not attempt to determine list subscription with functions.
775 If non-nil, this variable contains a list of functions which return
776 regular expressions to match lists.  These functions can be used in
777 conjunction with `message-subscribed-regexps' and
778 `message-subscribed-addresses'."
779   :version "22.1"
780   :group 'message-interface
781   :link '(custom-manual "(message)Mailing Lists")
782   :type '(repeat sexp))
783
784 (defcustom message-subscribed-address-file nil
785   "*A file containing addresses the user is subscribed to.
786 If nil, do not look at any files to determine list subscriptions.  If
787 non-nil, each line of this file should be a mailing list address."
788   :version "22.1"
789   :group 'message-interface
790   :link '(custom-manual "(message)Mailing Lists")
791   :type '(radio file (const nil)))
792
793 (defcustom message-subscribed-addresses nil
794   "*Specifies a list of addresses the user is subscribed to.
795 If nil, do not use any predefined list subscriptions.  This list of
796 addresses can be used in conjunction with
797 `message-subscribed-address-functions' and `message-subscribed-regexps'."
798   :version "22.1"
799   :group 'message-interface
800   :link '(custom-manual "(message)Mailing Lists")
801   :type '(repeat string))
802
803 (defcustom message-subscribed-regexps nil
804   "*Specifies a list of addresses the user is subscribed to.
805 If nil, do not use any predefined list subscriptions.  This list of
806 regular expressions can be used in conjunction with
807 `message-subscribed-address-functions' and `message-subscribed-addresses'."
808   :version "22.1"
809   :group 'message-interface
810   :link '(custom-manual "(message)Mailing Lists")
811   :type '(repeat regexp))
812
813 (defcustom message-allow-no-recipients 'ask
814   "Specifies what to do when there are no recipients other than Gcc/Fcc.
815 If it is the symbol `always', the posting is allowed.  If it is the
816 symbol `never', the posting is not allowed.  If it is the symbol
817 `ask', you are prompted."
818   :version "22.1"
819   :group 'message-interface
820   :link '(custom-manual "(message)Message Headers")
821   :type '(choice (const always)
822                  (const never)
823                  (const ask)))
824
825 (defcustom message-sendmail-f-is-evil nil
826   "*Non-nil means don't add \"-f username\" to the sendmail command line.
827 Doing so would be even more evil than leaving it out."
828   :group 'message-sending
829   :link '(custom-manual "(message)Mail Variables")
830   :type 'boolean)
831
832 (defcustom message-sendmail-envelope-from nil
833   "*Envelope-from when sending mail with sendmail.
834 If this is nil, use `user-mail-address'.  If it is the symbol
835 `header', use the From: header of the message."
836   :version "23.2"
837   :type '(choice (string :tag "From name")
838                  (const :tag "Use From: header from message" header)
839                  (const :tag "Use `user-mail-address'" nil))
840   :link '(custom-manual "(message)Mail Variables")
841   :group 'message-sending)
842
843 (defcustom message-sendmail-extra-arguments nil
844   "Additional arguments to `sendmail-program'."
845   ;; E.g. '("-a" "account") for msmtp
846   :version "23.1" ;; No Gnus
847   :type '(repeat string)
848   ;; :link '(custom-manual "(message)Mail Variables")
849   :group 'message-sending)
850
851 ;; qmail-related stuff
852 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
853   "Location of the qmail-inject program."
854   :group 'message-sending
855   :link '(custom-manual "(message)Mail Variables")
856   :type 'file)
857
858 (defcustom message-qmail-inject-args nil
859   "Arguments passed to qmail-inject programs.
860 This should be a list of strings, one string for each argument.
861 It may also be a function.
862
863 For e.g., if you wish to set the envelope sender address so that bounces
864 go to the right place or to deal with listserv's usage of that address, you
865 might set this variable to '(\"-f\" \"you@some.where\")."
866   :group 'message-sending
867   :link '(custom-manual "(message)Mail Variables")
868   :type '(choice (function)
869                  (repeat string)))
870
871 (defvar gnus-post-method)
872 (defvar gnus-select-method)
873 (defcustom message-post-method
874   (cond ((and (boundp 'gnus-post-method)
875               (listp gnus-post-method)
876               gnus-post-method)
877          gnus-post-method)
878         ((boundp 'gnus-select-method)
879          gnus-select-method)
880         (t '(nnspool "")))
881   "*Method used to post news.
882 Note that when posting from inside Gnus, for instance, this
883 variable isn't used."
884   :group 'message-news
885   :group 'message-sending
886   ;; This should be the `gnus-select-method' widget, but that might
887   ;; create a dependence to `gnus.el'.
888   :type 'sexp)
889
890 ;; FIXME: This should be a temporary workaround until someone implements a
891 ;; proper solution.  If a crash happens while replying, the auto-save file
892 ;; will *not* have a `References:' header if `message-generate-headers-first'
893 ;; is nil.  See: http://article.gmane.org/gmane.emacs.gnus.general/51138
894 (defcustom message-generate-headers-first '(references)
895   "Which headers should be generated before starting to compose a message.
896 If t, generate all required headers.  This can also be a list of headers to
897 generate.  The variables `message-required-news-headers' and
898 `message-required-mail-headers' specify which headers to generate.
899
900 Note that the variable `message-deletable-headers' specifies headers which
901 are to be deleted and then re-generated before sending, so this variable
902 will not have a visible effect for those headers."
903   :group 'message-headers
904   :link '(custom-manual "(message)Message Headers")
905   :type '(choice (const :tag "None" nil)
906                  (const :tag "References" '(references))
907                  (const :tag "All" t)
908                  (repeat (sexp :tag "Header"))))
909
910 (defcustom message-fill-column 72
911   "Column beyond which automatic line-wrapping should happen.
912 Local value for message buffers.  If non-nil, also turn on
913 auto-fill in message buffers."
914   :group 'message-various
915   ;; :link '(custom-manual "(message)Message Headers")
916   :type '(choice (const :tag "Don't turn on auto fill" nil)
917                  (integer)))
918
919 (defcustom message-setup-hook nil
920   "Normal hook, run each time a new outgoing message is initialized.
921 The function `message-setup' runs this hook."
922   :group 'message-various
923   :link '(custom-manual "(message)Various Message Variables")
924   :type 'hook)
925
926 (defcustom message-cancel-hook nil
927   "Hook run when cancelling articles."
928   :group 'message-various
929   :link '(custom-manual "(message)Various Message Variables")
930   :type 'hook)
931
932 (defcustom message-signature-setup-hook nil
933   "Normal hook, run each time a new outgoing message is initialized.
934 It is run after the headers have been inserted and before
935 the signature is inserted."
936   :group 'message-various
937   :link '(custom-manual "(message)Various Message Variables")
938   :type 'hook)
939
940 (defcustom message-mode-hook nil
941   "Hook run in message mode buffers."
942   :group 'message-various
943   :type 'hook)
944
945 (defcustom message-header-hook nil
946   "Hook run in a message mode buffer narrowed to the headers."
947   :group 'message-various
948   :type 'hook)
949
950 (defcustom message-header-setup-hook nil
951   "Hook called narrowed to the headers when setting up a message buffer."
952   :group 'message-various
953   :link '(custom-manual "(message)Various Message Variables")
954   :type 'hook)
955
956 (defcustom message-minibuffer-local-map
957   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
958     (set-keymap-parent map minibuffer-local-map)
959     map)
960   "Keymap for `message-read-from-minibuffer'."
961   :version "22.1"
962   :group 'message-various)
963
964 (defcustom message-citation-line-function 'message-insert-citation-line
965   "*Function called to insert the \"Whomever writes:\" line.
966
967 Predefined functions include `message-insert-citation-line' and
968 `message-insert-formatted-citation-line' (see the variable
969 `message-citation-line-format').
970
971 Note that Gnus provides a feature where the reader can click on
972 `writes:' to hide the cited text.  If you change this line too much,
973 people who read your message will have to change their Gnus
974 configuration.  See the variable `gnus-cite-attribution-suffix'."
975   :type '(choice
976           (function-item :tag "plain" message-insert-citation-line)
977           (function-item :tag "formatted" message-insert-formatted-citation-line)
978           (function :tag "Other"))
979   :link '(custom-manual "(message)Insertion Variables")
980   :group 'message-insertion)
981
982 (defcustom message-citation-line-format "On %a, %b %d %Y, %N wrote:\n"
983   "Format of the \"Whomever writes:\" line.
984
985 The string is formatted using `format-spec'.  The following
986 constructs are replaced:
987
988   %f   The full From, e.g. \"John Doe <john.doe@example.invalid>\".
989   %n   The mail address, e.g. \"john.doe@example.invalid\".
990   %N   The real name if present, e.g.: \"John Doe\", else fall
991        back to the mail address.
992   %F   The first name if present, e.g.: \"John\".
993   %L   The last name if present, e.g.: \"Doe\".
994
995 All other format specifiers are passed to `format-time-string'
996 which is called using the date from the article your replying to.
997 Extracting the first (%F) and last name (%L) is done
998 heuristically, so you should always check it yourself.
999
1000 Please also read the note in the documentation of
1001 `message-citation-line-function'."
1002   :type '(choice (const :tag "Plain" "%f writes:")
1003                  (const :tag "Include date" "On %a, %b %d %Y, %n wrote:")
1004                  string)
1005   :link '(custom-manual "(message)Insertion Variables")
1006   :version "23.1" ;; No Gnus
1007   :group 'message-insertion)
1008
1009 (defcustom message-yank-prefix "> "
1010   "*Prefix inserted on the lines of yanked messages.
1011 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
1012 See also `message-yank-cited-prefix' and `message-yank-empty-prefix'."
1013   :version "23.2"
1014   :type 'string
1015   :link '(custom-manual "(message)Insertion Variables")
1016   :group 'message-insertion)
1017
1018 (defcustom message-yank-cited-prefix ">"
1019   "*Prefix inserted on cited lines of yanked messages.
1020 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
1021 See also `message-yank-prefix' and `message-yank-empty-prefix'."
1022   :version "22.1"
1023   :type 'string
1024   :link '(custom-manual "(message)Insertion Variables")
1025   :group 'message-insertion)
1026
1027 (defcustom message-yank-empty-prefix ">"
1028   "*Prefix inserted on empty lines of yanked messages.
1029 See also `message-yank-prefix' and `message-yank-cited-prefix'."
1030   :version "22.1"
1031   :type 'string
1032   :link '(custom-manual "(message)Insertion Variables")
1033   :group 'message-insertion)
1034
1035 (defcustom message-indentation-spaces 3
1036   "*Number of spaces to insert at the beginning of each cited line.
1037 Used by `message-yank-original' via `message-yank-cite'."
1038   :version "23.2"
1039   :group 'message-insertion
1040   :link '(custom-manual "(message)Insertion Variables")
1041   :type 'integer)
1042
1043 (defcustom message-cite-function 'message-cite-original-without-signature
1044   "*Function for citing an original message.
1045 Predefined functions include `message-cite-original' and
1046 `message-cite-original-without-signature'.
1047 Note that these functions use `mail-citation-hook' if that is non-nil."
1048   :type '(radio (function-item message-cite-original)
1049                 (function-item message-cite-original-without-signature)
1050                 (function-item sc-cite-original)
1051                 (function :tag "Other"))
1052   :link '(custom-manual "(message)Insertion Variables")
1053   :version "22.3" ;; Gnus 5.10.12 (changed default)
1054   :group 'message-insertion)
1055
1056 (defcustom message-indent-citation-function 'message-indent-citation
1057   "*Function for modifying a citation just inserted in the mail buffer.
1058 This can also be a list of functions.  Each function can find the
1059 citation between (point) and (mark t).  And each function should leave
1060 point and mark around the citation text as modified."
1061   :type 'function
1062   :link '(custom-manual "(message)Insertion Variables")
1063   :group 'message-insertion)
1064
1065 (defcustom message-signature t
1066   "*String to be inserted at the end of the message buffer.
1067 If t, the `message-signature-file' file will be inserted instead.
1068 If a function, the result from the function will be used instead.
1069 If a form, the result from the form will be used instead."
1070   :version "23.2"
1071   :type 'sexp
1072   :link '(custom-manual "(message)Insertion Variables")
1073   :group 'message-insertion)
1074
1075 (defcustom message-signature-file "~/.signature"
1076   "*Name of file containing the text inserted at end of message buffer.
1077 Ignored if the named file doesn't exist.
1078 If nil, don't insert a signature.
1079 If a path is specified, the value of `message-signature-directory' is ignored,
1080 even if set."
1081   :version "23.2"
1082   :type '(choice file (const :tags "None" nil))
1083   :link '(custom-manual "(message)Insertion Variables")
1084   :group 'message-insertion)
1085
1086 (defcustom message-signature-directory nil
1087   "*Name of directory containing signature files.
1088 Comes in handy if you have many such files, handled via posting styles for
1089 instance.
1090 If nil, `message-signature-file' is expected to specify the directory if
1091 needed."
1092   :type '(choice string (const :tags "None" nil))
1093   :link '(custom-manual "(message)Insertion Variables")
1094   :group 'message-insertion)
1095
1096 (defcustom message-signature-insert-empty-line t
1097   "*If non-nil, insert an empty line before the signature separator."
1098   :version "22.1"
1099   :type 'boolean
1100   :link '(custom-manual "(message)Insertion Variables")
1101   :group 'message-insertion)
1102
1103 (defcustom message-distribution-function nil
1104   "*Function called to return a Distribution header."
1105   :group 'message-news
1106   :group 'message-headers
1107   :link '(custom-manual "(message)News Headers")
1108   :type '(choice function (const nil)))
1109
1110 (defcustom message-expires 14
1111   "Number of days before your article expires."
1112   :group 'message-news
1113   :group 'message-headers
1114   :link '(custom-manual "(message)News Headers")
1115   :type 'integer)
1116
1117 (defcustom message-user-path nil
1118   "If nil, use the NNTP server name in the Path header.
1119 If stringp, use this; if non-nil, use no host name (user name only)."
1120   :group 'message-news
1121   :group 'message-headers
1122   :link '(custom-manual "(message)News Headers")
1123   :type '(choice (const :tag "nntp" nil)
1124                  (string :tag "name")
1125                  (sexp :tag "none" :format "%t" t)))
1126
1127 ;; This can be the name of a buffer, or a cons cell (FUNCTION . ARGS)
1128 ;; for yanking the original buffer.
1129 (defvar message-reply-buffer nil)
1130 (defvar message-reply-headers nil
1131   "The headers of the current replied article.
1132 It is a vector of the following headers:
1133 \[number subject from date id references chars lines xref extra].")
1134 (defvar message-newsreader nil)
1135 (defvar message-mailer nil)
1136 (defvar message-sent-message-via nil)
1137 (defvar message-checksum nil)
1138 (defvar message-send-actions nil
1139   "A list of actions to be performed upon successful sending of a message.")
1140 (defvar message-exit-actions nil
1141   "A list of actions to be performed upon exiting after sending a message.")
1142 (defvar message-kill-actions nil
1143   "A list of actions to be performed before killing a message buffer.")
1144 (defvar message-postpone-actions nil
1145   "A list of actions to be performed after postponing a message.")
1146
1147 (define-widget 'message-header-lines 'text
1148   "All header lines must be LFD terminated."
1149   :format "%{%t%}:%n%v"
1150   :valid-regexp "^\\'"
1151   :error "All header lines must be newline terminated")
1152
1153 (defcustom message-default-headers ""
1154   "*A string containing header lines to be inserted in outgoing messages.
1155 It is inserted before you edit the message, so you can edit or delete
1156 these lines."
1157   :version "23.2"
1158   :group 'message-headers
1159   :link '(custom-manual "(message)Message Headers")
1160   :type 'message-header-lines)
1161
1162 (defcustom message-default-mail-headers
1163   ;; Ease the transition from mail-mode to message-mode.  See bugs#4431, 5555.
1164   (concat (if (and (boundp 'mail-default-reply-to)
1165                    (stringp mail-default-reply-to))
1166               (format "Reply-to: %s\n" mail-default-reply-to))
1167           (if (and (boundp 'mail-self-blind)
1168                    mail-self-blind)
1169               (format "BCC: %s\n" user-mail-address))
1170           (if (and (boundp 'mail-archive-file-name)
1171                    (stringp mail-archive-file-name))
1172               (format "FCC: %s\n" mail-archive-file-name))
1173           ;; Use the value of `mail-default-headers' if available.
1174           ;; Note: as for Emacs 21, XEmacs 21.4 and 21.5, it is
1175           ;; unavailable unless sendmail.el is loaded.
1176           (if (boundp 'mail-default-headers)
1177               mail-default-headers))
1178   "*A string of header lines to be inserted in outgoing mails."
1179   :version "23.2"
1180   :group 'message-headers
1181   :group 'message-mail
1182   :link '(custom-manual "(message)Mail Headers")
1183   :type 'message-header-lines)
1184
1185 (defcustom message-default-news-headers ""
1186   "*A string of header lines to be inserted in outgoing news articles."
1187   :group 'message-headers
1188   :group 'message-news
1189   :link '(custom-manual "(message)News Headers")
1190   :type 'message-header-lines)
1191
1192 ;; Note: could use /usr/ucb/mail instead of sendmail;
1193 ;; options -t, and -v if not interactive.
1194 (defcustom message-mailer-swallows-blank-line
1195   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
1196                          system-configuration)
1197            (file-readable-p "/etc/sendmail.cf")
1198            (let ((buffer (get-buffer-create " *temp*")))
1199              (unwind-protect
1200                  (with-current-buffer buffer
1201                    (insert-file-contents "/etc/sendmail.cf")
1202                    (goto-char (point-min))
1203                    (let ((case-fold-search nil))
1204                      (re-search-forward "^OR\\>" nil t)))
1205                (kill-buffer buffer))))
1206       ;; According to RFC822, "The field-name must be composed of printable
1207       ;; ASCII characters (i. e., characters that have decimal values between
1208       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
1209       ;; space, or colon.
1210       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
1211   "*Set this non-nil if the system's mailer runs the header and body together.
1212 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
1213 The value should be an expression to test whether the problem will
1214 actually occur."
1215   :group 'message-sending
1216   :link '(custom-manual "(message)Mail Variables")
1217   :type 'sexp)
1218
1219 ;;;###autoload
1220 (define-mail-user-agent 'message-user-agent
1221   'message-mail 'message-send-and-exit
1222   'message-kill-buffer 'message-send-hook)
1223
1224 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
1225   "If non-nil, delete the deletable headers before feeding to mh.")
1226
1227 (defvar message-send-method-alist
1228   '((news message-news-p message-send-via-news)
1229     (mail message-mail-p message-send-via-mail))
1230   "Alist of ways to send outgoing messages.
1231 Each element has the form
1232
1233   \(TYPE PREDICATE FUNCTION)
1234
1235 where TYPE is a symbol that names the method; PREDICATE is a function
1236 called without any parameters to determine whether the message is
1237 a message of type TYPE; and FUNCTION is a function to be called if
1238 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
1239 the prefix.")
1240
1241 (defcustom message-mail-alias-type 'abbrev
1242   "*What alias expansion type to use in Message buffers.
1243 The default is `abbrev', which uses mailabbrev.  `ecomplete' uses
1244 an electric completion mode.  nil switches mail aliases off.
1245 This can also be a list of values."
1246   :group 'message
1247   :link '(custom-manual "(message)Mail Aliases")
1248   :type '(choice (const :tag "Use Mailabbrev" abbrev)
1249                  (const :tag "Use ecomplete" ecomplete)
1250                  (const :tag "No expansion" nil)))
1251
1252 (defcustom message-self-insert-commands '(self-insert-command)
1253   "List of `self-insert-command's used to trigger ecomplete.
1254 When one of those commands is invoked to enter a character in To or Cc
1255 header, ecomplete will suggest the candidates of recipients (see also
1256 `message-mail-alias-type').  If you use some tool to enter non-ASCII
1257 text and it replaces `self-insert-command' with the other command, e.g.
1258 `egg-self-insert-command', you may want to add it to this list."
1259   :group 'message-various
1260   :type '(repeat function))
1261
1262 (defcustom message-auto-save-directory
1263   (file-name-as-directory (expand-file-name "drafts" message-directory))
1264   "*Directory where Message auto-saves buffers if Gnus isn't running.
1265 If nil, Message won't auto-save."
1266   :group 'message-buffers
1267   :link '(custom-manual "(message)Various Message Variables")
1268   :type '(choice directory (const :tag "Don't auto-save" nil)))
1269
1270 (defcustom message-default-charset
1271   (and (not (mm-multibyte-p)) 'iso-8859-1)
1272   "Default charset used in non-MULE Emacsen.
1273 If nil, you might be asked to input the charset."
1274   :version "21.1"
1275   :group 'message
1276   :link '(custom-manual "(message)Various Message Variables")
1277   :type 'symbol)
1278
1279 (defcustom message-dont-reply-to-names
1280   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
1281   "*Addresses to prune when doing wide replies.
1282 This can be a regexp or a list of regexps.  Also, a value of nil means
1283 exclude your own user name only."
1284   :version "21.1"
1285   :group 'message
1286   :link '(custom-manual "(message)Wide Reply")
1287   :type '(choice (const :tag "Yourself" nil)
1288                  regexp
1289                  (repeat :tag "Regexp List" regexp)))
1290
1291 (defsubst message-dont-reply-to-names ()
1292   (gmm-regexp-concat message-dont-reply-to-names))
1293
1294 (defvar message-shoot-gnksa-feet nil
1295   "*A list of GNKSA feet you are allowed to shoot.
1296 Gnus gives you all the opportunity you could possibly want for
1297 shooting yourself in the foot.  Also, Gnus allows you to shoot the
1298 feet of Good Net-Keeping Seal of Approval.  The following are foot
1299 candidates:
1300 `empty-article'     Allow you to post an empty article;
1301 `quoted-text-only'  Allow you to post quoted text only;
1302 `multiple-copies'   Allow you to post multiple copies;
1303 `cancel-messages'   Allow you to cancel or supersede messages from
1304                     your other email addresses.")
1305
1306 (defsubst message-gnksa-enable-p (feature)
1307   (or (not (listp message-shoot-gnksa-feet))
1308       (memq feature message-shoot-gnksa-feet)))
1309
1310 (defcustom message-hidden-headers '("^References:" "^Face:" "^X-Face:"
1311                                     "^X-Draft-From:")
1312   "Regexp of headers to be hidden when composing new messages.
1313 This can also be a list of regexps to match headers.  Or a list
1314 starting with `not' and followed by regexps."
1315   :version "22.1"
1316   :group 'message
1317   :link '(custom-manual "(message)Message Headers")
1318   :type '(choice
1319           :format "%{%t%}: %[Value Type%] %v"
1320           (regexp :menu-tag "regexp" :format "regexp\n%t: %v")
1321           (repeat :menu-tag "(regexp ...)" :format "(regexp ...)\n%v%i"
1322                   (regexp :format "%t: %v"))
1323           (cons :menu-tag "(not regexp ...)" :format "(not regexp ...)\n%v"
1324                 (const not)
1325                 (repeat :format "%v%i"
1326                         (regexp :format "%t: %v")))))
1327
1328 (defcustom message-cite-articles-with-x-no-archive t
1329   "If non-nil, cite text from articles that has X-No-Archive set."
1330   :group 'message
1331   :type 'boolean)
1332
1333 ;;; Internal variables.
1334 ;;; Well, not really internal.
1335
1336 (defvar message-mode-syntax-table
1337   (let ((table (copy-syntax-table text-mode-syntax-table)))
1338     (modify-syntax-entry ?% ". " table)
1339     (modify-syntax-entry ?> ". " table)
1340     (modify-syntax-entry ?< ". " table)
1341     table)
1342   "Syntax table used while in Message mode.")
1343
1344 (defface message-header-to
1345   '((((class color)
1346       (background dark))
1347      (:foreground "DarkOliveGreen1" :bold t))
1348     (((class color)
1349       (background light))
1350      (:foreground "MidnightBlue" :bold t))
1351     (t
1352      (:bold t :italic t)))
1353   "Face used for displaying From headers."
1354   :group 'message-faces)
1355 ;; backward-compatibility alias
1356 (put 'message-header-to-face 'face-alias 'message-header-to)
1357 (put 'message-header-to-face 'obsolete-face "22.1")
1358
1359 (defface message-header-cc
1360   '((((class color)
1361       (background dark))
1362      (:foreground "chartreuse1" :bold t))
1363     (((class color)
1364       (background light))
1365      (:foreground "MidnightBlue"))
1366     (t
1367      (:bold t)))
1368   "Face used for displaying Cc headers."
1369   :group 'message-faces)
1370 ;; backward-compatibility alias
1371 (put 'message-header-cc-face 'face-alias 'message-header-cc)
1372 (put 'message-header-cc-face 'obsolete-face "22.1")
1373
1374 (defface message-header-subject
1375   '((((class color)
1376       (background dark))
1377      (:foreground "OliveDrab1"))
1378     (((class color)
1379       (background light))
1380      (:foreground "navy blue" :bold t))
1381     (t
1382      (:bold t)))
1383   "Face used for displaying subject headers."
1384   :group 'message-faces)
1385 ;; backward-compatibility alias
1386 (put 'message-header-subject-face 'face-alias 'message-header-subject)
1387 (put 'message-header-subject-face 'obsolete-face "22.1")
1388
1389 (defface message-header-newsgroups
1390   '((((class color)
1391       (background dark))
1392      (:foreground "yellow" :bold t :italic t))
1393     (((class color)
1394       (background light))
1395      (:foreground "blue4" :bold t :italic t))
1396     (t
1397      (:bold t :italic t)))
1398   "Face used for displaying newsgroups headers."
1399   :group 'message-faces)
1400 ;; backward-compatibility alias
1401 (put 'message-header-newsgroups-face 'face-alias 'message-header-newsgroups)
1402 (put 'message-header-newsgroups-face 'obsolete-face "22.1")
1403
1404 (defface message-header-other
1405   '((((class color)
1406       (background dark))
1407      (:foreground "VioletRed1"))
1408     (((class color)
1409       (background light))
1410      (:foreground "steel blue"))
1411     (t
1412      (:bold t :italic t)))
1413   "Face used for displaying newsgroups headers."
1414   :group 'message-faces)
1415 ;; backward-compatibility alias
1416 (put 'message-header-other-face 'face-alias 'message-header-other)
1417 (put 'message-header-other-face 'obsolete-face "22.1")
1418
1419 (defface message-header-name
1420   '((((class color)
1421       (background dark))
1422      (:foreground "green"))
1423     (((class color)
1424       (background light))
1425      (:foreground "cornflower blue"))
1426     (t
1427      (:bold t)))
1428   "Face used for displaying header names."
1429   :group 'message-faces)
1430 ;; backward-compatibility alias
1431 (put 'message-header-name-face 'face-alias 'message-header-name)
1432 (put 'message-header-name-face 'obsolete-face "22.1")
1433
1434 (defface message-header-xheader
1435   '((((class color)
1436       (background dark))
1437      (:foreground "DeepSkyBlue1"))
1438     (((class color)
1439       (background light))
1440      (:foreground "blue"))
1441     (t
1442      (:bold t)))
1443   "Face used for displaying X-Header headers."
1444   :group 'message-faces)
1445 ;; backward-compatibility alias
1446 (put 'message-header-xheader-face 'face-alias 'message-header-xheader)
1447 (put 'message-header-xheader-face 'obsolete-face "22.1")
1448
1449 (defface message-separator
1450   '((((class color)
1451       (background dark))
1452      (:foreground "LightSkyBlue1"))
1453     (((class color)
1454       (background light))
1455      (:foreground "brown"))
1456     (t
1457      (:bold t)))
1458   "Face used for displaying the separator."
1459   :group 'message-faces)
1460 ;; backward-compatibility alias
1461 (put 'message-separator-face 'face-alias 'message-separator)
1462 (put 'message-separator-face 'obsolete-face "22.1")
1463
1464 (defface message-cited-text
1465   '((((class color)
1466       (background dark))
1467      (:foreground "LightPink1"))
1468     (((class color)
1469       (background light))
1470      (:foreground "red"))
1471     (t
1472      (:bold t)))
1473   "Face used for displaying cited text names."
1474   :group 'message-faces)
1475 ;; backward-compatibility alias
1476 (put 'message-cited-text-face 'face-alias 'message-cited-text)
1477 (put 'message-cited-text-face 'obsolete-face "22.1")
1478
1479 (defface message-mml
1480   '((((class color)
1481       (background dark))
1482      (:foreground "MediumSpringGreen"))
1483     (((class color)
1484       (background light))
1485      (:foreground "ForestGreen"))
1486     (t
1487      (:bold t)))
1488   "Face used for displaying MML."
1489   :group 'message-faces)
1490 ;; backward-compatibility alias
1491 (put 'message-mml-face 'face-alias 'message-mml)
1492 (put 'message-mml-face 'obsolete-face "22.1")
1493
1494 (defun message-font-lock-make-header-matcher (regexp)
1495   (let ((form
1496          `(lambda (limit)
1497             (let ((start (point)))
1498               (save-restriction
1499                 (widen)
1500                 (goto-char (point-min))
1501                 (if (re-search-forward
1502                      (concat "^" (regexp-quote mail-header-separator) "$")
1503                      nil t)
1504                     (setq limit (min limit (match-beginning 0))))
1505                 (goto-char start))
1506               (and (< start limit)
1507                    (re-search-forward ,regexp limit t))))))
1508     (if (featurep 'bytecomp)
1509         (byte-compile form)
1510       form)))
1511
1512 (defvar message-font-lock-keywords
1513   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1514     `((,(message-font-lock-make-header-matcher
1515          (concat "^\\([Tt]o:\\)" content))
1516        (1 'message-header-name)
1517        (2 'message-header-to nil t))
1518       (,(message-font-lock-make-header-matcher
1519          (concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content))
1520        (1 'message-header-name)
1521        (2 'message-header-cc nil t))
1522       (,(message-font-lock-make-header-matcher
1523          (concat "^\\([Ss]ubject:\\)" content))
1524        (1 'message-header-name)
1525        (2 'message-header-subject nil t))
1526       (,(message-font-lock-make-header-matcher
1527          (concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content))
1528        (1 'message-header-name)
1529        (2 'message-header-newsgroups nil t))
1530       (,(message-font-lock-make-header-matcher
1531          (concat "^\\(X-[A-Za-z0-9-]+:\\|In-Reply-To:\\)" content))
1532        (1 'message-header-name)
1533        (2 'message-header-xheader))
1534       (,(message-font-lock-make-header-matcher
1535          (concat "^\\([A-Z][^: \n\t]+:\\)" content))
1536        (1 'message-header-name)
1537        (2 'message-header-other nil t))
1538       ,@(if (and mail-header-separator
1539                  (not (equal mail-header-separator "")))
1540             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1541                1 'message-separator))
1542           nil)
1543       ((lambda (limit)
1544          (re-search-forward (concat "^\\("
1545                                     message-cite-prefix-regexp
1546                                     "\\).*")
1547                             limit t))
1548        (0 'message-cited-text))
1549       ("<#/?\\(multipart\\|part\\|external\\|mml\\|secure\\)[^>]*>"
1550        (0 'message-mml))))
1551   "Additional expressions to highlight in Message mode.")
1552
1553
1554 ;; XEmacs does it like this.  For Emacs, we have to set the
1555 ;; `font-lock-defaults' buffer-local variable.
1556 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
1557
1558 (defvar message-face-alist
1559   '((bold . message-bold-region)
1560     (underline . underline-region)
1561     (default . (lambda (b e)
1562                  (message-unbold-region b e)
1563                  (ununderline-region b e))))
1564   "Alist of mail and news faces for facemenu.
1565 The cdr of each entry is a function for applying the face to a region.")
1566
1567 (defcustom message-send-hook nil
1568   "Hook run before sending messages.
1569 This hook is run quite early when sending."
1570   :group 'message-various
1571   :options '(ispell-message)
1572   :link '(custom-manual "(message)Various Message Variables")
1573   :type 'hook)
1574
1575 (defcustom message-send-mail-hook nil
1576   "Hook run before sending mail messages.
1577 This hook is run very late -- just before the message is sent as
1578 mail."
1579   :group 'message-various
1580   :link '(custom-manual "(message)Various Message Variables")
1581   :type 'hook)
1582
1583 (defcustom message-send-news-hook nil
1584   "Hook run before sending news messages.
1585 This hook is run very late -- just before the message is sent as
1586 news."
1587   :group 'message-various
1588   :link '(custom-manual "(message)Various Message Variables")
1589   :type 'hook)
1590
1591 (defcustom message-sent-hook nil
1592   "Hook run after sending messages."
1593   :group 'message-various
1594   :type 'hook)
1595
1596 (defvar message-send-coding-system 'binary
1597   "Coding system to encode outgoing mail.")
1598
1599 (defvar message-draft-coding-system
1600   mm-auto-save-coding-system
1601   "*Coding system to compose mail.
1602 If you'd like to make it possible to share draft files between XEmacs
1603 and Emacs, you may use `iso-2022-7bit' for this value at your own risk.
1604 Note that the coding-system `iso-2022-7bit' isn't suitable to all data.")
1605
1606 (defcustom message-send-mail-partially-limit nil
1607   "The limitation of messages sent as message/partial.
1608 The lower bound of message size in characters, beyond which the message
1609 should be sent in several parts.  If it is nil, the size is unlimited."
1610   :version "24.1"
1611   :group 'message-buffers
1612   :link '(custom-manual "(message)Mail Variables")
1613   :type '(choice (const :tag "unlimited" nil)
1614                  (integer 1000000)))
1615
1616 (defcustom message-alternative-emails nil
1617   "*Regexp matching alternative email addresses.
1618 The first address in the To, Cc or From headers of the original
1619 article matching this variable is used as the From field of
1620 outgoing messages.
1621
1622 This variable has precedence over posting styles and anything that runs
1623 off `message-setup-hook'."
1624   :group 'message-headers
1625   :link '(custom-manual "(message)Message Headers")
1626   :type '(choice (const :tag "Always use primary" nil)
1627                  regexp))
1628
1629 (defcustom message-hierarchical-addresses nil
1630   "A list of hierarchical mail address definitions.
1631
1632 Inside each entry, the first address is the \"top\" address, and
1633 subsequent addresses are subaddresses; this is used to indicate that
1634 mail sent to the first address will automatically be delivered to the
1635 subaddresses.  So if the first address appears in the recipient list
1636 for a message, the subaddresses will be removed (if present) before
1637 the mail is sent.  All addresses in this structure should be
1638 downcased."
1639   :version "22.1"
1640   :group 'message-headers
1641   :type '(repeat (repeat string)))
1642
1643 (defcustom message-mail-user-agent nil
1644   "Like `mail-user-agent'.
1645 Except if it is nil, use Gnus native MUA; if it is t, use
1646 `mail-user-agent'."
1647   :version "22.1"
1648   :type '(radio (const :tag "Gnus native"
1649                        :format "%t\n"
1650                        nil)
1651                 (const :tag "`mail-user-agent'"
1652                        :format "%t\n"
1653                        t)
1654                 (function-item :tag "Default Emacs mail"
1655                                :format "%t\n"
1656                                sendmail-user-agent)
1657                 (function-item :tag "Emacs interface to MH"
1658                                :format "%t\n"
1659                                mh-e-user-agent)
1660                 (function :tag "Other"))
1661   :version "21.1"
1662   :group 'message)
1663
1664 (defcustom message-wide-reply-confirm-recipients nil
1665   "Whether to confirm a wide reply to multiple email recipients.
1666 If this variable is nil, don't ask whether to reply to all recipients.
1667 If this variable is non-nil, pose the question \"Reply to all
1668 recipients?\" before a wide reply to multiple recipients.  If the user
1669 answers yes, reply to all recipients as usual.  If the user answers
1670 no, only reply back to the author."
1671   :version "22.1"
1672   :group 'message-headers
1673   :link '(custom-manual "(message)Wide Reply")
1674   :type 'boolean)
1675
1676 (defcustom message-user-fqdn nil
1677   "*Domain part of Message-Ids."
1678   :version "22.1"
1679   :group 'message-headers
1680   :link '(custom-manual "(message)News Headers")
1681   :type '(radio (const :format "%v  " nil)
1682                 (string :format "FQDN: %v")))
1683
1684 (defcustom message-use-idna (and (condition-case nil (require 'idna)
1685                                    (file-error))
1686                                  (mm-coding-system-p 'utf-8)
1687                                  (executable-find idna-program)
1688                                  (string= (idna-to-ascii "räksmörgÃ¥s")
1689                                           "xn--rksmrgs-5wao1o")
1690                                  t)
1691   "Whether to encode non-ASCII in domain names into ASCII according to IDNA.
1692 GNU Libidn, and in particular the elisp package \"idna.el\" and
1693 the external program \"idn\", must be installed for this
1694 functionality to work."
1695   :version "22.1"
1696   :group 'message-headers
1697   :link '(custom-manual "(message)IDNA")
1698   :type '(choice (const :tag "Ask" ask)
1699                  (const :tag "Never" nil)
1700                  (const :tag "Always" t)))
1701
1702 (defcustom message-generate-hashcash (if (executable-find "hashcash") t)
1703   "*Whether to generate X-Hashcash: headers.
1704 If t, always generate hashcash headers.  If `opportunistic',
1705 only generate hashcash headers if it can be done without the user
1706 waiting (i.e., only asynchronously).
1707
1708 You must have the \"hashcash\" binary installed, see `hashcash-path'."
1709   :group 'message-headers
1710   :link '(custom-manual "(message)Mail Headers")
1711   :type '(choice (const :tag "Always" t)
1712                  (const :tag "Never" nil)
1713                  (const :tag "Opportunistic" opportunistic)))
1714
1715 ;;; Internal variables.
1716
1717 (defvar message-sending-message "Sending...")
1718 (defvar message-buffer-list nil)
1719 (defvar message-this-is-news nil)
1720 (defvar message-this-is-mail nil)
1721 (defvar message-draft-article nil)
1722 (defvar message-mime-part nil)
1723 (defvar message-posting-charset nil)
1724 (defvar message-inserted-headers nil)
1725 (defvar message-inhibit-ecomplete nil)
1726
1727 ;; Byte-compiler warning
1728 (defvar gnus-active-hashtb)
1729 (defvar gnus-read-active-file)
1730
1731 ;;; Regexp matching the delimiter of messages in UNIX mail format
1732 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1733 ;;; of rmail.el's rmail-unix-mail-delimiter.
1734 (defvar message-unix-mail-delimiter
1735   (let ((time-zone-regexp
1736          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1737                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1738                  "\\|"
1739                  "\\) *")))
1740     (concat
1741      "From "
1742
1743      ;; Many things can happen to an RFC 822 mailbox before it is put into
1744      ;; a `From' line.  The leading phrase can be stripped, e.g.
1745      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1746      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1747      ;; can be removed, e.g.
1748      ;;         From: joe@y.z (Joe      K
1749      ;;                 User)
1750      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1751      ;;         From: Joe User
1752      ;;                 <joe@y.z>
1753      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1754      ;; The mailbox can be removed or be replaced by white space, e.g.
1755      ;;         From: "Joe User"{space}{tab}
1756      ;;                 <joe@y.z>
1757      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1758      ;; where {space} and {tab} represent the Ascii space and tab characters.
1759      ;; We want to match the results of any of these manglings.
1760      ;; The following regexp rejects names whose first characters are
1761      ;; obviously bogus, but after that anything goes.
1762      "\\([^\0-\b\n-\r\^?].*\\)?"
1763
1764      ;; The time the message was sent.
1765      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1766      "\\([^\0-\r \^?]+\\) +"            ; month
1767      "\\([0-3]?[0-9]\\) +"              ; day of month
1768      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1769
1770      ;; Perhaps a time zone, specified by an abbreviation, or by a
1771      ;; numeric offset.
1772      time-zone-regexp
1773
1774      ;; The year.
1775      " \\([0-9][0-9]+\\) *"
1776
1777      ;; On some systems the time zone can appear after the year, too.
1778      time-zone-regexp
1779
1780      ;; Old uucp cruft.
1781      "\\(remote from .*\\)?"
1782
1783      "\n"))
1784   "Regexp matching the delimiter of messages in UNIX mail format.")
1785
1786 (defvar message-unsent-separator
1787   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1788           "^ *---+ +Returned message +---+ *$\\|"
1789           "^Start of returned message$\\|"
1790           "^ *---+ +Original message +---+ *$\\|"
1791           "^ *--+ +begin message +--+ *$\\|"
1792           "^ *---+ +Original message follows +---+ *$\\|"
1793           "^ *---+ +Undelivered message follows +---+ *$\\|"
1794           "^------ This is a copy of the message, including all the headers. ------ *$\\|"
1795           "^|? *---+ +Message text follows: +---+ *|?$")
1796   "A regexp that matches the separator before the text of a failed message.")
1797
1798 (defvar message-field-fillers
1799   '((To message-fill-field-address)
1800     (Cc message-fill-field-address)
1801     (From message-fill-field-address))
1802   "Alist of header names/filler functions.")
1803
1804 (defvar message-header-format-alist
1805   `((From)
1806     (Newsgroups)
1807     (To)
1808     (Cc)
1809     (Subject)
1810     (In-Reply-To)
1811     (Fcc)
1812     (Bcc)
1813     (Date)
1814     (Organization)
1815     (Distribution)
1816     (Lines)
1817     (Expires)
1818     (Message-ID)
1819     (References . message-shorten-references)
1820     (User-Agent))
1821   "Alist used for formatting headers.")
1822
1823 (defvar message-options nil
1824   "Some saved answers when sending message.")
1825
1826 (defvar message-send-mail-real-function nil
1827   "Internal send mail function.")
1828
1829 (defvar message-bogus-system-names "^localhost\\.\\|\\.local$"
1830   "The regexp of bogus system names.")
1831
1832 (defcustom message-valid-fqdn-regexp
1833   (concat "[a-z0-9][-.a-z0-9]+\\." ;; [hostname.subdomain.]domain.
1834           ;; valid TLDs:
1835           "\\([a-z][a-z]\\|" ;; two letter country TDLs
1836           "aero\\|arpa\\|bitnet\\|biz\\|bofh\\|"
1837           "cat\\|com\\|coop\\|edu\\|gov\\|"
1838           "info\\|int\\|jobs\\|"
1839           "mil\\|mobi\\|museum\\|name\\|net\\|"
1840           "org\\|pro\\|travel\\|uucp\\)")
1841   ;; http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains
1842   ;; http://en.wikipedia.org/wiki/GTLD
1843   ;; `in the process of being approved': .asia .post .tel .sex
1844   ;; "dead" nato bitnet uucp
1845   "Regular expression that matches a valid FQDN."
1846   ;; see also: gnus-button-valid-fqdn-regexp
1847   :version "22.1"
1848   :group 'message-headers
1849   :type 'regexp)
1850
1851 (autoload 'gnus-alive-p "gnus-util")
1852 (autoload 'gnus-delay-article "gnus-delay")
1853 (autoload 'gnus-extract-address-components "gnus-util")
1854 (autoload 'gnus-find-method-for-group "gnus")
1855 (autoload 'gnus-group-decoded-name "gnus-group")
1856 (autoload 'gnus-group-name-charset "gnus-group")
1857 (autoload 'gnus-group-name-decode "gnus-group")
1858 (autoload 'gnus-groups-from-server "gnus")
1859 (autoload 'gnus-make-local-hook "gnus-util")
1860 (autoload 'gnus-open-server "gnus-int")
1861 (autoload 'gnus-output-to-mail "gnus-util")
1862 (autoload 'gnus-output-to-rmail "gnus-util")
1863 (autoload 'gnus-request-post "gnus-int")
1864 (autoload 'gnus-select-frame-set-input-focus "gnus-util")
1865 (autoload 'gnus-server-string "gnus")
1866 (autoload 'idna-to-ascii "idna")
1867 (autoload 'message-setup-toolbar "messagexmas")
1868 (autoload 'mh-new-draft-name "mh-comp")
1869 (autoload 'mh-send-letter "mh-comp")
1870 (autoload 'nndraft-request-associate-buffer "nndraft")
1871 (autoload 'nndraft-request-expire-articles "nndraft")
1872 (autoload 'nnvirtual-find-group-art "nnvirtual")
1873 (autoload 'rmail-dont-reply-to "mail-utils")
1874 (autoload 'rmail-msg-is-pruned "rmail")
1875 (autoload 'rmail-output "rmailout")
1876
1877 \f
1878
1879 ;;;
1880 ;;; Utility functions.
1881 ;;;
1882
1883 (defmacro message-y-or-n-p (question show &rest text)
1884   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1885   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1886
1887 (defmacro message-delete-line (&optional n)
1888   "Delete the current line (and the next N lines)."
1889   `(delete-region (progn (beginning-of-line) (point))
1890                   (progn (forward-line ,(or n 1)) (point))))
1891
1892 (defun message-mark-active-p ()
1893   "Non-nil means the mark and region are currently active in this buffer."
1894   mark-active)
1895
1896 (defun message-unquote-tokens (elems)
1897   "Remove double quotes (\") from strings in list ELEMS."
1898   (mapcar (lambda (item)
1899             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1900               (setq item (concat (match-string 1 item)
1901                                  (match-string 2 item))))
1902             item)
1903           elems))
1904
1905 (defun message-tokenize-header (header &optional separator)
1906   "Split HEADER into a list of header elements.
1907 SEPARATOR is a string of characters to be used as separators.  \",\"
1908 is used by default."
1909   (if (not header)
1910       nil
1911     (let ((regexp (format "[%s]+" (or separator ",")))
1912           (first t)
1913           beg quoted elems paren)
1914       (with-temp-buffer
1915         (mm-enable-multibyte)
1916         (setq beg (point-min))
1917         (insert header)
1918         (goto-char (point-min))
1919         (while (not (eobp))
1920           (if first
1921               (setq first nil)
1922             (forward-char 1))
1923           (cond ((and (> (point) beg)
1924                       (or (eobp)
1925                           (and (looking-at regexp)
1926                                (not quoted)
1927                                (not paren))))
1928                  (push (buffer-substring beg (point)) elems)
1929                  (setq beg (match-end 0)))
1930                 ((eq (char-after) ?\")
1931                  (setq quoted (not quoted)))
1932                 ((and (eq (char-after) ?\()
1933                       (not quoted))
1934                  (setq paren t))
1935                 ((and (eq (char-after) ?\))
1936                       (not quoted))
1937                  (setq paren nil))))
1938         (nreverse elems)))))
1939
1940 (autoload 'nnheader-insert-file-contents "nnheader")
1941
1942 (defun message-mail-file-mbox-p (file)
1943   "Say whether FILE looks like a Unix mbox file."
1944   (when (and (file-exists-p file)
1945              (file-readable-p file)
1946              (file-regular-p file))
1947     (with-temp-buffer
1948       (nnheader-insert-file-contents file)
1949       (goto-char (point-min))
1950       (looking-at message-unix-mail-delimiter))))
1951
1952 (defun message-fetch-field (header &optional not-all)
1953   "The same as `mail-fetch-field', only remove all newlines.
1954 The buffer is expected to be narrowed to just the header of the message;
1955 see `message-narrow-to-headers-or-head'."
1956   (let* ((inhibit-point-motion-hooks t)
1957          (value (mail-fetch-field header nil (not not-all))))
1958     (when value
1959       (while (string-match "\n[\t ]+" value)
1960         (setq value (replace-match " " t t value)))
1961       value)))
1962
1963 (defun message-field-value (header &optional not-all)
1964   "The same as `message-fetch-field', only narrow to the headers first."
1965   (save-excursion
1966     (save-restriction
1967       (message-narrow-to-headers-or-head)
1968       (message-fetch-field header not-all))))
1969
1970 (defun message-narrow-to-field ()
1971   "Narrow the buffer to the header on the current line."
1972   (beginning-of-line)
1973   (while (looking-at "[ \t]")
1974     (forward-line -1))
1975   (narrow-to-region
1976    (point)
1977    (progn
1978      (forward-line 1)
1979      (if (re-search-forward "^[^ \n\t]" nil t)
1980          (point-at-bol)
1981        (point-max))))
1982   (goto-char (point-min)))
1983
1984 (defun message-add-header (&rest headers)
1985   "Add the HEADERS to the message header, skipping those already present."
1986   (while headers
1987     (let (hclean)
1988       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1989         (error "Invalid header `%s'" (car headers)))
1990       (setq hclean (match-string 1 (car headers)))
1991       (save-restriction
1992         (message-narrow-to-headers)
1993         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1994           (goto-char (point-max))
1995           (if (string-match "\n$" (car headers))
1996               (insert (car headers))
1997             (insert (car headers) ?\n)))))
1998     (setq headers (cdr headers))))
1999
2000 (defmacro message-with-reply-buffer (&rest forms)
2001   "Evaluate FORMS in the reply buffer, if it exists."
2002   `(when (and (bufferp message-reply-buffer)
2003               (buffer-name message-reply-buffer))
2004      (with-current-buffer message-reply-buffer
2005        ,@forms)))
2006
2007 (put 'message-with-reply-buffer 'lisp-indent-function 0)
2008 (put 'message-with-reply-buffer 'edebug-form-spec '(body))
2009
2010 (defun message-fetch-reply-field (header)
2011   "Fetch field HEADER from the message we're replying to."
2012   (message-with-reply-buffer
2013     (save-restriction
2014       (mail-narrow-to-head)
2015       (message-fetch-field header))))
2016
2017 (defun message-strip-list-identifiers (subject)
2018   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
2019   (require 'gnus-sum)                   ; for gnus-list-identifiers
2020   (let ((regexp (if (stringp gnus-list-identifiers)
2021                     gnus-list-identifiers
2022                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
2023     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
2024                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
2025         (concat (substring subject 0 (match-beginning 1))
2026                 (or (match-string 3 subject)
2027                     (match-string 5 subject))
2028                 (substring subject
2029                            (match-end 1)))
2030       subject)))
2031
2032 (defun message-strip-subject-re (subject)
2033   "Remove \"Re:\" from subject lines in string SUBJECT."
2034   (if (string-match message-subject-re-regexp subject)
2035       (substring subject (match-end 0))
2036     subject))
2037
2038 (defcustom message-replacement-char "."
2039   "Replacement character used instead of unprintable or not decodable chars."
2040   :group 'message-various
2041   :version "22.1" ;; Gnus 5.10.9
2042   :type '(choice string
2043                  (const ".")
2044                  (const "?")))
2045
2046 ;; FIXME: We also should call `message-strip-subject-encoded-words'
2047 ;; when forwarding.  Probably in `message-make-forward-subject' and
2048 ;; `message-forward-make-body'.
2049
2050 (defun message-strip-subject-encoded-words (subject)
2051   "Fix non-decodable words in SUBJECT."
2052   ;; Cf. `gnus-simplify-subject-fully'.
2053   (let* ((case-fold-search t)
2054          (replacement-chars (format "[%s%s%s]"
2055                                     message-replacement-char
2056                                     message-replacement-char
2057                                     message-replacement-char))
2058          (enc-word-re "=\\?\\([^?]+\\)\\?\\([QB]\\)\\?\\([^?]+\\)\\(\\?=\\)")
2059          cs-string
2060          (have-marker
2061           (with-temp-buffer
2062             (insert subject)
2063             (goto-char (point-min))
2064             (when (re-search-forward enc-word-re nil t)
2065               (setq cs-string (match-string 1)))))
2066          cs-coding q-or-b word-beg word-end)
2067     (if (or (not have-marker) ;; No encoded word found...
2068             ;; ... or double encoding was correct:
2069             (and (stringp cs-string)
2070                  (setq cs-string (downcase cs-string))
2071                  (mm-coding-system-p (intern cs-string))
2072                  (not (prog1
2073                           (y-or-n-p
2074                            (format "\
2075 Decoded Subject \"%s\"
2076 contains a valid encoded word.  Decode again? "
2077                                    subject))
2078                         (setq cs-coding (intern cs-string))))))
2079         subject
2080       (with-temp-buffer
2081         (insert subject)
2082         (goto-char (point-min))
2083         (while (re-search-forward enc-word-re nil t)
2084           (setq cs-string (downcase (match-string 1))
2085                 q-or-b    (match-string 2)
2086                 word-beg (match-beginning 0)
2087                 word-end (match-end 0))
2088           (setq cs-coding
2089                 (if (mm-coding-system-p (intern cs-string))
2090                     (setq cs-coding (intern cs-string))
2091                   nil))
2092           ;; No double encoded subject? => bogus charset.
2093           (unless cs-coding
2094             (setq cs-coding
2095                   (mm-read-coding-system
2096                    (format "\
2097 Decoded Subject \"%s\"
2098 contains an encoded word.  The charset `%s' is unknown or invalid.
2099 Hit RET to replace non-decodable characters with \"%s\" or enter replacement
2100 charset: "
2101                            subject cs-string message-replacement-char)))
2102             (if cs-coding
2103                 (replace-match (concat "=?" (symbol-name cs-coding)
2104                                        "?\\2?\\3\\4\\5"))
2105               (save-excursion
2106                 (goto-char word-beg)
2107                 (re-search-forward "=\\?\\([^?]+\\)\\?\\([QB]\\)\\?" word-end t)
2108                 (replace-match "")
2109                 ;; QP or base64
2110                 (if (string-match "\\`Q\\'" q-or-b)
2111                     ;; QP
2112                     (progn
2113                       (message "Replacing non-decodable characters with \"%s\"."
2114                                message-replacement-char)
2115                       (while (re-search-forward "\\(=[A-F0-9][A-F0-9]\\)+"
2116                                                 word-end t)
2117                         (replace-match message-replacement-char)))
2118                   ;; base64
2119                   (message "Replacing non-decodable characters with \"%s\"."
2120                            replacement-chars)
2121                   (re-search-forward "[^?]+" word-end t)
2122                   (replace-match replacement-chars))
2123                 (re-search-forward "\\?=")
2124                 (replace-match "")))))
2125         (rfc2047-decode-region (point-min) (point-max))
2126         (buffer-string)))))
2127
2128 ;;; Start of functions adopted from `message-utils.el'.
2129
2130 (defun message-strip-subject-trailing-was (subject)
2131   "Remove trailing \"(was: <old subject>)\" from SUBJECT lines.
2132 Leading \"Re: \" is not stripped by this function.  Use the function
2133 `message-strip-subject-re' for this."
2134   (let* ((query message-subject-trailing-was-query)
2135          (new) (found))
2136     (setq found
2137           (string-match
2138            (if (eq query 'ask)
2139                message-subject-trailing-was-ask-regexp
2140              message-subject-trailing-was-regexp)
2141            subject))
2142     (if found
2143         (setq new (substring subject 0 (match-beginning 0))))
2144     (if (or (not found) (eq query nil))
2145         subject
2146       (if (eq query 'ask)
2147           (if (message-y-or-n-p
2148                "Strip `(was: <old subject>)' in subject? " t
2149                (concat
2150                 "Strip `(was: <old subject>)' in subject "
2151                 "and use the new one instead?\n\n"
2152                 "Current subject is:   \""
2153                 subject "\"\n\n"
2154                 "New subject would be: \""
2155                 new "\"\n\n"
2156                 "See the variable `message-subject-trailing-was-query' "
2157                 "to get rid of this query."
2158                 ))
2159               new subject)
2160         new))))
2161
2162 ;;; Suggested by Jonas Steverud  @  www.dtek.chalmers.se/~d4jonas/
2163
2164 (defun message-change-subject (new-subject)
2165   "Ask for NEW-SUBJECT header, append (was: <Old Subject>)."
2166   ;; <URL:http://www.landfield.com/usefor/drafts/draft-ietf-usefor-useage--1.02.unpaged>
2167   (interactive
2168    (list
2169     (read-from-minibuffer "New subject: ")))
2170   (cond ((and (not (or (null new-subject) ; new subject not empty
2171                        (zerop (string-width new-subject))
2172                        (string-match "^[ \t]*$" new-subject))))
2173          (save-excursion
2174            (let ((old-subject
2175                   (save-restriction
2176                     (message-narrow-to-headers)
2177                     (message-fetch-field "Subject"))))
2178              (cond ((not old-subject)
2179                     (error "No current subject"))
2180                    ((not (string-match
2181                           (concat "^[ \t]*"
2182                                   (regexp-quote new-subject)
2183                                   " \t]*$")
2184                           old-subject))  ; yes, it really is a new subject
2185                     ;; delete eventual Re: prefix
2186                     (setq old-subject
2187                           (message-strip-subject-re old-subject))
2188                     (message-goto-subject)
2189                     (message-delete-line)
2190                     (insert (concat "Subject: "
2191                                     new-subject
2192                                     " (was: "
2193                                     old-subject ")\n")))))))))
2194
2195 (defun message-mark-inserted-region (beg end &optional verbatim)
2196   "Mark some region in the current article with enclosing tags.
2197 See `message-mark-insert-begin' and `message-mark-insert-end'.
2198 If VERBATIM, use slrn style verbatim marks (\"#v+\" and \"#v-\")."
2199   (interactive "r\nP")
2200   (save-excursion
2201     ;; add to the end of the region first, otherwise end would be invalid
2202     (goto-char end)
2203     (insert (if verbatim "#v-\n" message-mark-insert-end))
2204     (goto-char beg)
2205     (insert (if verbatim "#v+\n" message-mark-insert-begin))))
2206
2207 (defun message-mark-insert-file (file &optional verbatim)
2208   "Insert FILE at point, marking it with enclosing tags.
2209 See `message-mark-insert-begin' and `message-mark-insert-end'.
2210 If VERBATIM, use slrn style verbatim marks (\"#v+\" and \"#v-\")."
2211   (interactive "fFile to insert: \nP")
2212     ;; reverse insertion to get correct result.
2213   (let ((p (point)))
2214     (insert (if verbatim "#v-\n" message-mark-insert-end))
2215     (goto-char p)
2216     (insert-file-contents file)
2217     (goto-char p)
2218     (insert (if verbatim "#v+\n" message-mark-insert-begin))))
2219
2220 (defun message-add-archive-header ()
2221   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
2222 The note can be customized using `message-archive-note'.  When called with a
2223 prefix argument, ask for a text to insert.  If you don't want the note in the
2224 body, set  `message-archive-note' to nil."
2225   (interactive)
2226   (if current-prefix-arg
2227       (setq message-archive-note
2228             (read-from-minibuffer "Reason for No-Archive: "
2229                                   (cons message-archive-note 0))))
2230     (save-excursion
2231       (if (message-goto-signature)
2232           (re-search-backward message-signature-separator))
2233       (when message-archive-note
2234         (insert message-archive-note)
2235         (newline))
2236       (message-add-header message-archive-header)
2237       (message-sort-headers)))
2238
2239 (defun message-cross-post-followup-to-header (target-group)
2240   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
2241 With prefix-argument just set Follow-Up, don't cross-post."
2242   (interactive
2243    (list ; Completion based on Gnus
2244     (completing-read "Followup To: "
2245                      (if (boundp 'gnus-newsrc-alist)
2246                          gnus-newsrc-alist)
2247                      nil nil '("poster" . 0)
2248                      (if (boundp 'gnus-group-history)
2249                          'gnus-group-history))))
2250   (message-remove-header "Follow[Uu]p-[Tt]o" t)
2251   (message-goto-newsgroups)
2252   (beginning-of-line)
2253   ;; if we already did a crosspost before, kill old target
2254   (if (and message-cross-post-old-target
2255            (re-search-forward
2256             (regexp-quote (concat "," message-cross-post-old-target))
2257             nil t))
2258       (replace-match ""))
2259   ;; unless (followup is to poster or user explicitly asked not
2260   ;; to cross-post, or target-group is already in Newsgroups)
2261   ;; add target-group to Newsgroups line.
2262   (cond ((and (or
2263                ;; def: cross-post, req:no
2264                (and message-cross-post-default (not current-prefix-arg))
2265                ;; def: no-cross-post, req:yes
2266                (and (not message-cross-post-default) current-prefix-arg))
2267               (not (string-match "poster" target-group))
2268               (not (string-match (regexp-quote target-group)
2269                                  (message-fetch-field "Newsgroups"))))
2270          (end-of-line)
2271          (insert (concat "," target-group))))
2272   (end-of-line) ; ensure Followup: comes after Newsgroups:
2273   ;; unless new followup would be identical to Newsgroups line
2274   ;; make a new Followup-To line
2275   (if (not (string-match (concat "^[ \t]*"
2276                                  target-group
2277                                  "[ \t]*$")
2278                          (message-fetch-field "Newsgroups")))
2279       (insert (concat "\nFollowup-To: " target-group)))
2280   (setq message-cross-post-old-target target-group))
2281
2282 (defun message-cross-post-insert-note (target-group cross-post in-old
2283                                                     old-groups)
2284   "Insert a in message body note about a set Followup or Crosspost.
2285 If there have been previous notes, delete them.  TARGET-GROUP specifies the
2286 group to Followup-To.  When CROSS-POST is t, insert note about
2287 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
2288 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
2289 been made to before the user asked for a Crosspost."
2290   ;; start scanning body for previous uses
2291   (message-goto-signature)
2292   (let ((head (re-search-backward
2293                (concat "^" mail-header-separator)
2294                nil t))) ; just search in body
2295     (message-goto-signature)
2296     (while (re-search-backward
2297             (concat "^" (regexp-quote message-cross-post-note) ".*")
2298             head t)
2299       (message-delete-line))
2300     (message-goto-signature)
2301     (while (re-search-backward
2302             (concat "^" (regexp-quote message-followup-to-note) ".*")
2303             head t)
2304       (message-delete-line))
2305     ;; insert new note
2306     (if (message-goto-signature)
2307         (re-search-backward message-signature-separator))
2308     (if (or in-old
2309             (not cross-post)
2310             (string-match "^[ \t]*poster[ \t]*$" target-group))
2311         (insert (concat message-followup-to-note target-group "\n"))
2312       (insert (concat message-cross-post-note target-group "\n")))))
2313
2314 (defun message-cross-post-followup-to (target-group)
2315   "Crossposts message and set Followup-To to TARGET-GROUP.
2316 With prefix-argument just set Follow-Up, don't cross-post."
2317   (interactive
2318    (list ; Completion based on Gnus
2319     (completing-read "Followup To: "
2320                      (if (boundp 'gnus-newsrc-alist)
2321                          gnus-newsrc-alist)
2322                      nil nil '("poster" . 0)
2323                      (if (boundp 'gnus-group-history)
2324                          'gnus-group-history))))
2325   (cond ((not (or (null target-group) ; new subject not empty
2326                   (zerop (string-width target-group))
2327                   (string-match "^[ \t]*$" target-group)))
2328          (save-excursion
2329            (let* ((old-groups (message-fetch-field "Newsgroups"))
2330                   (in-old (string-match
2331                            (regexp-quote target-group)
2332                            (or old-groups ""))))
2333              ;; check whether target exactly matches old Newsgroups
2334              (cond ((not old-groups)
2335                     (error "No current newsgroup"))
2336                    ((or (not in-old)
2337                         (not (string-match
2338                               (concat "^[ \t]*"
2339                                       (regexp-quote target-group)
2340                                       "[ \t]*$")
2341                               old-groups)))
2342                     ;; yes, Newsgroups line must change
2343                     (message-cross-post-followup-to-header target-group)
2344                     ;; insert note whether we do cross-post or followup-to
2345                     (funcall message-cross-post-note-function
2346                              target-group
2347                              (if (or (and message-cross-post-default
2348                                           (not current-prefix-arg))
2349                                      (and (not message-cross-post-default)
2350                                           current-prefix-arg)) t)
2351                              in-old old-groups))))))))
2352
2353 ;;; Reduce To: to Cc: or Bcc: header
2354
2355 (defun message-reduce-to-to-cc ()
2356  "Replace contents of To: header with contents of Cc: or Bcc: header."
2357  (interactive)
2358  (let ((cc-content
2359         (save-restriction (message-narrow-to-headers)
2360                           (message-fetch-field "cc")))
2361        (bcc nil))
2362    (if (and (not cc-content)
2363             (setq cc-content
2364                   (save-restriction
2365                     (message-narrow-to-headers)
2366                     (message-fetch-field "bcc"))))
2367        (setq bcc t))
2368    (cond (cc-content
2369           (save-excursion
2370             (message-goto-to)
2371             (message-delete-line)
2372             (insert (concat "To: " cc-content "\n"))
2373             (save-restriction
2374               (message-narrow-to-headers)
2375               (message-remove-header (if bcc
2376                                          "bcc"
2377                                        "cc"))))))))
2378
2379 ;;; End of functions adopted from `message-utils.el'.
2380
2381 (defun message-remove-header (header &optional is-regexp first reverse)
2382   "Remove HEADER in the narrowed buffer.
2383 If IS-REGEXP, HEADER is a regular expression.
2384 If FIRST, only remove the first instance of the header.
2385 Return the number of headers removed."
2386   (goto-char (point-min))
2387   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
2388         (number 0)
2389         (case-fold-search t)
2390         last)
2391     (while (and (not (eobp))
2392                 (not last))
2393       (if (if reverse
2394               (not (looking-at regexp))
2395             (looking-at regexp))
2396           (progn
2397             (incf number)
2398             (when first
2399               (setq last t))
2400             (delete-region
2401              (point)
2402              ;; There might be a continuation header, so we have to search
2403              ;; until we find a new non-continuation line.
2404              (progn
2405                (forward-line 1)
2406                (if (re-search-forward "^[^ \t]" nil t)
2407                    (goto-char (match-beginning 0))
2408                  (point-max)))))
2409         (forward-line 1)
2410         (if (re-search-forward "^[^ \t]" nil t)
2411             (goto-char (match-beginning 0))
2412           (goto-char (point-max)))))
2413     number))
2414
2415 (defun message-remove-first-header (header)
2416   "Remove the first instance of HEADER if there is more than one."
2417   (let ((count 0)
2418         (regexp (concat "^" (regexp-quote header) ":")))
2419     (save-excursion
2420       (goto-char (point-min))
2421       (while (re-search-forward regexp nil t)
2422         (incf count)))
2423     (while (> count 1)
2424       (message-remove-header header nil t)
2425       (decf count))))
2426
2427 (defun message-narrow-to-headers ()
2428   "Narrow the buffer to the head of the message."
2429   (widen)
2430   (narrow-to-region
2431    (goto-char (point-min))
2432    (if (re-search-forward
2433         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2434        (match-beginning 0)
2435      (point-max)))
2436   (goto-char (point-min)))
2437
2438 (defun message-narrow-to-head-1 ()
2439   "Like `message-narrow-to-head'.  Don't widen."
2440   (narrow-to-region
2441    (goto-char (point-min))
2442    (if (search-forward "\n\n" nil 1)
2443        (1- (point))
2444      (point-max)))
2445   (goto-char (point-min)))
2446
2447 ;; FIXME: clarify diffference: message-narrow-to-head,
2448 ;; message-narrow-to-headers-or-head, message-narrow-to-headers
2449 (defun message-narrow-to-head ()
2450   "Narrow the buffer to the head of the message.
2451 Point is left at the beginning of the narrowed-to region."
2452   (widen)
2453   (message-narrow-to-head-1))
2454
2455 (defun message-narrow-to-headers-or-head ()
2456   "Narrow the buffer to the head of the message."
2457   (widen)
2458   (narrow-to-region
2459    (goto-char (point-min))
2460    (if (re-search-forward (concat "\\(\n\\)\n\\|^\\("
2461                                   (regexp-quote mail-header-separator)
2462                                   "\n\\)")
2463                           nil t)
2464        (or (match-end 1) (match-beginning 2))
2465      (point-max)))
2466   (goto-char (point-min)))
2467
2468 (defun message-news-p ()
2469   "Say whether the current buffer contains a news message."
2470   (and (not message-this-is-mail)
2471        (or message-this-is-news
2472            (save-excursion
2473              (save-restriction
2474                (message-narrow-to-headers)
2475                (and (message-fetch-field "newsgroups")
2476                     (not (message-fetch-field "posted-to"))))))))
2477
2478 (defun message-mail-p ()
2479   "Say whether the current buffer contains a mail message."
2480   (and (not message-this-is-news)
2481        (or message-this-is-mail
2482            (save-excursion
2483              (save-restriction
2484                (message-narrow-to-headers)
2485                (or (message-fetch-field "to")
2486                    (message-fetch-field "cc")
2487                    (message-fetch-field "bcc")))))))
2488
2489 (defun message-subscribed-p ()
2490   "Say whether we need to insert a MFT header."
2491   (or message-subscribed-regexps
2492       message-subscribed-addresses
2493       message-subscribed-address-file
2494       message-subscribed-address-functions))
2495
2496 (defun message-next-header ()
2497   "Go to the beginning of the next header."
2498   (beginning-of-line)
2499   (or (eobp) (forward-char 1))
2500   (not (if (re-search-forward "^[^ \t]" nil t)
2501            (beginning-of-line)
2502          (goto-char (point-max)))))
2503
2504 (defun message-sort-headers-1 ()
2505   "Sort the buffer as headers using `message-rank' text props."
2506   (goto-char (point-min))
2507   (require 'sort)
2508   (sort-subr
2509    nil 'message-next-header
2510    (lambda ()
2511      (message-next-header)
2512      (unless (bobp)
2513        (forward-char -1)))
2514    (lambda ()
2515      (or (get-text-property (point) 'message-rank)
2516          10000))))
2517
2518 (defun message-sort-headers ()
2519   "Sort the headers of the current message according to `message-header-format-alist'."
2520   (interactive)
2521   (save-excursion
2522     (save-restriction
2523       (let ((max (1+ (length message-header-format-alist)))
2524             rank)
2525         (message-narrow-to-headers)
2526         (while (re-search-forward "^[^ \n]+:" nil t)
2527           (put-text-property
2528            (match-beginning 0) (1+ (match-beginning 0))
2529            'message-rank
2530            (if (setq rank (length (memq (assq (intern (buffer-substring
2531                                                        (match-beginning 0)
2532                                                        (1- (match-end 0))))
2533                                               message-header-format-alist)
2534                                         message-header-format-alist)))
2535                (- max rank)
2536              (1+ max)))))
2537       (message-sort-headers-1))))
2538
2539 (defun message-kill-address ()
2540   "Kill the address under point."
2541   (interactive)
2542   (let ((start (point)))
2543     (message-skip-to-next-address)
2544     (kill-region start (point))))
2545
2546
2547 (autoload 'Info-goto-node "info")
2548 (defvar mml2015-use)
2549
2550 (defun message-info (&optional arg)
2551   "Display the Message manual.
2552
2553 Prefixed with one \\[universal-argument], display the Emacs MIME
2554 manual.  With two \\[universal-argument]'s, display the EasyPG or
2555 PGG manual, depending on the value of `mml2015-use'."
2556   (interactive "p")
2557   ;; Don't use `info' because support for `(filename)nodename' is not
2558   ;; available in XEmacs < 21.5.12.
2559   (Info-goto-node (format "(%s)Top"
2560                           (cond ((eq arg 16)
2561                                  (require 'mml2015)
2562                                  mml2015-use)
2563                                 ((eq arg  4) 'emacs-mime)
2564                                 ;; `booleanp' only available in Emacs 22+
2565                                 ((and (not (memq arg '(nil t)))
2566                                       (symbolp arg))
2567                                  arg)
2568                                 (t
2569                                  'message)))))
2570
2571 \f
2572
2573 ;;;
2574 ;;; Message mode
2575 ;;;
2576
2577 ;;; Set up keymap.
2578
2579 (defvar message-mode-map nil)
2580
2581 (unless message-mode-map
2582   (setq message-mode-map (make-keymap))
2583   (set-keymap-parent message-mode-map text-mode-map)
2584   (define-key message-mode-map "\C-c?" 'describe-mode)
2585
2586   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
2587   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
2588   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
2589   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
2590   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
2591   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
2592   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
2593   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
2594   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
2595   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
2596   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2597   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
2598   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
2599   (define-key message-mode-map "\C-c\C-f\C-i"
2600     'message-insert-or-toggle-importance)
2601   (define-key message-mode-map "\C-c\C-f\C-a"
2602     'message-generate-unsubscribed-mail-followup-to)
2603
2604   ;; modify headers (and insert notes in body)
2605   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
2606   ;;
2607   (define-key message-mode-map "\C-c\C-fx"    'message-cross-post-followup-to)
2608   ;; prefix+message-cross-post-followup-to = same w/o cross-post
2609   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
2610   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
2611   ;; mark inserted text
2612   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
2613   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
2614
2615   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
2616   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
2617
2618   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
2619   (define-key message-mode-map "\C-c\C-fw" 'message-insert-wide-reply)
2620   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
2621   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
2622   (define-key message-mode-map "\C-c\C-f\C-e" 'message-insert-expires)
2623
2624   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
2625   (define-key message-mode-map "\C-c\M-n"
2626     'message-insert-disposition-notification-to)
2627
2628   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
2629   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
2630   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
2631   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2632   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2633   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2634   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2635   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2636
2637   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2638   (define-key message-mode-map "\C-c\C-s" 'message-send)
2639   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2640   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2641   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2642
2643   (define-key message-mode-map "\C-c\M-k" 'message-kill-address)
2644   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2645   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2646   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2647   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2648   (define-key message-mode-map [remap split-line]  'message-split-line)
2649
2650   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
2651
2652   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2653   (define-key message-mode-map "\t" 'message-tab)
2654   (define-key message-mode-map "\M-;" 'comment-region)
2655
2656   (define-key message-mode-map "\M-n" 'message-display-abbrev))
2657
2658 (easy-menu-define
2659   message-mode-menu message-mode-map "Message Menu."
2660   `("Message"
2661     ["Yank Original" message-yank-original message-reply-buffer]
2662     ["Fill Yanked Message" message-fill-yanked-message t]
2663     ["Insert Signature" message-insert-signature t]
2664     ["Caesar (rot13) Message" message-caesar-buffer-body t]
2665     ["Caesar (rot13) Region" message-caesar-region (message-mark-active-p)]
2666     ["Elide Region" message-elide-region
2667      :active (message-mark-active-p)
2668      ,@(if (featurep 'xemacs) nil
2669          '(:help "Replace text in region with an ellipsis"))]
2670     ["Delete Outside Region" message-delete-not-region
2671      :active (message-mark-active-p)
2672      ,@(if (featurep 'xemacs) nil
2673          '(:help "Delete all quoted text outside region"))]
2674     ["Kill To Signature" message-kill-to-signature t]
2675     ["Newline and Reformat" message-newline-and-reformat t]
2676     ["Rename buffer" message-rename-buffer t]
2677     ["Spellcheck" ispell-message
2678      ,@(if (featurep 'xemacs) '(t)
2679          '(:help "Spellcheck this message"))]
2680     "----"
2681     ["Insert Region Marked" message-mark-inserted-region
2682      :active (message-mark-active-p)
2683      ,@(if (featurep 'xemacs) nil
2684          '(:help "Mark region with enclosing tags"))]
2685     ["Insert File Marked..." message-mark-insert-file
2686      ,@(if (featurep 'xemacs) '(t)
2687          '(:help "Insert file at point marked with enclosing tags"))]
2688     "----"
2689     ["Send Message" message-send-and-exit
2690      ,@(if (featurep 'xemacs) '(t)
2691          '(:help "Send this message"))]
2692     ["Postpone Message" message-dont-send
2693      ,@(if (featurep 'xemacs) '(t)
2694          '(:help "File this draft message and exit"))]
2695     ["Send at Specific Time..." gnus-delay-article
2696      ,@(if (featurep 'xemacs) '(t)
2697          '(:help "Ask, then arrange to send message at that time"))]
2698     ["Kill Message" message-kill-buffer
2699      ,@(if (featurep 'xemacs) '(t)
2700          '(:help "Delete this message without sending"))]
2701     "----"
2702     ["Message manual" message-info
2703      ,@(if (featurep 'xemacs) '(t)
2704          '(:help "Display the Message manual"))]))
2705
2706 (easy-menu-define
2707   message-mode-field-menu message-mode-map ""
2708   `("Field"
2709     ["To" message-goto-to t]
2710     ["From" message-goto-from t]
2711     ["Subject" message-goto-subject t]
2712     ["Change subject..." message-change-subject t]
2713     ["Cc" message-goto-cc t]
2714     ["Bcc" message-goto-bcc t]
2715     ["Fcc" message-goto-fcc t]
2716     ["Reply-To" message-goto-reply-to t]
2717     ["Flag As Important" message-insert-importance-high
2718      ,@(if (featurep 'xemacs) '(t)
2719          '(:help "Mark this message as important"))]
2720     ["Flag As Unimportant" message-insert-importance-low
2721      ,@(if (featurep 'xemacs) '(t)
2722          '(:help "Mark this message as unimportant"))]
2723     ["Request Receipt"
2724      message-insert-disposition-notification-to
2725      ,@(if (featurep 'xemacs) '(t)
2726          '(:help "Request a receipt notification"))]
2727     "----"
2728     ;; (typical) news stuff
2729     ["Summary" message-goto-summary t]
2730     ["Keywords" message-goto-keywords t]
2731     ["Newsgroups" message-goto-newsgroups t]
2732     ["Fetch Newsgroups" message-insert-newsgroups t]
2733     ["Followup-To" message-goto-followup-to t]
2734     ;; ["Followup-To (with note in body)" message-cross-post-followup-to t]
2735     ["Crosspost / Followup-To..." message-cross-post-followup-to t]
2736     ["Distribution" message-goto-distribution t]
2737     ["Expires" message-insert-expires t ]
2738     ["X-No-Archive" message-add-archive-header t ]
2739     "----"
2740     ;; (typical) mailing-lists stuff
2741     ["Fetch To" message-insert-to
2742      ,@(if (featurep 'xemacs) '(t)
2743          '(:help "Insert a To header that points to the author."))]
2744     ["Fetch To and Cc" message-insert-wide-reply
2745      ,@(if (featurep 'xemacs) '(t)
2746          '(:help
2747            "Insert To and Cc headers as if you were doing a wide reply."))]
2748     "----"
2749     ["Send to list only" message-to-list-only t]
2750     ["Mail-Followup-To" message-goto-mail-followup-to t]
2751     ["Unsubscribed list post" message-generate-unsubscribed-mail-followup-to
2752      ,@(if (featurep 'xemacs) '(t)
2753          '(:help "Insert a reasonable `Mail-Followup-To:' header."))]
2754     ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2755     "----"
2756     ["Sort Headers" message-sort-headers t]
2757     ["Encode non-ASCII domain names" message-idna-to-ascii-rhs t]
2758     ;; We hide `message-hidden-headers' by narrowing the buffer.
2759     ["Show Hidden Headers" widen t]
2760     ["Goto Body" message-goto-body t]
2761     ["Goto Signature" message-goto-signature t]))
2762
2763 (defvar message-tool-bar-map nil)
2764
2765 (defvar facemenu-add-face-function)
2766 (defvar facemenu-remove-face-function)
2767
2768 ;;; Forbidden properties
2769 ;;
2770 ;; We use `after-change-functions' to keep special text properties
2771 ;; that interfere with the normal function of message mode out of the
2772 ;; buffer.
2773
2774 (defcustom message-strip-special-text-properties t
2775   "Strip special properties from the message buffer.
2776
2777 Emacs has a number of special text properties which can break message
2778 composing in various ways.  If this option is set, message will strip
2779 these properties from the message composition buffer.  However, some
2780 packages requires these properties to be present in order to work.
2781 If you use one of these packages, turn this option off, and hope the
2782 message composition doesn't break too bad."
2783   :version "22.1"
2784   :group 'message-various
2785   :link '(custom-manual "(message)Various Message Variables")
2786   :type 'boolean)
2787
2788 (defconst message-forbidden-properties
2789   ;; No reason this should be clutter up customize.  We make it a
2790   ;; property list (rather than a list of property symbols), to be
2791   ;; directly useful for `remove-text-properties'.
2792   '(field nil read-only nil invisible nil intangible nil
2793           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2794           insert-behind-hooks nil point-entered nil point-left nil)
2795   ;; Other special properties:
2796   ;; category, face, display: probably doesn't do any harm.
2797   ;; fontified: is used by font-lock.
2798   ;; syntax-table, local-map: I dunno.
2799   ;; We need to add XEmacs names to the list.
2800   "Property list of with properties forbidden in message buffers.
2801 The values of the properties are ignored, only the property names are used.")
2802
2803 (defun message-tamago-not-in-use-p (pos)
2804   "Return t when tamago version 4 is not in use at the cursor position.
2805 Tamago version 4 is a popular input method for writing Japanese text.
2806 It uses the properties `intangible', `invisible', `modification-hooks'
2807 and `read-only' when translating ascii or kana text to kanji text.
2808 These properties are essential to work, so we should never strip them."
2809   (not (and (boundp 'egg-modefull-mode)
2810             (symbol-value 'egg-modefull-mode)
2811             (or (memq (get-text-property pos 'intangible)
2812                       '(its-part-1 its-part-2))
2813                 (get-text-property pos 'egg-end)
2814                 (get-text-property pos 'egg-lang)
2815                 (get-text-property pos 'egg-start)))))
2816
2817 (defsubst message-mail-alias-type-p (type)
2818   (if (atom message-mail-alias-type)
2819       (eq message-mail-alias-type type)
2820     (memq type message-mail-alias-type)))
2821
2822 (defun message-strip-forbidden-properties (begin end &optional old-length)
2823   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2824 This function is intended to be called from `after-change-functions'.
2825 See also `message-forbidden-properties'."
2826   (when (and (message-mail-alias-type-p 'ecomplete)
2827              (memq this-command message-self-insert-commands))
2828     (message-display-abbrev))
2829   (when (and message-strip-special-text-properties
2830              (message-tamago-not-in-use-p begin))
2831     (let ((buffer-read-only nil)
2832           (inhibit-read-only t))
2833       (remove-text-properties begin end message-forbidden-properties))))
2834
2835 (autoload 'ecomplete-setup "ecomplete") ;; for Emacs <23.
2836
2837 ;;;###autoload
2838 (define-derived-mode message-mode text-mode "Message"
2839   "Major mode for editing mail and news to be sent.
2840 Like Text Mode but with these additional commands:\\<message-mode-map>
2841 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2842 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2843 C-c C-f  move to a header field (and create it if there isn't):
2844          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2845          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2846          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2847          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2848          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2849          C-c C-f C-o  move to From (\"Originator\")
2850          C-c C-f C-f  move to Followup-To
2851          C-c C-f C-m  move to Mail-Followup-To
2852          C-c C-f C-e  move to Expires
2853          C-c C-f C-i  cycle through Importance values
2854          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2855          C-c C-f x    crossposting with FollowUp-To header and note in body
2856          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2857          C-c C-f a    Insert X-No-Archive: header and a note in the body
2858 C-c C-t  `message-insert-to' (add a To header to a news followup)
2859 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2860 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2861 C-c C-b  `message-goto-body' (move to beginning of message text).
2862 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2863 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2864 C-c C-y  `message-yank-original' (insert current message, if any).
2865 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2866 C-c C-e  `message-elide-region' (elide the text between point and mark).
2867 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2868 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2869 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2870 C-c C-a  `mml-attach-file' (attach a file as MIME).
2871 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2872 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2873 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2874 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2875 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2876   (setq local-abbrev-table text-mode-abbrev-table)
2877   (set (make-local-variable 'message-reply-buffer) nil)
2878   (set (make-local-variable 'message-inserted-headers) nil)
2879   (set (make-local-variable 'message-send-actions) nil)
2880   (set (make-local-variable 'message-exit-actions) nil)
2881   (set (make-local-variable 'message-kill-actions) nil)
2882   (set (make-local-variable 'message-postpone-actions) nil)
2883   (set (make-local-variable 'message-draft-article) nil)
2884   (setq buffer-offer-save t)
2885   (set (make-local-variable 'facemenu-add-face-function)
2886        (lambda (face end)
2887          (let ((face-fun (cdr (assq face message-face-alist))))
2888            (if face-fun
2889                (funcall face-fun (point) end)
2890              (error "Face %s not configured for %s mode" face mode-name)))
2891          ""))
2892   (set (make-local-variable 'facemenu-remove-face-function) t)
2893   (set (make-local-variable 'message-reply-headers) nil)
2894   (make-local-variable 'message-newsreader)
2895   (make-local-variable 'message-mailer)
2896   (make-local-variable 'message-post-method)
2897   (set (make-local-variable 'message-sent-message-via) nil)
2898   (set (make-local-variable 'message-checksum) nil)
2899   (set (make-local-variable 'message-mime-part) 0)
2900   (message-setup-fill-variables)
2901   (when message-fill-column
2902     (setq fill-column message-fill-column)
2903     (turn-on-auto-fill))
2904   ;; Allow using comment commands to add/remove quoting.
2905   ;; (set (make-local-variable 'comment-start) message-yank-prefix)
2906   (when message-yank-prefix
2907     (set (make-local-variable 'comment-start) message-yank-prefix)
2908     (set (make-local-variable 'comment-start-skip)
2909          (concat "^" (regexp-quote message-yank-prefix) "[ \t]*")))
2910   (if (featurep 'xemacs)
2911       (message-setup-toolbar)
2912     (set (make-local-variable 'font-lock-defaults)
2913          '(message-font-lock-keywords t))
2914     (if (boundp 'tool-bar-map)
2915         (set (make-local-variable 'tool-bar-map) (message-make-tool-bar))))
2916   (easy-menu-add message-mode-menu message-mode-map)
2917   (easy-menu-add message-mode-field-menu message-mode-map)
2918   (gnus-make-local-hook 'after-change-functions)
2919   ;; Mmmm... Forbidden properties...
2920   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2921             nil 'local)
2922   ;; Allow mail alias things.
2923   (cond
2924    ((message-mail-alias-type-p 'abbrev)
2925     (if (fboundp 'mail-abbrevs-setup)
2926         (mail-abbrevs-setup)
2927       (if (fboundp 'mail-aliases-setup) ; warning avoidance
2928           (mail-aliases-setup))))
2929    ((message-mail-alias-type-p 'ecomplete)
2930     (ecomplete-setup)))
2931   (unless buffer-file-name
2932     (message-set-auto-save-file-name))
2933   (unless (buffer-base-buffer)
2934     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
2935     ;; multibyte is not necessary at all. -- zsh
2936     (mm-enable-multibyte))
2937   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
2938   (mml-mode))
2939
2940 (defun message-setup-fill-variables ()
2941   "Setup message fill variables."
2942   (set (make-local-variable 'fill-paragraph-function)
2943        'message-fill-paragraph)
2944   (make-local-variable 'paragraph-separate)
2945   (make-local-variable 'paragraph-start)
2946   (make-local-variable 'adaptive-fill-regexp)
2947   (unless (boundp 'adaptive-fill-first-line-regexp)
2948     (setq adaptive-fill-first-line-regexp nil))
2949   (make-local-variable 'adaptive-fill-first-line-regexp)
2950   (let ((quote-prefix-regexp
2951          ;; User should change message-cite-prefix-regexp if
2952          ;; message-yank-prefix is set to an abnormal value.
2953          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2954     (setq paragraph-start
2955           (concat
2956            (regexp-quote mail-header-separator) "$\\|"
2957            "[ \t]*$\\|"                 ; blank lines
2958            "-- $\\|"                    ; signature delimiter
2959            "---+$\\|"              ; delimiters for forwarded messages
2960            page-delimiter "$\\|"        ; spoiler warnings
2961            ".*wrote:$\\|"               ; attribution lines
2962            quote-prefix-regexp "$\\|"   ; empty lines in quoted text
2963                                         ; mml tags
2964            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
2965     (setq paragraph-separate paragraph-start)
2966     (setq adaptive-fill-regexp
2967           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2968     (setq adaptive-fill-first-line-regexp
2969           (concat quote-prefix-regexp "\\|"
2970                   adaptive-fill-first-line-regexp)))
2971   (make-local-variable 'auto-fill-inhibit-regexp)
2972   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2973   (setq auto-fill-inhibit-regexp nil)
2974   (make-local-variable 'normal-auto-fill-function)
2975   (setq normal-auto-fill-function 'message-do-auto-fill)
2976   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2977   ;; In that case, ensure that it uses the right function.  The real
2978   ;; solution would be not to use `define-derived-mode', and run
2979   ;; `text-mode-hook' ourself at the end of the mode.
2980   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2981   ;; This kludge is unneeded in Emacs>=21 since define-derived-mode is
2982   ;; now careful to run parent hooks after the body.  --Stef
2983   (when auto-fill-function
2984     (setq auto-fill-function normal-auto-fill-function)))
2985
2986 \f
2987
2988 ;;;
2989 ;;; Message mode commands
2990 ;;;
2991
2992 ;;; Movement commands
2993
2994 (defun message-goto-to ()
2995   "Move point to the To header."
2996   (interactive)
2997   (message-position-on-field "To"))
2998
2999 (defun message-goto-from ()
3000   "Move point to the From header."
3001   (interactive)
3002   (message-position-on-field "From"))
3003
3004 (defun message-goto-subject ()
3005   "Move point to the Subject header."
3006   (interactive)
3007   (message-position-on-field "Subject"))
3008
3009 (defun message-goto-cc ()
3010   "Move point to the Cc header."
3011   (interactive)
3012   (message-position-on-field "Cc" "To"))
3013
3014 (defun message-goto-bcc ()
3015   "Move point to the Bcc  header."
3016   (interactive)
3017   (message-position-on-field "Bcc" "Cc" "To"))
3018
3019 (defun message-goto-fcc ()
3020   "Move point to the Fcc header."
3021   (interactive)
3022   (message-position-on-field "Fcc" "To" "Newsgroups"))
3023
3024 (defun message-goto-reply-to ()
3025   "Move point to the Reply-To header."
3026   (interactive)
3027   (message-position-on-field "Reply-To" "Subject"))
3028
3029 (defun message-goto-newsgroups ()
3030   "Move point to the Newsgroups header."
3031   (interactive)
3032   (message-position-on-field "Newsgroups"))
3033
3034 (defun message-goto-distribution ()
3035   "Move point to the Distribution header."
3036   (interactive)
3037   (message-position-on-field "Distribution"))
3038
3039 (defun message-goto-followup-to ()
3040   "Move point to the Followup-To header."
3041   (interactive)
3042   (message-position-on-field "Followup-To" "Newsgroups"))
3043
3044 (defun message-goto-mail-followup-to ()
3045   "Move point to the Mail-Followup-To header."
3046   (interactive)
3047   (message-position-on-field "Mail-Followup-To" "To"))
3048
3049 (defun message-goto-keywords ()
3050   "Move point to the Keywords header."
3051   (interactive)
3052   (message-position-on-field "Keywords" "Subject"))
3053
3054 (defun message-goto-summary ()
3055   "Move point to the Summary header."
3056   (interactive)
3057   (message-position-on-field "Summary" "Subject"))
3058
3059 (defun message-goto-body (&optional interactivep)
3060   "Move point to the beginning of the message body."
3061   (interactive (list t))
3062   (when (and interactivep
3063              (looking-at "[ \t]*\n"))
3064     (expand-abbrev))
3065   (goto-char (point-min))
3066   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
3067       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
3068
3069 (defun message-in-body-p ()
3070   "Return t if point is in the message body."
3071   (let ((body (save-excursion (message-goto-body) (point))))
3072     (>= (point) body)))
3073
3074 (defun message-goto-eoh ()
3075   "Move point to the end of the headers."
3076   (interactive)
3077   (message-goto-body)
3078   (forward-line -1))
3079
3080 (defun message-goto-signature ()
3081   "Move point to the beginning of the message signature.
3082 If there is no signature in the article, go to the end and
3083 return nil."
3084   (interactive)
3085   (goto-char (point-min))
3086   (if (re-search-forward message-signature-separator nil t)
3087       (forward-line 1)
3088     (goto-char (point-max))
3089     nil))
3090
3091 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
3092   "Insert a reasonable MFT header in a post to an unsubscribed list.
3093 When making original posts to a mailing list you are not subscribed to,
3094 you have to type in a MFT header by hand.  The contents, usually, are
3095 the addresses of the list and your own address.  This function inserts
3096 such a header automatically.  It fetches the contents of the To: header
3097 in the current mail buffer, and appends the current `user-mail-address'.
3098
3099 If the optional argument INCLUDE-CC is non-nil, the addresses in the
3100 Cc: header are also put into the MFT."
3101
3102   (interactive "P")
3103   (let* (cc tos)
3104     (save-restriction
3105       (message-narrow-to-headers)
3106       (message-remove-header "Mail-Followup-To")
3107       (setq cc (and include-cc (message-fetch-field "Cc")))
3108       (setq tos (if cc
3109                     (concat (message-fetch-field "To") "," cc)
3110                   (message-fetch-field "To"))))
3111     (message-goto-mail-followup-to)
3112     (insert (concat tos ", " user-mail-address))))
3113
3114 \f
3115
3116 (defun message-insert-to (&optional force)
3117   "Insert a To header that points to the author of the article being replied to.
3118 If the original author requested not to be sent mail, don't insert unless the
3119 prefix FORCE is given."
3120   (interactive "P")
3121   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
3122          (dont (and mct (or (equal (downcase mct) "never")
3123                             (equal (downcase mct) "nobody"))))
3124          (to (or (message-fetch-reply-field "mail-reply-to")
3125                  (message-fetch-reply-field "reply-to")
3126                  (message-fetch-reply-field "from"))))
3127     (when (and dont to)
3128       (message
3129        (if force
3130            "Ignoring the user request not to have copies sent via mail"
3131          "Complying with the user request not to have copies sent via mail")))
3132     (when (and force (not to))
3133       (error "No mail address in the article"))
3134     (when (and to (or force (not dont)))
3135       (message-carefully-insert-headers (list (cons 'To to))))))
3136
3137 (defun message-insert-wide-reply ()
3138   "Insert To and Cc headers as if you were doing a wide reply."
3139   (interactive)
3140   (let ((headers (message-with-reply-buffer
3141                    (message-get-reply-headers t))))
3142     (message-carefully-insert-headers headers)))
3143
3144 (defcustom message-header-synonyms
3145   '((To Cc Bcc)
3146     (Original-To))
3147   "List of lists of header synonyms.
3148 E.g., if this list contains a member list with elements `Cc' and `To',
3149 then `message-carefully-insert-headers' will not insert a `To' header
3150 when the message is already `Cc'ed to the recipient."
3151   :version "22.1"
3152   :group 'message-headers
3153   :link '(custom-manual "(message)Message Headers")
3154   :type '(repeat sexp))
3155
3156 (defun message-carefully-insert-headers (headers)
3157   "Insert the HEADERS, an alist, into the message buffer.
3158 Does not insert the headers when they are already present there
3159 or in the synonym headers, defined by `message-header-synonyms'."
3160   ;; FIXME: Should compare only the address and not the full name.  Comparison
3161   ;; should be done case-folded (and with `string=' rather than
3162   ;; `string-match').
3163   ;; (mail-strip-quoted-names "Foo Bar <foo@bar>, bla@fasel (Bla Fasel)")
3164   (dolist (header headers)
3165     (let* ((header-name (symbol-name (car header)))
3166            (new-header (cdr header))
3167            (synonyms (loop for synonym in message-header-synonyms
3168                            when (memq (car header) synonym) return synonym))
3169            (old-header
3170             (loop for synonym in synonyms
3171                   for old-header = (mail-fetch-field (symbol-name synonym))
3172                   when (and old-header (string-match new-header old-header))
3173                   return synonym)))
3174       (if old-header
3175           (message "already have `%s' in `%s'" new-header old-header)
3176         (when (and (message-position-on-field header-name)
3177                    (setq old-header (mail-fetch-field header-name))
3178                    (not (string-match "\\` *\\'" old-header)))
3179           (insert ", "))
3180         (insert new-header)))))
3181
3182 (defun message-widen-reply ()
3183   "Widen the reply to include maximum recipients."
3184   (interactive)
3185   (let ((follow-to
3186          (and (bufferp message-reply-buffer)
3187               (buffer-name message-reply-buffer)
3188               (with-current-buffer message-reply-buffer
3189                 (message-get-reply-headers t)))))
3190     (save-excursion
3191       (save-restriction
3192         (message-narrow-to-headers)
3193         (dolist (elem follow-to)
3194           (message-remove-header (symbol-name (car elem)))
3195           (goto-char (point-min))
3196           (insert (symbol-name (car elem)) ": "
3197                   (cdr elem) "\n"))))))
3198
3199 (defun message-insert-newsgroups ()
3200   "Insert the Newsgroups header from the article being replied to."
3201   (interactive)
3202   (when (and (message-position-on-field "Newsgroups")
3203              (mail-fetch-field "newsgroups")
3204              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
3205     (insert ","))
3206   (insert (or (message-fetch-reply-field "newsgroups") "")))
3207
3208 \f
3209
3210 ;;; Various commands
3211
3212 (defun message-delete-not-region (beg end)
3213   "Delete everything in the body of the current message outside of the region."
3214   (interactive "r")
3215   (let (citeprefix)
3216     (save-excursion
3217       (goto-char beg)
3218       ;; snarf citation prefix, if appropriate
3219       (unless (eq (point) (progn (beginning-of-line) (point)))
3220         (when (looking-at message-cite-prefix-regexp)
3221           (setq citeprefix (match-string 0))))
3222       (goto-char end)
3223       (delete-region (point) (if (not (message-goto-signature))
3224                                  (point)
3225                                (forward-line -2)
3226                                (point)))
3227       (insert "\n")
3228       (goto-char beg)
3229       (delete-region beg (progn (message-goto-body)
3230                                 (forward-line 2)
3231                                 (point)))
3232       (when citeprefix
3233         (insert citeprefix))))
3234   (when (message-goto-signature)
3235     (forward-line -2)))
3236
3237 (defun message-kill-to-signature (&optional arg)
3238   "Kill all text up to the signature.
3239 If a numeric argument or prefix arg is given, leave that number
3240 of lines before the signature intact."
3241   (interactive "P")
3242   (save-excursion
3243     (save-restriction
3244       (let ((point (point)))
3245         (narrow-to-region point (point-max))
3246         (message-goto-signature)
3247         (unless (eobp)
3248           (if (and arg (numberp arg))
3249               (forward-line (- -1 arg))
3250             (end-of-line -1)))
3251         (unless (= point (point))
3252           (kill-region point (point))
3253           (unless (bolp)
3254             (insert "\n")))))))
3255
3256 (defun message-newline-and-reformat (&optional arg not-break)
3257   "Insert four newlines, and then reformat if inside quoted text.
3258 Prefix arg means justify as well."
3259   (interactive (list (if current-prefix-arg 'full)))
3260   (let (quoted point beg end leading-space bolp fill-paragraph-function)
3261     (setq point (point))
3262     (beginning-of-line)
3263     (setq beg (point))
3264     (setq bolp (= beg point))
3265     ;; Find first line of the paragraph.
3266     (if not-break
3267         (while (and (not (eobp))
3268                     (not (looking-at message-cite-prefix-regexp))
3269                     (looking-at paragraph-start))
3270           (forward-line 1)))
3271     ;; Find the prefix
3272     (when (looking-at message-cite-prefix-regexp)
3273       (setq quoted (match-string 0))
3274       (goto-char (match-end 0))
3275       (looking-at "[ \t]*")
3276       (setq leading-space (match-string 0)))
3277     (if (and quoted
3278              (not not-break)
3279              (not bolp)
3280              (< (- point beg) (length quoted)))
3281         ;; break inside the cite prefix.
3282         (setq quoted nil
3283               end nil))
3284     (if quoted
3285         (progn
3286           (forward-line 1)
3287           (while (and (not (eobp))
3288                       (not (looking-at paragraph-separate))
3289                       (looking-at message-cite-prefix-regexp)
3290                       (equal quoted (match-string 0)))
3291             (goto-char (match-end 0))
3292             (looking-at "[ \t]*")
3293             (if (> (length leading-space) (length (match-string 0)))
3294                 (setq leading-space (match-string 0)))
3295             (forward-line 1))
3296           (setq end (point))
3297           (goto-char beg)
3298           (while (and (if (bobp) nil (forward-line -1) t)
3299                       (not (looking-at paragraph-start))
3300                       (looking-at message-cite-prefix-regexp)
3301                       (equal quoted (match-string 0)))
3302             (setq beg (point))
3303             (goto-char (match-end 0))
3304             (looking-at "[ \t]*")
3305             (if (> (length leading-space) (length (match-string 0)))
3306                 (setq leading-space (match-string 0)))))
3307       (while (and (not (eobp))
3308                   (not (looking-at paragraph-separate))
3309                   (not (looking-at message-cite-prefix-regexp)))
3310         (forward-line 1))
3311       (setq end (point))
3312       (goto-char beg)
3313       (while (and (if (bobp) nil (forward-line -1) t)
3314                   (not (looking-at paragraph-start))
3315                   (not (looking-at message-cite-prefix-regexp)))
3316         (setq beg (point))))
3317     (goto-char point)
3318     (save-restriction
3319       (narrow-to-region beg end)
3320       (if not-break
3321           (setq point nil)
3322         (if bolp
3323             (newline)
3324           (newline)
3325           (newline))
3326         (setq point (point))
3327         ;; (newline 2) doesn't mark both newline's as hard, so call
3328         ;; newline twice. -jas
3329         (newline)
3330         (newline)
3331         (delete-region (point) (re-search-forward "[ \t]*"))
3332         (when (and quoted (not bolp))
3333           (insert quoted leading-space)))
3334       (undo-boundary)
3335       (if quoted
3336           (let* ((adaptive-fill-regexp
3337                   (regexp-quote (concat quoted leading-space)))
3338                  (adaptive-fill-first-line-regexp
3339                   adaptive-fill-regexp ))
3340             (fill-paragraph arg))
3341         (fill-paragraph arg))
3342       (if point (goto-char point)))))
3343
3344 (defun message-fill-paragraph (&optional arg)
3345   "Message specific function to fill a paragraph.
3346 This function is used as the value of `fill-paragraph-function' in
3347 Message buffers and is not meant to be called directly."
3348   (interactive (list (if current-prefix-arg 'full)))
3349   (if (if (boundp 'filladapt-mode) filladapt-mode)
3350       nil
3351     (if (message-point-in-header-p)
3352         (message-fill-field)
3353       (message-newline-and-reformat arg t))
3354     t))
3355
3356 (defun message-point-in-header-p ()
3357   "Return t if point is in the header."
3358   (save-excursion
3359     (not (re-search-backward
3360           (concat "^" (regexp-quote mail-header-separator) "\n") nil t))))
3361
3362 (defun message-do-auto-fill ()
3363   "Like `do-auto-fill', but don't fill in message header."
3364   (unless (message-point-in-header-p)
3365     (do-auto-fill)))
3366
3367 (defun message-insert-signature (&optional force)
3368   "Insert a signature.  See documentation for variable `message-signature'."
3369   (interactive (list 0))
3370   (let* ((signature
3371           (cond
3372            ((and (null message-signature)
3373                  (eq force 0))
3374             (save-excursion
3375               (goto-char (point-max))
3376               (not (re-search-backward message-signature-separator nil t))))
3377            ((and (null message-signature)
3378                  force)
3379             t)
3380            ((functionp message-signature)
3381             (funcall message-signature))
3382            ((listp message-signature)
3383             (eval message-signature))
3384            (t message-signature)))
3385          signature-file)
3386     (setq signature
3387           (cond ((stringp signature)
3388                  signature)
3389                 ((and (eq t signature) message-signature-file)
3390                  (setq signature-file
3391                        (if (and message-signature-directory
3392                                 ;; don't actually use the signature directory
3393                                 ;; if message-signature-file contains a path.
3394                                 (not (file-name-directory
3395                                       message-signature-file)))
3396                            (expand-file-name message-signature-file
3397                                              message-signature-directory)
3398                          message-signature-file))
3399                  (file-exists-p signature-file))))
3400     (when signature
3401       (goto-char (point-max))
3402       ;; Insert the signature.
3403       (unless (bolp)
3404         (insert "\n"))
3405       (when message-signature-insert-empty-line
3406         (insert "\n"))
3407       (insert "-- \n")
3408       (if (eq signature t)
3409           (insert-file-contents signature-file)
3410         (insert signature))
3411       (goto-char (point-max))
3412       (or (bolp) (insert "\n")))))
3413
3414 (defun message-insert-importance-high ()
3415   "Insert header to mark message as important."
3416   (interactive)
3417   (save-excursion
3418     (save-restriction
3419       (message-narrow-to-headers)
3420       (message-remove-header "Importance"))
3421     (message-goto-eoh)
3422     (insert "Importance: high\n")))
3423
3424 (defun message-insert-importance-low ()
3425   "Insert header to mark message as unimportant."
3426   (interactive)
3427   (save-excursion
3428     (save-restriction
3429       (message-narrow-to-headers)
3430       (message-remove-header "Importance"))
3431     (message-goto-eoh)
3432     (insert "Importance: low\n")))
3433
3434 (defun message-insert-or-toggle-importance ()
3435   "Insert a \"Importance: high\" header, or cycle through the header values.
3436 The three allowed values according to RFC 1327 are `high', `normal'
3437 and `low'."
3438   (interactive)
3439   (save-excursion
3440     (let ((new "high")
3441           cur)
3442       (save-restriction
3443         (message-narrow-to-headers)
3444         (when (setq cur (message-fetch-field "Importance"))
3445           (message-remove-header "Importance")
3446           (setq new (cond ((string= cur "high")
3447                            "low")
3448                           ((string= cur "low")
3449                            "normal")
3450                           (t
3451                            "high")))))
3452       (message-goto-eoh)
3453       (insert (format "Importance: %s\n" new)))))
3454
3455 (defun message-insert-disposition-notification-to ()
3456   "Request a disposition notification (return receipt) to this message.
3457 Note that this should not be used in newsgroups."
3458   (interactive)
3459   (save-excursion
3460     (save-restriction
3461       (message-narrow-to-headers)
3462       (message-remove-header "Disposition-Notification-To"))
3463     (message-goto-eoh)
3464     (insert (format "Disposition-Notification-To: %s\n"
3465                     (or (message-field-value "Reply-to")
3466                         (message-field-value "From")
3467                         (message-make-from))))))
3468
3469 (defun message-elide-region (b e)
3470   "Elide the text in the region.
3471 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3472 text was killed."
3473   (interactive "r")
3474   (kill-region b e)
3475   (insert message-elide-ellipsis))
3476
3477 (defvar message-caesar-translation-table nil)
3478
3479 (defun message-caesar-region (b e &optional n)
3480   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3481   (interactive
3482    (list
3483     (min (point) (or (mark t) (point)))
3484     (max (point) (or (mark t) (point)))
3485     (when current-prefix-arg
3486       (prefix-numeric-value current-prefix-arg))))
3487
3488   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3489   (unless (or (zerop n)                 ; no action needed for a rot of 0
3490               (= b e))                  ; no region to rotate
3491     ;; We build the table, if necessary.
3492     (when (or (not message-caesar-translation-table)
3493               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3494       (setq message-caesar-translation-table
3495             (message-make-caesar-translation-table n)))
3496     (translate-region b e message-caesar-translation-table)))
3497
3498 (defun message-make-caesar-translation-table (n)
3499   "Create a rot table with offset N."
3500   (let ((i -1)
3501         (table (make-string 256 0)))
3502     (while (< (incf i) 256)
3503       (aset table i i))
3504     (concat
3505      (substring table 0 ?A)
3506      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3507      (substring table ?A (+ ?A n))
3508      (substring table (+ ?A 26) ?a)
3509      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3510      (substring table ?a (+ ?a n))
3511      (substring table (+ ?a 26) 255))))
3512
3513 (defun message-caesar-buffer-body (&optional rotnum wide)
3514   "Caesar rotate all letters in the current buffer by 13 places.
3515 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3516 With prefix arg, specifies the number of places to rotate each letter forward.
3517 Mail and USENET news headers are not rotated unless WIDE is non-nil."
3518   (interactive (if current-prefix-arg
3519                    (list (prefix-numeric-value current-prefix-arg))
3520                  (list nil)))
3521   (save-excursion
3522     (save-restriction
3523       (when (and (not wide) (message-goto-body))
3524         (narrow-to-region (point) (point-max)))
3525       (message-caesar-region (point-min) (point-max) rotnum))))
3526
3527 (defun message-pipe-buffer-body (program)
3528   "Pipe the message body in the current buffer through PROGRAM."
3529   (save-excursion
3530     (save-restriction
3531       (when (message-goto-body)
3532         (narrow-to-region (point) (point-max)))
3533       (shell-command-on-region
3534        (point-min) (point-max) program nil t))))
3535
3536 (defun message-rename-buffer (&optional enter-string)
3537   "Rename the *message* buffer to \"*message* RECIPIENT\".
3538 If the function is run with a prefix, it will ask for a new buffer
3539 name, rather than giving an automatic name."
3540   (interactive "Pbuffer name: ")
3541   (save-excursion
3542     (save-restriction
3543       (goto-char (point-min))
3544       (narrow-to-region (point)
3545                         (search-forward mail-header-separator nil 'end))
3546       (let* ((mail-to (or
3547                        (if (message-news-p) (message-fetch-field "Newsgroups")
3548                          (message-fetch-field "To"))
3549                        ""))
3550              (mail-trimmed-to
3551               (if (string-match "," mail-to)
3552                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3553                 mail-to))
3554              (name-default (concat "*message* " mail-trimmed-to))
3555              (name (if enter-string
3556                        (read-string "New buffer name: " name-default)
3557                      name-default)))
3558         (rename-buffer name t)))))
3559
3560 (defun message-fill-yanked-message (&optional justifyp)
3561   "Fill the paragraphs of a message yanked into this one.
3562 Numeric argument means justify as well."
3563   (interactive "P")
3564   (save-excursion
3565     (goto-char (point-min))
3566     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3567     (let ((fill-prefix message-yank-prefix))
3568       (fill-individual-paragraphs (point) (point-max) justifyp))))
3569
3570 (defun message-indent-citation (&optional start end yank-only)
3571   "Modify text just inserted from a message to be cited.
3572 The inserted text should be the region.
3573 When this function returns, the region is again around the modified text.
3574
3575 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3576 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3577   (unless start (setq start (point)))
3578   (unless yank-only
3579     ;; Remove unwanted headers.
3580     (when message-ignored-cited-headers
3581       (let (all-removed)
3582         (save-restriction
3583           (narrow-to-region
3584            (goto-char start)
3585            (if (search-forward "\n\n" nil t)
3586                (1- (point))
3587              (point)))
3588           (message-remove-header message-ignored-cited-headers t)
3589           (when (= (point-min) (point-max))
3590             (setq all-removed t))
3591           (goto-char (point-max)))
3592         (if all-removed
3593             (goto-char start)
3594           (forward-line 1))))
3595     ;; Delete blank lines at the start of the buffer.
3596     (while (and (point-min)
3597                 (eolp)
3598                 (not (eobp)))
3599       (message-delete-line))
3600     ;; Delete blank lines at the end of the buffer.
3601     (goto-char (point-max))
3602     (unless (eolp)
3603       (insert "\n"))
3604     (while (and (zerop (forward-line -1))
3605                 (looking-at "$"))
3606       (message-delete-line)))
3607   ;; Do the indentation.
3608   (if (null message-yank-prefix)
3609       (indent-rigidly start (or end (mark t)) message-indentation-spaces)
3610     (save-excursion
3611       (goto-char start)
3612       (while (< (point) (or end (mark t)))
3613         (cond ((looking-at ">")
3614                (insert message-yank-cited-prefix))
3615               ((looking-at "^$")
3616                (insert message-yank-empty-prefix))
3617               (t
3618                (insert message-yank-prefix)))
3619         (forward-line 1))))
3620   (goto-char start))
3621
3622 (defun message-remove-blank-cited-lines (&optional remove)
3623   "Remove cited lines containing only blanks.
3624 If REMOVE is non-nil, remove newlines, too.
3625
3626 To use this automatically, you may add this function to
3627 `gnus-message-setup-hook'."
3628   (interactive "P")
3629   (let ((citexp
3630          (concat
3631           "^\\("
3632           (when (boundp 'message-yank-cited-prefix)
3633             (concat message-yank-cited-prefix "\\|"))
3634           message-yank-prefix
3635           "\\)+ *\n"
3636           )))
3637     (gnus-message 8 "removing `%s'" citexp)
3638     (save-excursion
3639       (message-goto-body)
3640       (while (re-search-forward citexp nil t)
3641         (replace-match (if remove "" "\n"))))))
3642
3643 (defvar message-cite-reply-above nil
3644   "If non-nil, start own text above the quote.
3645
3646 Note: Top posting is bad netiquette.  Don't use it unless you
3647 really must.  You probably want to set variable only for specific
3648 groups, e.g. using `gnus-posting-styles':
3649
3650   (eval (set (make-local-variable 'message-cite-reply-above) t))
3651
3652 This variable has no effect in news postings.")
3653
3654 (defun message-yank-original (&optional arg)
3655   "Insert the message being replied to, if any.
3656 Puts point before the text and mark after.
3657 Normally indents each nonblank line ARG spaces (default 3).  However,
3658 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3659
3660 This function uses `message-cite-function' to do the actual citing.
3661
3662 Just \\[universal-argument] as argument means don't indent, insert no
3663 prefix, and don't delete any headers."
3664   (interactive "P")
3665   (let ((modified (buffer-modified-p))
3666         body-text)
3667     (when (and message-reply-buffer
3668                message-cite-function)
3669       (when message-cite-reply-above
3670         (if (and (not (message-news-p))
3671                  (or (eq message-cite-reply-above 'is-evil)
3672                      (y-or-n-p "\
3673 Top posting is bad netiquette.  Please don't top post unless you really must.
3674 Really top post? ")))
3675             (save-excursion
3676               (setq body-text
3677                     (buffer-substring (message-goto-body)
3678                                       (point-max)))
3679               (delete-region (message-goto-body) (point-max)))
3680           (set (make-local-variable 'message-cite-reply-above) nil)))
3681       (if (bufferp message-reply-buffer)
3682           (delete-windows-on message-reply-buffer t))
3683       (push-mark (save-excursion
3684                    (cond
3685                     ((bufferp message-reply-buffer)
3686                      (insert-buffer-substring message-reply-buffer))
3687                     ((and (consp message-reply-buffer)
3688                           (functionp (car message-reply-buffer)))
3689                      (apply (car message-reply-buffer)
3690                             (cdr message-reply-buffer))))
3691                    (unless (bolp)
3692                      (insert ?\n))
3693                    (point)))
3694       (unless arg
3695         (funcall message-cite-function)
3696         (unless (eq (char-before (mark t)) ?\n)
3697           (let ((pt (point)))
3698             (goto-char (mark t))
3699             (insert-before-markers ?\n)
3700             (goto-char pt))))
3701       (when message-cite-reply-above
3702         (message-goto-body)
3703         (insert body-text)
3704         (insert (if (bolp) "\n" "\n\n"))
3705         (message-goto-body))
3706       ;; Add a `message-setup-very-last-hook' here?
3707       ;; Add `gnus-article-highlight-citation' here?
3708       (unless modified
3709         (setq message-checksum (message-checksum))))))
3710
3711 (defun message-yank-buffer (buffer)
3712   "Insert BUFFER into the current buffer and quote it."
3713   (interactive "bYank buffer: ")
3714   (let ((message-reply-buffer (get-buffer buffer)))
3715     (save-window-excursion
3716       (message-yank-original))))
3717
3718 (defun message-buffers ()
3719   "Return a list of active message buffers."
3720   (let (buffers)
3721     (save-current-buffer
3722       (dolist (buffer (buffer-list t))
3723         (set-buffer buffer)
3724         (when (and (eq major-mode 'message-mode)
3725                    (null message-sent-message-via))
3726           (push (buffer-name buffer) buffers))))
3727     (nreverse buffers)))
3728
3729 (defun message-cite-original-1 (strip-signature)
3730   "Cite an original message.
3731 If STRIP-SIGNATURE is non-nil, strips off the signature from the
3732 original message.
3733
3734 This function uses `mail-citation-hook' if that is non-nil."
3735   (if (and (boundp 'mail-citation-hook)
3736            mail-citation-hook)
3737       (run-hooks 'mail-citation-hook)
3738     (let* ((start (point))
3739            (end (mark t))
3740            (x-no-archive nil)
3741            (functions
3742             (when message-indent-citation-function
3743               (if (listp message-indent-citation-function)
3744                   message-indent-citation-function
3745                 (list message-indent-citation-function))))
3746            ;; This function may be called by `gnus-summary-yank-message' and
3747            ;; may insert a different article from the original.  So, we will
3748            ;; modify the value of `message-reply-headers' with that article.
3749            (message-reply-headers
3750             (save-restriction
3751               (narrow-to-region start end)
3752               (message-narrow-to-head-1)
3753               (setq x-no-archive (message-fetch-field "x-no-archive"))
3754               (vector 0
3755                       (or (message-fetch-field "subject") "none")
3756                       (or (message-fetch-field "from") "nobody")
3757                       (message-fetch-field "date")
3758                       (message-fetch-field "message-id" t)
3759                       (message-fetch-field "references")
3760                       0 0 ""))))
3761       (mml-quote-region start end)
3762       (when strip-signature
3763         ;; Allow undoing.
3764         (undo-boundary)
3765         (goto-char end)
3766         (when (re-search-backward message-signature-separator start t)
3767           ;; Also peel off any blank lines before the signature.
3768           (forward-line -1)
3769           (while (looking-at "^[ \t]*$")
3770             (forward-line -1))
3771           (forward-line 1)
3772           (delete-region (point) end)
3773           (unless (search-backward "\n\n" start t)
3774             ;; Insert a blank line if it is peeled off.
3775             (insert "\n"))))
3776       (goto-char start)
3777       (mapc 'funcall functions)
3778       (when message-citation-line-function
3779         (unless (bolp)
3780           (insert "\n"))
3781         (funcall message-citation-line-function))
3782       (when (and x-no-archive
3783                  (not message-cite-articles-with-x-no-archive)
3784                  (string-match "yes" x-no-archive))
3785         (undo-boundary)
3786         (delete-region (point) (mark t))
3787         (insert "> [Quoted text removed due to X-No-Archive]\n")
3788         (push-mark)
3789         (forward-line -1)))))
3790
3791 (defun message-cite-original ()
3792   "Cite function in the standard Message manner."
3793   (message-cite-original-1 nil))
3794
3795 (defvar gnus-extract-address-components)
3796
3797 (autoload 'format-spec "format-spec")
3798
3799 (defun message-insert-formatted-citation-line (&optional from date)
3800   "Function that inserts a formatted citation line.
3801
3802 See `message-citation-line-format'."
3803   ;; The optional args are for testing/debugging.  They will disappear later.
3804   ;; Example:
3805   ;; (with-temp-buffer
3806   ;;   (message-insert-formatted-citation-line
3807   ;;    "John Doe <john.doe@example.invalid>"
3808   ;;    (current-time))
3809   ;;   (buffer-string))
3810   (when (or message-reply-headers (and from date))
3811     (unless from
3812       (setq from (mail-header-from message-reply-headers)))
3813     (let* ((data (condition-case ()
3814                      (funcall (if (boundp gnus-extract-address-components)
3815                                   gnus-extract-address-components
3816                                 'mail-extract-address-components)
3817                               from)
3818                    (error nil)))
3819            (name (car data))
3820            (fname name)
3821            (lname name)
3822            (net (car (cdr data)))
3823            (name-or-net (or (car data)
3824                             (car (cdr data)) from))
3825            (replydate
3826             (or
3827              date
3828              ;; We need Gnus functionality if the user wants date or time from
3829              ;; the original article:
3830              (when (string-match "%[^fnNFL]" message-citation-line-format)
3831                (autoload 'gnus-date-get-time "gnus-util")
3832                (gnus-date-get-time (mail-header-date message-reply-headers)))))
3833            (flist
3834             (let ((i ?A) lst)
3835               (when (stringp name)
3836                 ;; Guess first name and last name:
3837                 (cond ((string-match
3838                         "\\`\\(\\w\\|[-.]\\)+ \\(\\w\\|[-.]\\)+\\'" name)
3839                        (setq fname (nth 0 (split-string name "[ \t]+"))
3840                              lname (nth 1 (split-string name "[ \t]+"))))
3841                       ((string-match
3842                         "\\`\\(\\w\\|[-.]\\)+, \\(\\w\\|[-.]\\)+\\'" name)
3843                        (setq fname (nth 1 (split-string name "[ \t,]+"))
3844                              lname (nth 0 (split-string name "[ \t,]+"))))
3845                       ((string-match
3846                         "\\`\\(\\w\\|[-.]\\)+\\'" name)
3847                        (setq fname name
3848                              lname ""))))
3849               ;; The following letters are not used in `format-time-string':
3850               (push ?E lst) (push "<E>" lst)
3851               (push ?F lst) (push fname lst)
3852               ;; We might want to use "" instead of "<X>" later.
3853               (push ?J lst) (push "<J>" lst)
3854               (push ?K lst) (push "<K>" lst)
3855               (push ?L lst) (push lname lst)
3856               (push ?N lst) (push name-or-net lst)
3857               (push ?O lst) (push "<O>" lst)
3858               (push ?P lst) (push "<P>" lst)
3859               (push ?Q lst) (push "<Q>" lst)
3860               (push ?f lst) (push from lst)
3861               (push ?i lst) (push "<i>" lst)
3862               (push ?n lst) (push net lst)
3863               (push ?o lst) (push "<o>" lst)
3864               (push ?q lst) (push "<q>" lst)
3865               (push ?t lst) (push "<t>" lst)
3866               (push ?v lst) (push "<v>" lst)
3867               ;; Delegate the rest to `format-time-string':
3868               (while (<= i ?z)
3869                 (when (and (not (memq i lst))
3870                            ;; Skip (Z,a)
3871                            (or (<= i ?Z)
3872                                (>= i ?a)))
3873                   (push i lst)
3874                   (push (condition-case nil
3875                             (format-time-string (format "%%%c" i) replydate)
3876                           (error (format ">%c<" i)))
3877                         lst))
3878                 (setq i (1+ i)))
3879               (reverse lst)))
3880            (spec (apply 'format-spec-make flist)))
3881       (insert (format-spec message-citation-line-format spec)))
3882     (newline)))
3883
3884 (defun message-cite-original-without-signature ()
3885   "Cite function in the standard Message manner.
3886 This function strips off the signature from the original message."
3887   (message-cite-original-1 t))
3888
3889 (defun message-insert-citation-line ()
3890   "Insert a simple citation line."
3891   (when message-reply-headers
3892     (insert (mail-header-from message-reply-headers) " writes:")
3893     (newline)
3894     (newline)))
3895
3896 (defun message-position-on-field (header &rest afters)
3897   (let ((case-fold-search t))
3898     (save-restriction
3899       (narrow-to-region
3900        (goto-char (point-min))
3901        (progn
3902          (re-search-forward
3903           (concat "^" (regexp-quote mail-header-separator) "$"))
3904          (match-beginning 0)))
3905       (goto-char (point-min))
3906       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3907           (progn
3908             (re-search-forward "^[^ \t]" nil 'move)
3909             (beginning-of-line)
3910             (skip-chars-backward "\n")
3911             t)
3912         (while (and afters
3913                     (not (re-search-forward
3914                           (concat "^" (regexp-quote (car afters)) ":")
3915                           nil t)))
3916           (pop afters))
3917         (when afters
3918           (re-search-forward "^[^ \t]" nil 'move)
3919           (beginning-of-line))
3920         (insert header ": \n")
3921         (forward-char -1)
3922         nil))))
3923
3924 (defun message-remove-signature ()
3925   "Remove the signature from the text between point and mark.
3926 The text will also be indented the normal way."
3927   (save-excursion
3928     (let ((start (point))
3929           mark)
3930       (if (not (re-search-forward message-signature-separator (mark t) t))
3931           ;; No signature here, so we just indent the cited text.
3932           (message-indent-citation)
3933         ;; Find the last non-empty line.
3934         (forward-line -1)
3935         (while (looking-at "[ \t]*$")
3936           (forward-line -1))
3937         (forward-line 1)
3938         (setq mark (set-marker (make-marker) (point)))
3939         (goto-char start)
3940         (message-indent-citation)
3941         ;; Enable undoing the deletion.
3942         (undo-boundary)
3943         (delete-region mark (mark t))
3944         (set-marker mark nil)))))
3945
3946 \f
3947
3948 ;;;
3949 ;;; Sending messages
3950 ;;;
3951
3952 (defun message-send-and-exit (&optional arg)
3953   "Send message like `message-send', then, if no errors, exit from mail buffer."
3954   (interactive "P")
3955   (let ((buf (current-buffer))
3956         (actions message-exit-actions))
3957     (when (and (message-send arg)
3958                (buffer-name buf))
3959       (if message-kill-buffer-on-exit
3960           (kill-buffer buf)
3961         (bury-buffer buf)
3962         (when (eq buf (current-buffer))
3963           (message-bury buf)))
3964       (message-do-actions actions)
3965       t)))
3966
3967 (defun message-dont-send ()
3968   "Don't send the message you have been editing.
3969 Instead, just auto-save the buffer and then bury it."
3970   (interactive)
3971   (set-buffer-modified-p t)
3972   (save-buffer)
3973   (let ((actions message-postpone-actions))
3974     (message-bury (current-buffer))
3975     (message-do-actions actions)))
3976
3977 (defun message-kill-buffer ()
3978   "Kill the current buffer."
3979   (interactive)
3980   (when (or (not (buffer-modified-p))
3981             (not message-kill-buffer-query)
3982             (yes-or-no-p "Message modified; kill anyway? "))
3983     (let ((actions message-kill-actions)
3984           (draft-article message-draft-article)
3985           (auto-save-file-name buffer-auto-save-file-name)
3986           (file-name buffer-file-name)
3987           (modified (buffer-modified-p)))
3988       (setq buffer-file-name nil)
3989       (kill-buffer (current-buffer))
3990       (when (and (or (and auto-save-file-name
3991                           (file-exists-p auto-save-file-name))
3992                      (and file-name
3993                           (file-exists-p file-name)))
3994                  (progn
3995                    ;; If the message buffer has lived in a dedicated window,
3996                    ;; `kill-buffer' has killed the frame.  Thus the
3997                    ;; `yes-or-no-p' may show up in a lowered frame.  Make sure
3998                    ;; that the user can see the question by raising the
3999                    ;; current frame:
4000                    (raise-frame)
4001                    (yes-or-no-p (format "Remove the backup file%s? "
4002                                         (if modified " too" "")))))
4003         (ignore-errors
4004           (delete-file auto-save-file-name))
4005         (let ((message-draft-article draft-article))
4006           (message-disassociate-draft)))
4007       (message-do-actions actions))))
4008
4009 (defun message-bury (buffer)
4010   "Bury this mail BUFFER."
4011   (let ((newbuf (other-buffer buffer)))
4012     (bury-buffer buffer)
4013     (if (and (window-dedicated-p (selected-window))
4014              (not (null (delq (selected-frame) (visible-frame-list)))))
4015         (delete-frame (selected-frame))
4016       (switch-to-buffer newbuf))))
4017
4018 (defun message-send (&optional arg)
4019   "Send the message in the current buffer.
4020 If `message-interactive' is non-nil, wait for success indication or
4021 error messages, and inform user.
4022 Otherwise any failure is reported in a message back to the user from
4023 the mailer.
4024 The usage of ARG is defined by the instance that called Message.
4025 It should typically alter the sending method in some way or other."
4026   (interactive "P")
4027   ;; Make it possible to undo the coming changes.
4028   (undo-boundary)
4029   (let ((inhibit-read-only t))
4030     (put-text-property (point-min) (point-max) 'read-only nil))
4031   (message-fix-before-sending)
4032   (run-hooks 'message-send-hook)
4033   (when message-confirm-send
4034     (or (y-or-n-p "Send message? ")
4035         (keyboard-quit)))
4036   (message message-sending-message)
4037   (let ((alist message-send-method-alist)
4038         (success t)
4039         elem sent dont-barf-on-no-method
4040         (message-options message-options))
4041     (message-options-set-recipient)
4042     (while (and success
4043                 (setq elem (pop alist)))
4044       (when (funcall (cadr elem))
4045         (when (and (or (not (memq (car elem)
4046                                   message-sent-message-via))
4047                        (message-fetch-field "supersedes")
4048                        (if (or (message-gnksa-enable-p 'multiple-copies)
4049                                (not (eq (car elem) 'news)))
4050                            (y-or-n-p
4051                             (format
4052                              "Already sent message via %s; resend? "
4053                              (car elem)))
4054                          (error "Denied posting -- multiple copies")))
4055                    (setq success (funcall (caddr elem) arg)))
4056           (setq sent t))))
4057     (unless (or sent
4058                 (not success)
4059                 (let ((fcc (message-fetch-field "Fcc"))
4060                       (gcc (message-fetch-field "Gcc")))
4061                   (when (or fcc gcc)
4062                     (or (eq message-allow-no-recipients 'always)
4063                         (and (not (eq message-allow-no-recipients 'never))
4064                              (setq dont-barf-on-no-method
4065                                    (gnus-y-or-n-p
4066                                     (format "No receiver, perform %s anyway? "
4067                                             (cond ((and fcc gcc) "Fcc and Gcc")
4068                                                   (fcc "Fcc")
4069                                                   (t "Gcc"))))))))))
4070       (error "No methods specified to send by"))
4071     (when (or dont-barf-on-no-method
4072               (and success sent))
4073       (message-do-fcc)
4074       (save-excursion
4075         (run-hooks 'message-sent-hook))
4076       (message "Sending...done")
4077       ;; Do ecomplete address snarfing.
4078       (when (and (message-mail-alias-type-p 'ecomplete)
4079                  (not message-inhibit-ecomplete))
4080         (message-put-addresses-in-ecomplete))
4081       ;; Mark the buffer as unmodified and delete auto-save.
4082       (set-buffer-modified-p nil)
4083       (delete-auto-save-file-if-necessary t)
4084       (message-disassociate-draft)
4085       ;; Delete other mail buffers and stuff.
4086       (message-do-send-housekeeping)
4087       (message-do-actions message-send-actions)
4088       ;; Return success.
4089       t)))
4090
4091 (defun message-send-via-mail (arg)
4092   "Send the current message via mail."
4093   (message-send-mail arg))
4094
4095 (defun message-send-via-news (arg)
4096   "Send the current message via news."
4097   (funcall message-send-news-function arg))
4098
4099 (defmacro message-check (type &rest forms)
4100   "Eval FORMS if TYPE is to be checked."
4101   `(or (message-check-element ,type)
4102        (save-excursion
4103          ,@forms)))
4104
4105 (put 'message-check 'lisp-indent-function 1)
4106 (put 'message-check 'edebug-form-spec '(form body))
4107
4108 (defun message-text-with-property (prop &optional start end reverse)
4109   "Return a list of start and end positions where the text has PROP.
4110 START and END bound the search, they default to `point-min' and
4111 `point-max' respectively.  If REVERSE is non-nil, find text which does
4112 not have PROP."
4113   (unless start
4114     (setq start (point-min)))
4115   (unless end
4116     (setq end (point-max)))
4117   (let (next regions)
4118     (if reverse
4119         (while (and start
4120                     (setq start (text-property-any start end prop nil)))
4121           (setq next (next-single-property-change start prop nil end))
4122           (push (cons start (or next end)) regions)
4123           (setq start next))
4124       (while (and start
4125                   (or (get-text-property start prop)
4126                       (and (setq start (next-single-property-change
4127                                         start prop nil end))
4128                            (get-text-property start prop))))
4129         (setq next (text-property-any start end prop nil))
4130         (push (cons start (or next end)) regions)
4131         (setq start next)))
4132     (nreverse regions)))
4133
4134 (defcustom message-bogus-addresses
4135   ;; '("noreply" "nospam" "invalid")
4136   '("noreply" "nospam" "invalid" "@@" "[^[:ascii:]].*@" "[ \t]")
4137   "List of regexps of potentially bogus mail addresses.
4138 See `message-check-recipients' how to setup checking.
4139
4140 This list should make it possible to catch typos or warn about
4141 spam-trap addresses.  It doesn't aim to verify strict RFC
4142 conformance."
4143   :version "23.1" ;; No Gnus
4144   :group 'message-headers
4145   :type '(choice
4146           (const :tag "None" nil)
4147           (list
4148            (set :inline t
4149                 (const "noreply")
4150                 (const "nospam")
4151                 (const "invalid")
4152                 (const :tag "duplicate @" "@@")
4153                 (const :tag "non-ascii local part" "[^[:ascii:]].*@")
4154                 ;; Already caught by `message-valid-fqdn-regexp'
4155                 ;; (const :tag "`_' in domain part" "@.*_")
4156                 (const :tag "whitespace" "[ \t]"))
4157            (repeat :inline t
4158                    :tag "Other"
4159                    (regexp)))))
4160
4161 (defun message-fix-before-sending ()
4162   "Do various things to make the message nice before sending it."
4163   ;; Make sure there's a newline at the end of the message.
4164   (goto-char (point-max))
4165   (unless (bolp)
4166     (insert "\n"))
4167   ;; Make the hidden headers visible.
4168   (widen)
4169   ;; Sort headers before sending the message.
4170   (message-sort-headers)
4171   ;; Make invisible text visible.
4172   ;; It doesn't seem as if this is useful, since the invisible property
4173   ;; is clobbered by an after-change hook anyhow.
4174   (message-check 'invisible-text
4175     (let ((regions (message-text-with-property 'invisible))
4176           from to)
4177       (when regions
4178         (while regions
4179           (setq from (caar regions)
4180                 to (cdar regions)
4181                 regions (cdr regions))
4182           (put-text-property from to 'invisible nil)
4183           (message-overlay-put (message-make-overlay from to)
4184                                'face 'highlight))
4185         (unless (yes-or-no-p
4186                  "Invisible text found and made visible; continue sending? ")
4187           (error "Invisible text found and made visible")))))
4188   (message-check 'illegible-text
4189     (let (char found choice)
4190       (message-goto-body)
4191       (while (progn
4192                (skip-chars-forward mm-7bit-chars)
4193                (when (get-text-property (point) 'no-illegible-text)
4194                  ;; There is a signed or encrypted raw message part
4195                  ;; that is considered to be safe.
4196                  (goto-char (or (next-single-property-change
4197                                  (point) 'no-illegible-text)
4198                                 (point-max))))
4199                (setq char (char-after)))
4200         (when (or (< (mm-char-int char) 128)
4201                   (and (mm-multibyte-p)
4202                        (memq (char-charset char)
4203                              '(eight-bit-control eight-bit-graphic
4204                                                  ;; Emacs 23, Bug#1770:
4205                                                  eight-bit
4206                                                  control-1))
4207                        (not (get-text-property
4208                              (point) 'untranslated-utf-8))))
4209           (message-overlay-put (message-make-overlay (point) (1+ (point)))
4210                                'face 'highlight)
4211           (setq found t))
4212         (forward-char))
4213       (when found
4214         (setq choice
4215               (gnus-multiple-choice
4216                "Non-printable characters found.  Continue sending?"
4217                `((?d "Remove non-printable characters and send")
4218                  (?r ,(format
4219                        "Replace non-printable characters with \"%s\" and send"
4220                        message-replacement-char))
4221                  (?i "Ignore non-printable characters and send")
4222                  (?e "Continue editing"))))
4223         (if (eq choice ?e)
4224           (error "Non-printable characters"))
4225         (message-goto-body)
4226         (skip-chars-forward mm-7bit-chars)
4227         (while (not (eobp))
4228           (when (let ((char (char-after)))
4229                   (or (< (mm-char-int char) 128)
4230                       (and (mm-multibyte-p)
4231                            ;; FIXME: Wrong for Emacs 23 (unicode) and for
4232                            ;; things like undecodable utf-8 (in Emacs 21?).
4233                            ;; Should at least use find-coding-systems-region.
4234                            ;; -- fx
4235                            (memq (char-charset char)
4236                                  '(eight-bit-control eight-bit-graphic
4237                                                      ;; Emacs 23, Bug#1770:
4238                                                      eight-bit
4239                                                      control-1))
4240                            (not (get-text-property
4241                                  (point) 'untranslated-utf-8)))))
4242             (if (eq choice ?i)
4243                 (message-kill-all-overlays)
4244               (delete-char 1)
4245               (when (eq choice ?r)
4246                 (insert message-replacement-char))))
4247           (forward-char)
4248           (skip-chars-forward mm-7bit-chars)))))
4249   (message-check 'bogus-recipient
4250     ;; Warn before sending a mail to an invalid address.
4251     (message-check-recipients)))
4252
4253 (defun message-bogus-recipient-p (recipients)
4254   "Check if a mail address in RECIPIENTS looks bogus.
4255
4256 RECIPIENTS is a mail header.  Return a list of potentially bogus
4257 addresses.  If none is found, return nil.
4258
4259 An address might be bogus if the domain part is not fully
4260 qualified, see `message-valid-fqdn-regexp', or if there's a
4261 matching entry in `message-bogus-addresses'."
4262   ;; FIXME: How about "foo@subdomain", when the MTA adds ".domain.tld"?
4263   (let (found)
4264     (mapc (lambda (address)
4265             (setq address (cadr address))
4266             (when
4267                 (or (not
4268                      (or
4269                       (not (string-match "@" address))
4270                       (string-match
4271                        (concat ".@.*\\("
4272                                message-valid-fqdn-regexp "\\)\\'") address)))
4273                     (and message-bogus-addresses
4274                          (let ((re
4275                                 (if (listp message-bogus-addresses)
4276                                     (mapconcat 'identity
4277                                                message-bogus-addresses
4278                                                "\\|")
4279                                   message-bogus-addresses)))
4280                            (string-match re address))))
4281                          (push address found)))
4282           ;;
4283           (mail-extract-address-components recipients t))
4284     found))
4285
4286 (defun message-check-recipients ()
4287   "Warn before composing or sending a mail to an invalid address.
4288
4289 This function could be useful in `message-setup-hook'."
4290   (interactive)
4291   (save-restriction
4292     (message-narrow-to-headers)
4293     (dolist (hdr '("To" "Cc" "Bcc"))
4294       (let ((addr (message-fetch-field hdr)))
4295         (when (stringp addr)
4296           (dolist (bog (message-bogus-recipient-p addr))
4297             (and bog
4298                  (not (y-or-n-p
4299                        (format
4300                         "Address `%s' might be bogus.  Continue? " bog)))
4301                  (error "Bogus address"))))))))
4302
4303 (custom-add-option 'message-setup-hook 'message-check-recipients)
4304
4305 (defun message-add-action (action &rest types)
4306   "Add ACTION to be performed when doing an exit of type TYPES."
4307   (while types
4308     (add-to-list (intern (format "message-%s-actions" (pop types)))
4309                  action)))
4310
4311 (defun message-delete-action (action &rest types)
4312   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
4313   (let (var)
4314     (while types
4315       (set (setq var (intern (format "message-%s-actions" (pop types))))
4316            (delq action (symbol-value var))))))
4317
4318 (defun message-do-actions (actions)
4319   "Perform all actions in ACTIONS."
4320   ;; Now perform actions on successful sending.
4321   (dolist (action actions)
4322     (ignore-errors
4323       (cond
4324        ;; A simple function.
4325        ((functionp action)
4326         (funcall action))
4327        ;; Something to be evaled.
4328        (t
4329         (eval action))))))
4330
4331 (defun message-send-mail-partially ()
4332   "Send mail as message/partial."
4333   ;; replace the header delimiter with a blank line
4334   (goto-char (point-min))
4335   (re-search-forward
4336    (concat "^" (regexp-quote mail-header-separator) "\n"))
4337   (replace-match "\n")
4338   (run-hooks 'message-send-mail-hook)
4339   (let ((p (goto-char (point-min)))
4340         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
4341         (curbuf (current-buffer))
4342         (id (message-make-message-id)) (n 1)
4343         plist total  header required-mail-headers)
4344     (while (not (eobp))
4345       (if (< (point-max) (+ p message-send-mail-partially-limit))
4346           (goto-char (point-max))
4347         (goto-char (+ p message-send-mail-partially-limit))
4348         (beginning-of-line)
4349         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
4350       (push p plist)
4351       (setq p (point)))
4352     (setq total (length plist))
4353     (push (point-max) plist)
4354     (setq plist (nreverse plist))
4355     (unwind-protect
4356         (save-excursion
4357           (setq p (pop plist))
4358           (while plist
4359             (set-buffer curbuf)
4360             (copy-to-buffer tembuf p (car plist))
4361             (set-buffer tembuf)
4362             (goto-char (point-min))
4363             (if header
4364                 (progn
4365                   (goto-char (point-min))
4366                   (narrow-to-region (point) (point))
4367                   (insert header))
4368               (message-goto-eoh)
4369               (setq header (buffer-substring (point-min) (point)))
4370               (goto-char (point-min))
4371               (narrow-to-region (point) (point))
4372               (insert header)
4373               (message-remove-header "Mime-Version")
4374               (message-remove-header "Content-Type")
4375               (message-remove-header "Content-Transfer-Encoding")
4376               (message-remove-header "Message-ID")
4377               (message-remove-header "Lines")
4378               (goto-char (point-max))
4379               (insert "Mime-Version: 1.0\n")
4380               (setq header (buffer-string)))
4381             (goto-char (point-max))
4382             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
4383                             id n total))
4384             (forward-char -1)
4385             (let ((mail-header-separator ""))
4386               (when (memq 'Message-ID message-required-mail-headers)
4387                 (insert "Message-ID: " (message-make-message-id) "\n"))
4388               (when (memq 'Lines message-required-mail-headers)
4389                 (insert "Lines: " (message-make-lines) "\n"))
4390               (message-goto-subject)
4391               (end-of-line)
4392               (insert (format " (%d/%d)" n total))
4393               (widen)
4394               (funcall (or message-send-mail-real-function
4395                            message-send-mail-function)))
4396             (setq n (+ n 1))
4397             (setq p (pop plist))
4398             (erase-buffer)))
4399       (kill-buffer tembuf))))
4400
4401 (declare-function hashcash-wait-async "hashcash" (&optional buffer))
4402
4403 (defun message-send-mail (&optional arg)
4404   (require 'mail-utils)
4405   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4406          (case-fold-search nil)
4407          (news (message-news-p))
4408          (mailbuf (current-buffer))
4409          (message-this-is-mail t)
4410          ;; gnus-setup-posting-charset is autoloaded in mml.el (FIXME
4411          ;; maybe it should not be), which this file requires.  Hence
4412          ;; the fboundp test is always true.  Loading it from gnus-msg
4413          ;; loads many Gnus files (Bug#5642).  If
4414          ;; gnus-group-posting-charset-alist hasn't been customized,
4415          ;; this is just going to return nil anyway.  FIXME it would
4416          ;; be good to improve this further, because even if g-g-p-c-a
4417          ;; has been customized, that is likely to just be for news.
4418          ;; Eg either move the definition from gnus-msg, or separate out
4419          ;; the mail and news parts.
4420          (message-posting-charset
4421           (if (and (fboundp 'gnus-setup-posting-charset)
4422                    (boundp 'gnus-group-posting-charset-alist))
4423               (gnus-setup-posting-charset nil)
4424             message-posting-charset))
4425          (headers message-required-mail-headers))
4426     (when (and message-generate-hashcash
4427                (not (eq message-generate-hashcash 'opportunistic)))
4428       (message "Generating hashcash...")
4429       (require 'hashcash)
4430       ;; Wait for calculations already started to finish...
4431       (hashcash-wait-async)
4432       ;; ...and do calculations not already done.  mail-add-payment
4433       ;; will leave existing X-Hashcash headers alone.
4434       (mail-add-payment)
4435       (message "Generating hashcash...done"))
4436     (save-restriction
4437       (message-narrow-to-headers)
4438       ;; Generate the Mail-Followup-To header if the header is not there...
4439       (if (and (message-subscribed-p)
4440                (not (mail-fetch-field "mail-followup-to")))
4441           (setq headers
4442                 (cons
4443                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4444                  message-required-mail-headers))
4445         ;; otherwise, delete the MFT header if the field is empty
4446         (when (equal "" (mail-fetch-field "mail-followup-to"))
4447           (message-remove-header "^Mail-Followup-To:")))
4448       ;; Insert some headers.
4449       (let ((message-deletable-headers
4450              (if news nil message-deletable-headers)))
4451         (message-generate-headers headers))
4452       ;; Check continuation headers.
4453       (message-check 'continuation-headers
4454         (goto-char (point-min))
4455         (while (re-search-forward "^[^ \t\n][^ \t\n:]*[ \t\n]" nil t)
4456           (goto-char (match-beginning 0))
4457           (if (y-or-n-p "Fix continuation lines? ")
4458               (insert " ")
4459             (forward-line 1)
4460             (unless (y-or-n-p "Send anyway? ")
4461               (error "Failed to send the message")))))
4462       ;; Let the user do all of the above.
4463       (run-hooks 'message-header-hook))
4464     (unwind-protect
4465         (with-current-buffer tembuf
4466           (erase-buffer)
4467           ;; Avoid copying text props (except hard newlines).
4468           (insert (with-current-buffer mailbuf
4469                     (mml-buffer-substring-no-properties-except-hard-newlines
4470                      (point-min) (point-max))))
4471           ;; Remove some headers.
4472           (message-encode-message-body)
4473           (save-restriction
4474             (message-narrow-to-headers)
4475             ;; We (re)generate the Lines header.
4476             (when (memq 'Lines message-required-mail-headers)
4477               (message-generate-headers '(Lines)))
4478             ;; Remove some headers.
4479             (message-remove-header message-ignored-mail-headers t)
4480             (let ((mail-parse-charset message-default-charset))
4481               (mail-encode-encoded-word-buffer)))
4482           (goto-char (point-max))
4483           ;; require one newline at the end.
4484           (or (= (preceding-char) ?\n)
4485               (insert ?\n))
4486           (message-cleanup-headers)
4487           ;; FIXME: we're inserting the courtesy copy after encoding.
4488           ;; This is wrong if the courtesy copy string contains
4489           ;; non-ASCII characters. -- jh
4490           (when
4491               (save-restriction
4492                 (message-narrow-to-headers)
4493                 (and news
4494                      (or (message-fetch-field "cc")
4495                          (message-fetch-field "bcc")
4496                          (message-fetch-field "to"))
4497                      (let ((content-type (message-fetch-field
4498                                           "content-type")))
4499                        (and
4500                         (or
4501                          (not content-type)
4502                          (string= "text/plain"
4503                                   (car
4504                                    (mail-header-parse-content-type
4505                                     content-type))))
4506                         (not
4507                          (string= "base64"
4508                                   (message-fetch-field
4509                                    "content-transfer-encoding")))))))
4510             (message-insert-courtesy-copy))
4511           ;; Let's make sure we encoded all the body.
4512           (assert (save-excursion
4513                     (goto-char (point-min))
4514                     (not (re-search-forward "[^\000-\377]" nil t))))
4515           (mm-disable-multibyte)
4516           (if (or (not message-send-mail-partially-limit)
4517                   (< (buffer-size) message-send-mail-partially-limit)
4518                   (not (message-y-or-n-p
4519                         "The message size is too large, split? "
4520                         t
4521                         "\
4522 The message size, "
4523                         (/ (buffer-size) 1000) "KB, is too large.
4524
4525 Some mail gateways (MTA's) bounce large messages.  To avoid the
4526 problem, answer `y', and the message will be split into several
4527 smaller pieces, the size of each is about "
4528                         (/ message-send-mail-partially-limit 1000)
4529                         "KB except the last
4530 one.
4531
4532 However, some mail readers (MUA's) can't read split messages, i.e.,
4533 mails in message/partially format. Answer `n', and the message will be
4534 sent in one piece.
4535
4536 The size limit is controlled by `message-send-mail-partially-limit'.
4537 If you always want Gnus to send messages in one piece, set
4538 `message-send-mail-partially-limit' to nil.
4539 ")))
4540               (progn
4541                 (message "Sending via mail...")
4542                 (funcall (or message-send-mail-real-function
4543                              message-send-mail-function)))
4544             (message-send-mail-partially)))
4545       (kill-buffer tembuf))
4546     (set-buffer mailbuf)
4547     (push 'mail message-sent-message-via)))
4548
4549 (defun message-send-mail-with-sendmail ()
4550   "Send off the prepared buffer with sendmail."
4551   (require 'sendmail)
4552   (let ((errbuf (if message-interactive
4553                     (message-generate-new-buffer-clone-locals
4554                      " sendmail errors")
4555                   0))
4556         resend-to-addresses delimline)
4557     (unwind-protect
4558         (progn
4559           (let ((case-fold-search t))
4560             (save-restriction
4561               (message-narrow-to-headers)
4562               (setq resend-to-addresses (message-fetch-field "resent-to")))
4563             ;; Change header-delimiter to be what sendmail expects.
4564             (goto-char (point-min))
4565             (re-search-forward
4566              (concat "^" (regexp-quote mail-header-separator) "\n"))
4567             (replace-match "\n")
4568             (backward-char 1)
4569             (setq delimline (point-marker))
4570             (run-hooks 'message-send-mail-hook)
4571             ;; Insert an extra newline if we need it to work around
4572             ;; Sun's bug that swallows newlines.
4573             (goto-char (1+ delimline))
4574             (when (eval message-mailer-swallows-blank-line)
4575               (newline))
4576             (when message-interactive
4577               (with-current-buffer errbuf
4578                 (erase-buffer))))
4579           (let* ((default-directory "/")
4580                  (coding-system-for-write message-send-coding-system)
4581                  (cpr (apply
4582                        'call-process-region
4583                        (append
4584                         (list (point-min) (point-max)
4585                               (cond ((boundp 'sendmail-program)
4586                                      sendmail-program)
4587                                     ((file-exists-p "/usr/sbin/sendmail")
4588                                      "/usr/sbin/sendmail")
4589                                     ((file-exists-p "/usr/lib/sendmail")
4590                                      "/usr/lib/sendmail")
4591                                     ((file-exists-p "/usr/ucblib/sendmail")
4592                                      "/usr/ucblib/sendmail")
4593                                     (t "fakemail"))
4594                               nil errbuf nil "-oi")
4595                         message-sendmail-extra-arguments
4596                         ;; Always specify who from,
4597                         ;; since some systems have broken sendmails.
4598                         ;; But some systems are more broken with -f, so
4599                         ;; we'll let users override this.
4600                         (and (null message-sendmail-f-is-evil)
4601                              (list "-f" (message-sendmail-envelope-from)))
4602                         ;; These mean "report errors by mail"
4603                         ;; and "deliver in background".
4604                         (if (null message-interactive) '("-oem" "-odb"))
4605                         ;; Get the addresses from the message
4606                         ;; unless this is a resend.
4607                         ;; We must not do that for a resend
4608                         ;; because we would find the original addresses.
4609                         ;; For a resend, include the specific addresses.
4610                         (if resend-to-addresses
4611                             (list resend-to-addresses)
4612                           '("-t"))))))
4613             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4614               (if errbuf (pop-to-buffer errbuf))
4615               (error "Sending...failed with exit value %d" cpr)))
4616           (when message-interactive
4617             (with-current-buffer errbuf
4618               (goto-char (point-min))
4619               (while (re-search-forward "\n+ *" nil t)
4620                 (replace-match "; "))
4621               (if (not (zerop (buffer-size)))
4622                   (error "Sending...failed to %s"
4623                          (buffer-string))))))
4624       (when (bufferp errbuf)
4625         (kill-buffer errbuf)))))
4626
4627 (defun message-send-mail-with-qmail ()
4628   "Pass the prepared message buffer to qmail-inject.
4629 Refer to the documentation for the variable `message-send-mail-function'
4630 to find out how to use this."
4631   ;; replace the header delimiter with a blank line
4632   (goto-char (point-min))
4633   (re-search-forward
4634    (concat "^" (regexp-quote mail-header-separator) "\n"))
4635   (replace-match "\n")
4636   (run-hooks 'message-send-mail-hook)
4637   ;; send the message
4638   (case
4639       (let ((coding-system-for-write message-send-coding-system))
4640         (apply
4641          'call-process-region (point-min) (point-max)
4642          message-qmail-inject-program nil nil nil
4643          ;; qmail-inject's default behavior is to look for addresses on the
4644          ;; command line; if there're none, it scans the headers.
4645          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4646          ;;
4647          ;; in general, ALL of qmail-inject's defaults are perfect for simply
4648          ;; reading a formatted (i. e., at least a To: or Resent-To header)
4649          ;; message from stdin.
4650          ;;
4651          ;; qmail also has the advantage of not having been raped by
4652          ;; various vendors, so we don't have to allow for that, either --
4653          ;; compare this with message-send-mail-with-sendmail and weep
4654          ;; for sendmail's lost innocence.
4655          ;;
4656          ;; all this is way cool coz it lets us keep the arguments entirely
4657          ;; free for -inject-arguments -- a big win for the user and for us
4658          ;; since we don't have to play that double-guessing game and the user
4659          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4660          (if (functionp message-qmail-inject-args)
4661              (funcall message-qmail-inject-args)
4662            message-qmail-inject-args)))
4663     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4664     ;; we have to look at the retval instead
4665     (0 nil)
4666     (100 (error "qmail-inject reported permanent failure"))
4667     (111 (error "qmail-inject reported transient failure"))
4668     ;; should never happen
4669     (t   (error "qmail-inject reported unknown failure"))))
4670
4671 (defun message-send-mail-with-mh ()
4672   "Send the prepared message buffer with mh."
4673   (let ((mh-previous-window-config nil)
4674         (name (mh-new-draft-name)))
4675     (setq buffer-file-name name)
4676     ;; MH wants to generate these headers itself.
4677     (when message-mh-deletable-headers
4678       (let ((headers message-mh-deletable-headers))
4679         (while headers
4680           (goto-char (point-min))
4681           (and (re-search-forward
4682                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4683                (message-delete-line))
4684           (pop headers))))
4685     (run-hooks 'message-send-mail-hook)
4686     ;; Pass it on to mh.
4687     (mh-send-letter)))
4688
4689 (defun message-smtpmail-send-it ()
4690   "Send the prepared message buffer with `smtpmail-send-it'.
4691 The only difference from `smtpmail-send-it' is that this command
4692 evaluates `message-send-mail-hook' just before sending a message.
4693 It is useful if your ISP requires the POP-before-SMTP
4694 authentication.  See the Gnus manual for details."
4695   (run-hooks 'message-send-mail-hook)
4696   (smtpmail-send-it))
4697
4698 (defun message-send-mail-with-mailclient ()
4699   "Send the prepared message buffer with `mailclient-send-it'.
4700 The only difference from `mailclient-send-it' is that this
4701 command evaluates `message-send-mail-hook' just before sending a message."
4702   (run-hooks 'message-send-mail-hook)
4703   (mailclient-send-it))
4704
4705 (defun message-canlock-generate ()
4706   "Return a string that is non-trivial to guess.
4707 Do not use this for anything important, it is cryptographically weak."
4708   (require 'sha1)
4709   (let (sha1-maximum-internal-length)
4710     (sha1 (concat (message-unique-id)
4711                   (format "%x%x%x" (random) (random t) (random))
4712                   (prin1-to-string (recent-keys))
4713                   (prin1-to-string (garbage-collect))))))
4714
4715 (defvar canlock-password)
4716 (defvar canlock-password-for-verify)
4717
4718 (defun message-canlock-password ()
4719   "The password used by message for cancel locks.
4720 This is the value of `canlock-password', if that option is non-nil.
4721 Otherwise, generate and save a value for `canlock-password' first."
4722   (require 'canlock)
4723   (unless canlock-password
4724     (customize-save-variable 'canlock-password (message-canlock-generate))
4725     (setq canlock-password-for-verify canlock-password))
4726   canlock-password)
4727
4728 (defun message-insert-canlock ()
4729   (when message-insert-canlock
4730     (message-canlock-password)
4731     (canlock-insert-header)))
4732
4733 (autoload 'nnheader-get-report "nnheader")
4734
4735 (declare-function gnus-setup-posting-charset "gnus-msg" (group))
4736
4737 (defun message-send-news (&optional arg)
4738   (require 'gnus-msg)
4739   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4740          (case-fold-search nil)
4741          (method (if (functionp message-post-method)
4742                      (funcall message-post-method arg)
4743                    message-post-method))
4744          (newsgroups-field (save-restriction
4745                             (message-narrow-to-headers-or-head)
4746                             (message-fetch-field "Newsgroups")))
4747          (followup-field (save-restriction
4748                            (message-narrow-to-headers-or-head)
4749                            (message-fetch-field "Followup-To")))
4750          ;; BUG: We really need to get the charset for each name in the
4751          ;; Newsgroups and Followup-To lines to allow crossposting
4752          ;; between group namess with incompatible character sets.
4753          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4754          (group-field-charset
4755           (gnus-group-name-charset method newsgroups-field))
4756          (followup-field-charset
4757           (gnus-group-name-charset method (or followup-field "")))
4758          (rfc2047-header-encoding-alist
4759           (append (when group-field-charset
4760                     (list (cons "Newsgroups" group-field-charset)))
4761                   (when followup-field-charset
4762                     (list (cons "Followup-To" followup-field-charset)))
4763                   rfc2047-header-encoding-alist))
4764          (messbuf (current-buffer))
4765          (message-syntax-checks
4766           (if (and arg
4767                    (listp message-syntax-checks))
4768               (cons '(existing-newsgroups . disabled)
4769                     message-syntax-checks)
4770             message-syntax-checks))
4771          (message-this-is-news t)
4772          (message-posting-charset
4773           (gnus-setup-posting-charset newsgroups-field))
4774          result)
4775     (if (not (message-check-news-body-syntax))
4776         nil
4777       (save-restriction
4778         (message-narrow-to-headers)
4779         ;; Insert some headers.
4780         (message-generate-headers message-required-news-headers)
4781         (message-insert-canlock)
4782         ;; Let the user do all of the above.
4783         (run-hooks 'message-header-hook))
4784       ;; Note: This check will be disabled by the ".*" default value for
4785       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4786       (when (and group-field-charset
4787                  (listp message-syntax-checks))
4788         (setq message-syntax-checks
4789               (cons '(valid-newsgroups . disabled)
4790                     message-syntax-checks)))
4791       (message-cleanup-headers)
4792       (if (not (let ((message-post-method method))
4793                  (message-check-news-syntax)))
4794           nil
4795         (unwind-protect
4796             (with-current-buffer tembuf
4797               (buffer-disable-undo)
4798               (erase-buffer)
4799               ;; Avoid copying text props (except hard newlines).
4800               (insert
4801                (with-current-buffer messbuf
4802                  (mml-buffer-substring-no-properties-except-hard-newlines
4803                   (point-min) (point-max))))
4804               (message-encode-message-body)
4805               ;; Remove some headers.
4806               (save-restriction
4807                 (message-narrow-to-headers)
4808                 ;; We (re)generate the Lines header.
4809                 (when (memq 'Lines message-required-mail-headers)
4810                   (message-generate-headers '(Lines)))
4811                 ;; Remove some headers.
4812                 (message-remove-header message-ignored-news-headers t)
4813                 (let ((mail-parse-charset message-default-charset))
4814                   (mail-encode-encoded-word-buffer)))
4815               (goto-char (point-max))
4816               ;; require one newline at the end.
4817               (or (= (preceding-char) ?\n)
4818                   (insert ?\n))
4819               (let ((case-fold-search t))
4820                 ;; Remove the delimiter.
4821                 (goto-char (point-min))
4822                 (re-search-forward
4823                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4824                 (replace-match "\n")
4825                 (backward-char 1))
4826               (run-hooks 'message-send-news-hook)
4827               (gnus-open-server method)
4828               (message "Sending news via %s..." (gnus-server-string method))
4829               (setq result (let ((mail-header-separator ""))
4830                              (gnus-request-post method))))
4831           (kill-buffer tembuf))
4832         (set-buffer messbuf)
4833         (if result
4834             (push 'news message-sent-message-via)
4835           (message "Couldn't send message via news: %s"
4836                    (nnheader-get-report (car method)))
4837           nil)))))
4838
4839 ;;;
4840 ;;; Header generation & syntax checking.
4841 ;;;
4842
4843 (defun message-check-element (type)
4844   "Return non-nil if this TYPE is not to be checked."
4845   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4846       t
4847     (let ((able (assq type message-syntax-checks)))
4848       (and (consp able)
4849            (eq (cdr able) 'disabled)))))
4850
4851 (defun message-check-news-syntax ()
4852   "Check the syntax of the message."
4853   (save-excursion
4854     (save-restriction
4855       (widen)
4856       ;; We narrow to the headers and check them first.
4857       (save-excursion
4858         (save-restriction
4859           (message-narrow-to-headers)
4860           (message-check-news-header-syntax))))))
4861
4862 (defun message-check-news-header-syntax ()
4863   (and
4864    ;; Check Newsgroups header.
4865    (message-check 'newsgroups
4866      (let ((group (message-fetch-field "newsgroups")))
4867        (or
4868         (and group
4869              (not (string-match "\\`[ \t]*\\'" group)))
4870         (ignore
4871          (message
4872           "The newsgroups field is empty or missing.  Posting is denied.")))))
4873    ;; Check the Subject header.
4874    (message-check 'subject
4875      (let* ((case-fold-search t)
4876             (subject (message-fetch-field "subject")))
4877        (or
4878         (and subject
4879              (not (string-match "\\`[ \t]*\\'" subject)))
4880         (ignore
4881          (message
4882           "The subject field is empty or missing.  Posting is denied.")))))
4883    ;; Check for commands in Subject.
4884    (message-check 'subject-cmsg
4885      (if (string-match "^cmsg " (message-fetch-field "subject"))
4886          (y-or-n-p
4887           "The control code \"cmsg\" is in the subject.  Really post? ")
4888        t))
4889    ;; Check long header lines.
4890    (message-check 'long-header-lines
4891      (let ((start (point))
4892            (header nil)
4893            (length 0)
4894            found)
4895        (while (and (not found)
4896                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4897          (if (> (- (point) (match-beginning 0)) 998)
4898              (setq found t
4899                    length (- (point) (match-beginning 0)))
4900            (setq header (match-string-no-properties 1)))
4901          (setq start (match-beginning 0))
4902          (forward-line 1))
4903        (if found
4904            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4905                              header length))
4906          t)))
4907    ;; Check for multiple identical headers.
4908    (message-check 'multiple-headers
4909      (let (found)
4910        (while (and (not found)
4911                    (re-search-forward "^[^ \t:]+: " nil t))
4912          (save-excursion
4913            (or (re-search-forward
4914                 (concat "^"
4915                         (regexp-quote
4916                          (setq found
4917                                (buffer-substring
4918                                 (match-beginning 0) (- (match-end 0) 2))))
4919                         ":")
4920                 nil t)
4921                (setq found nil))))
4922        (if found
4923            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4924          t)))
4925    ;; Check for Version and Sendsys.
4926    (message-check 'sendsys
4927      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4928          (y-or-n-p
4929           (format "The article contains a %s command.  Really post? "
4930                   (buffer-substring (match-beginning 0)
4931                                     (1- (match-end 0)))))
4932        t))
4933    ;; See whether we can shorten Followup-To.
4934    (message-check 'shorten-followup-to
4935      (let ((newsgroups (message-fetch-field "newsgroups"))
4936            (followup-to (message-fetch-field "followup-to"))
4937            to)
4938        (when (and newsgroups
4939                   (string-match "," newsgroups)
4940                   (not followup-to)
4941                   (not
4942                    (zerop
4943                     (length
4944                      (setq to (completing-read
4945                                "Followups to (default no Followup-To header): "
4946                                (mapcar #'list
4947                                        (cons "poster"
4948                                              (message-tokenize-header
4949                                               newsgroups)))))))))
4950          (goto-char (point-min))
4951          (insert "Followup-To: " to "\n"))
4952        t))
4953    ;; Check "Shoot me".
4954    (message-check 'shoot
4955      (if (re-search-forward
4956           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4957          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4958        t))
4959    ;; Check for Approved.
4960    (message-check 'approved
4961      (if (re-search-forward "^Approved:" nil t)
4962          (y-or-n-p "The article contains an Approved header.  Really post? ")
4963        t))
4964    ;; Check the Message-ID header.
4965    (message-check 'message-id
4966      (let* ((case-fold-search t)
4967             (message-id (message-fetch-field "message-id" t)))
4968        (or (not message-id)
4969            ;; Is there an @ in the ID?
4970            (and (string-match "@" message-id)
4971                 ;; Is there a dot in the ID?
4972                 (string-match "@[^.]*\\." message-id)
4973                 ;; Does the ID end with a dot?
4974                 (not (string-match "\\.>" message-id)))
4975            (y-or-n-p
4976             (format "The Message-ID looks strange: \"%s\".  Really post? "
4977                     message-id)))))
4978    ;; Check the Newsgroups & Followup-To headers.
4979    (message-check 'existing-newsgroups
4980      (let* ((case-fold-search t)
4981             (newsgroups (message-fetch-field "newsgroups"))
4982             (followup-to (message-fetch-field "followup-to"))
4983             (groups (message-tokenize-header
4984                      (if followup-to
4985                          (concat newsgroups "," followup-to)
4986                        newsgroups)))
4987             (post-method (if (functionp message-post-method)
4988                              (funcall message-post-method)
4989                            message-post-method))
4990             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4991             ;; would probably involve a new nnoo function.
4992             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4993             (method (if (and (consp post-method)
4994                              (eq (car post-method) 'nnvirtual)
4995                              gnus-message-group-art)
4996                         (let ((group (car (nnvirtual-find-group-art
4997                                            (car gnus-message-group-art)
4998                                            (cdr gnus-message-group-art)))))
4999                           (gnus-find-method-for-group group))
5000                       post-method))
5001             (known-groups
5002              (mapcar (lambda (n)
5003                        (gnus-group-name-decode
5004                         (gnus-group-real-name n)
5005                         (gnus-group-name-charset method n)))
5006                      (gnus-groups-from-server method)))
5007             errors)
5008        (while groups
5009          (when (and (not (equal (car groups) "poster"))
5010                     (not (member (car groups) known-groups))
5011                     (not (member (car groups) errors)))
5012            (push (car groups) errors))
5013          (pop groups))
5014        (cond
5015         ;; Gnus is not running.
5016         ((or (not (and (boundp 'gnus-active-hashtb)
5017                        gnus-active-hashtb))
5018              (not (boundp 'gnus-read-active-file)))
5019          t)
5020         ;; We don't have all the group names.
5021         ((and (or (not gnus-read-active-file)
5022                   (eq gnus-read-active-file 'some))
5023               errors)
5024          (y-or-n-p
5025           (format
5026            "Really use %s possibly unknown group%s: %s? "
5027            (if (= (length errors) 1) "this" "these")
5028            (if (= (length errors) 1) "" "s")
5029            (mapconcat 'identity errors ", "))))
5030         ;; There were no errors.
5031         ((not errors)
5032          t)
5033         ;; There are unknown groups.
5034         (t
5035          (y-or-n-p
5036           (format
5037            "Really post to %s unknown group%s: %s? "
5038            (if (= (length errors) 1) "this" "these")
5039            (if (= (length errors) 1) "" "s")
5040            (mapconcat 'identity errors ", ")))))))
5041    ;; Check continuation headers.
5042    (message-check 'continuation-headers
5043      (goto-char (point-min))
5044      (let ((do-posting t))
5045        (while (re-search-forward "^[^ \t\n][^ \t\n:]*[ \t\n]" nil t)
5046          (goto-char (match-beginning 0))
5047          (if (y-or-n-p "Fix continuation lines? ")
5048              (insert " ")
5049            (forward-line 1)
5050            (unless (y-or-n-p "Send anyway? ")
5051              (setq do-posting nil))))
5052        do-posting))
5053    ;; Check the Newsgroups & Followup-To headers for syntax errors.
5054    (message-check 'valid-newsgroups
5055      (let ((case-fold-search t)
5056            (headers '("Newsgroups" "Followup-To"))
5057            header error)
5058        (while (and headers (not error))
5059          (when (setq header (mail-fetch-field (car headers)))
5060            (if (or
5061                 (not
5062                  (string-match
5063                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
5064                   header))
5065                 (memq
5066                  nil (mapcar
5067                       (lambda (g)
5068                         (not (string-match "\\.\\'\\|\\.\\." g)))
5069                       (message-tokenize-header header ","))))
5070                (setq error t)))
5071          (unless error
5072            (pop headers)))
5073        (if (not error)
5074            t
5075          (y-or-n-p
5076           (format "The %s header looks odd: \"%s\".  Really post? "
5077                   (car headers) header)))))
5078    (message-check 'repeated-newsgroups
5079      (let ((case-fold-search t)
5080            (headers '("Newsgroups" "Followup-To"))
5081            header error groups group)
5082        (while (and headers
5083                    (not error))
5084          (when (setq header (mail-fetch-field (pop headers)))
5085            (setq groups (message-tokenize-header header ","))
5086            (while (setq group (pop groups))
5087              (when (member group groups)
5088                (setq error group
5089                      groups nil)))))
5090        (if (not error)
5091            t
5092          (y-or-n-p
5093           (format "Group %s is repeated in headers.  Really post? " error)))))
5094    ;; Check the From header.
5095    (message-check 'from
5096      (let* ((case-fold-search t)
5097             (from (message-fetch-field "from"))
5098             ad)
5099        (cond
5100         ((not from)
5101          (message "There is no From line.  Posting is denied.")
5102          nil)
5103         ((or (not (string-match
5104                    "@[^\\.]*\\."
5105                    (setq ad (nth 1 (mail-extract-address-components
5106                                     from))))) ;larsi@ifi
5107              (string-match "\\.\\." ad) ;larsi@ifi..uio
5108              (string-match "@\\." ad)   ;larsi@.ifi.uio
5109              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5110              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5111              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
5112          (message
5113           "Denied posting -- the From looks strange: \"%s\"." from)
5114          nil)
5115         ((let ((addresses (rfc822-addresses from)))
5116            ;; `rfc822-addresses' returns a string if parsing fails.
5117            (while (and (consp addresses)
5118                        (not (eq (string-to-char (car addresses)) ?\()))
5119              (setq addresses (cdr addresses)))
5120            addresses)
5121          (message
5122           "Denied posting -- bad From address: \"%s\"." from)
5123          nil)
5124         (t t))))
5125    ;; Check the Reply-To header.
5126    (message-check 'reply-to
5127      (let* ((case-fold-search t)
5128             (reply-to (message-fetch-field "reply-to"))
5129             ad)
5130        (cond
5131         ((not reply-to)
5132          t)
5133         ((string-match "," reply-to)
5134          (y-or-n-p
5135           (format "Multiple Reply-To addresses: \"%s\". Really post? "
5136                   reply-to)))
5137         ((or (not (string-match
5138                    "@[^\\.]*\\."
5139                    (setq ad (nth 1 (mail-extract-address-components
5140                                     reply-to))))) ;larsi@ifi
5141              (string-match "\\.\\." ad) ;larsi@ifi..uio
5142              (string-match "@\\." ad)   ;larsi@.ifi.uio
5143              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5144              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5145              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
5146          (y-or-n-p
5147           (format
5148            "The Reply-To looks strange: \"%s\". Really post? "
5149            reply-to)))
5150         (t t))))))
5151
5152 (defun message-check-news-body-syntax ()
5153   (and
5154    ;; Check for long lines.
5155    (message-check 'long-lines
5156      (goto-char (point-min))
5157      (re-search-forward
5158       (concat "^" (regexp-quote mail-header-separator) "$"))
5159      (forward-line 1)
5160      (while (and
5161              (or (looking-at
5162                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
5163                  (let ((p (point)))
5164                    (end-of-line)
5165                    (< (- (point) p) 80)))
5166              (zerop (forward-line 1))))
5167      (or (bolp)
5168          (eobp)
5169          (y-or-n-p
5170           "You have lines longer than 79 characters.  Really post? ")))
5171    ;; Check whether the article is empty.
5172    (message-check 'empty
5173      (goto-char (point-min))
5174      (re-search-forward
5175       (concat "^" (regexp-quote mail-header-separator) "$"))
5176      (forward-line 1)
5177      (let ((b (point)))
5178        (goto-char (point-max))
5179        (re-search-backward message-signature-separator nil t)
5180        (beginning-of-line)
5181        (or (re-search-backward "[^ \n\t]" b t)
5182            (if (message-gnksa-enable-p 'empty-article)
5183                (y-or-n-p "Empty article.  Really post? ")
5184              (message "Denied posting -- Empty article.")
5185              nil))))
5186    ;; Check for control characters.
5187    (message-check 'control-chars
5188      (if (re-search-forward
5189           (mm-string-to-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
5190           nil t)
5191          (y-or-n-p
5192           "The article contains control characters.  Really post? ")
5193        t))
5194    ;; Check excessive size.
5195    (message-check 'size
5196      (if (> (buffer-size) 60000)
5197          (y-or-n-p
5198           (format "The article is %d octets long.  Really post? "
5199                   (buffer-size)))
5200        t))
5201    ;; Check whether any new text has been added.
5202    (message-check 'new-text
5203      (or
5204       (not message-checksum)
5205       (not (eq (message-checksum) message-checksum))
5206       (if (message-gnksa-enable-p 'quoted-text-only)
5207           (y-or-n-p
5208            "It looks like no new text has been added.  Really post? ")
5209         (message "Denied posting -- no new text has been added.")
5210         nil)))
5211    ;; Check the length of the signature.
5212    (message-check 'signature
5213      (let (sig-start sig-end)
5214        (goto-char (point-max))
5215        (if (not (re-search-backward message-signature-separator nil t))
5216            t
5217          (setq sig-start (1+ (point-at-eol)))
5218          (setq sig-end
5219                (if (re-search-forward
5220                     "<#/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
5221                    (- (point-at-bol) 1)
5222                  (point-max)))
5223          (if (>= (count-lines sig-start sig-end) 5)
5224              (if (message-gnksa-enable-p 'signature)
5225                  (y-or-n-p
5226                   (format "Signature is excessively long (%d lines).  Really post? "
5227                           (count-lines sig-start sig-end)))
5228                (message "Denied posting -- Excessive signature.")
5229                nil)
5230            t))))
5231    ;; Ensure that text follows last quoted portion.
5232    (message-check 'quoting-style
5233      (goto-char (point-max))
5234      (let ((no-problem t))
5235        (when (search-backward-regexp "^>[^\n]*\n" nil t)
5236          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
5237        (if no-problem
5238            t
5239          (if (message-gnksa-enable-p 'quoted-text-only)
5240              (y-or-n-p "Your text should follow quoted text.  Really post? ")
5241            ;; Ensure that
5242            (goto-char (point-min))
5243            (re-search-forward
5244             (concat "^" (regexp-quote mail-header-separator) "$"))
5245            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
5246                (y-or-n-p "Your text should follow quoted text.  Really post? ")
5247              (message "Denied posting -- only quoted text.")
5248              nil)))))))
5249
5250 (defun message-checksum ()
5251   "Return a \"checksum\" for the current buffer."
5252   (let ((sum 0))
5253     (save-excursion
5254       (goto-char (point-min))
5255       (re-search-forward
5256        (concat "^" (regexp-quote mail-header-separator) "$"))
5257       (while (not (eobp))
5258         (when (not (looking-at "[ \t\n]"))
5259           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
5260                             (char-after))))
5261         (forward-char 1)))
5262     sum))
5263
5264 (defun message-do-fcc ()
5265   "Process Fcc headers in the current buffer."
5266   (let ((case-fold-search t)
5267         (buf (current-buffer))
5268         list file
5269         (mml-externalize-attachments message-fcc-externalize-attachments))
5270     (save-excursion
5271       (save-restriction
5272         (message-narrow-to-headers)
5273         (setq file (message-fetch-field "fcc" t)))
5274       (when file
5275         (set-buffer (get-buffer-create " *message temp*"))
5276         (erase-buffer)
5277         (insert-buffer-substring buf)
5278         (message-encode-message-body)
5279         (save-restriction
5280           (message-narrow-to-headers)
5281           (while (setq file (message-fetch-field "fcc" t))
5282             (push file list)
5283             (message-remove-header "fcc" nil t))
5284           (let ((mail-parse-charset message-default-charset)
5285                 (rfc2047-header-encoding-alist
5286                  (cons '("Newsgroups" . default)
5287                        rfc2047-header-encoding-alist)))
5288             (mail-encode-encoded-word-buffer)))
5289         (goto-char (point-min))
5290         (when (re-search-forward
5291                (concat "^" (regexp-quote mail-header-separator) "$")
5292                nil t)
5293           (replace-match "" t t ))
5294         ;; Process FCC operations.
5295         (while list
5296           (setq file (pop list))
5297           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
5298               ;; Pipe the article to the program in question.
5299               (call-process-region (point-min) (point-max) shell-file-name
5300                                    nil nil nil shell-command-switch
5301                                    (match-string 1 file))
5302             ;; Save the article.
5303             (setq file (expand-file-name file))
5304             (unless (file-exists-p (file-name-directory file))
5305               (make-directory (file-name-directory file) t))
5306             (if (and message-fcc-handler-function
5307                      (not (eq message-fcc-handler-function 'rmail-output)))
5308                 (funcall message-fcc-handler-function file)
5309               ;; FIXME this option, rmail-output (also used if
5310               ;; message-fcc-handler-function is nil) is not
5311               ;; documented anywhere AFAICS.  It should work in Emacs
5312               ;; 23; I suspect it does not work in Emacs 22.
5313               ;; FIXME I don't see the need for the two different cases here.
5314               ;; mail-use-rfc822 makes no difference (in Emacs 23),and
5315               ;; the third argument just controls \"Wrote file\" message.
5316               (if (and (file-readable-p file) (mail-file-babyl-p file))
5317                   (rmail-output file 1 nil t)
5318                 (let ((mail-use-rfc822 t))
5319                   (rmail-output file 1 t t))))))
5320         (kill-buffer (current-buffer))))))
5321
5322 (defun message-output (filename)
5323   "Append this article to Unix/babyl mail file FILENAME."
5324   (if (and (file-readable-p filename)
5325            (mail-file-babyl-p filename))
5326       (gnus-output-to-rmail filename t)
5327     (gnus-output-to-mail filename t)))
5328
5329 (defun message-cleanup-headers ()
5330   "Do various automatic cleanups of the headers."
5331   ;; Remove empty lines in the header.
5332   (save-restriction
5333     (message-narrow-to-headers)
5334     ;; Remove blank lines.
5335     (while (re-search-forward "^[ \t]*\n" nil t)
5336       (replace-match "" t t))
5337
5338     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
5339     ;; spaces to comma and eliminate spaces around commas.  Eliminate
5340     ;; embedded line breaks.
5341     (goto-char (point-min))
5342     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
5343       (save-restriction
5344         (narrow-to-region
5345          (point)
5346          (if (re-search-forward "^[^ \t]" nil t)
5347              (match-beginning 0)
5348            (forward-line 1)
5349            (point)))
5350         (goto-char (point-min))
5351         (while (re-search-forward "\n[ \t]+" nil t)
5352           (replace-match " " t t))     ;No line breaks (too confusing)
5353         (goto-char (point-min))
5354         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
5355           (replace-match "," t t))
5356         (goto-char (point-min))
5357         ;; Remove trailing commas.
5358         (when (re-search-forward ",+$" nil t)
5359           (replace-match "" t t))))))
5360
5361 (defun message-make-date (&optional now)
5362   "Make a valid data header.
5363 If NOW, use that time instead."
5364   (let ((system-time-locale "C"))
5365     (format-time-string "%a, %d %b %Y %T %z" now)))
5366
5367 (defun message-insert-expires (days)
5368   "Insert the Expires header.  Expiry in DAYS days."
5369   (interactive "NExpire article in how many days? ")
5370   (save-excursion
5371     (message-position-on-field "Expires" "X-Draft-From")
5372     (insert (message-make-expires-date days))))
5373
5374 (defun message-make-expires-date (days)
5375   "Make date string for the Expires header.  Expiry in DAYS days.
5376
5377 In posting styles use `(\"Expires\" (make-expires-date 30))'."
5378   (let* ((cur (decode-time (current-time)))
5379          (nday (+ days (nth 3 cur))))
5380     (setf (nth 3 cur) nday)
5381     (message-make-date (apply 'encode-time cur))))
5382
5383 (defun message-make-message-id ()
5384   "Make a unique Message-ID."
5385   (concat "<" (message-unique-id)
5386           (let ((psubject (save-excursion (message-fetch-field "subject")))
5387                 (psupersedes
5388                  (save-excursion (message-fetch-field "supersedes"))))
5389             (if (or
5390                  (and message-reply-headers
5391                       (mail-header-references message-reply-headers)
5392                       (mail-header-subject message-reply-headers)
5393                       psubject
5394                       (not (string=
5395                             (message-strip-subject-re
5396                              (mail-header-subject message-reply-headers))
5397                             (message-strip-subject-re psubject))))
5398                  (and psupersedes
5399                       (string-match "_-_@" psupersedes)))
5400                 "_-_" ""))
5401           "@" (message-make-fqdn) ">"))
5402
5403 (defvar message-unique-id-char nil)
5404
5405 ;; If you ever change this function, make sure the new version
5406 ;; cannot generate IDs that the old version could.
5407 ;; You might for example insert a "." somewhere (not next to another dot
5408 ;; or string boundary), or modify the "fsf" string.
5409 (defun message-unique-id ()
5410   ;; Don't use microseconds from (current-time), they may be unsupported.
5411   ;; Instead we use this randomly inited counter.
5412   (setq message-unique-id-char
5413         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5414            ;; (current-time) returns 16-bit ints,
5415            ;; and 2^16*25 just fits into 4 digits i base 36.
5416            (* 25 25)))
5417   (let ((tm (current-time)))
5418     (concat
5419      (if (or (eq system-type 'ms-dos)
5420              ;; message-number-base36 doesn't handle bigints.
5421              (floatp (user-uid)))
5422          (let ((user (downcase (user-login-name))))
5423            (while (string-match "[^a-z0-9_]" user)
5424              (aset user (match-beginning 0) ?_))
5425            user)
5426        (message-number-base36 (user-uid) -1))
5427      (message-number-base36 (+ (car tm)
5428                                (lsh (% message-unique-id-char 25) 16)) 4)
5429      (message-number-base36 (+ (nth 1 tm)
5430                                (lsh (/ message-unique-id-char 25) 16)) 4)
5431      ;; Append a given name, because while the generated ID is unique
5432      ;; to this newsreader, other newsreaders might otherwise generate
5433      ;; the same ID via another algorithm.
5434      ".fsf")))
5435
5436 (defun message-number-base36 (num len)
5437   (if (if (< len 0)
5438           (<= num 0)
5439         (= len 0))
5440       ""
5441     (concat (message-number-base36 (/ num 36) (1- len))
5442             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5443                                   (% num 36))))))
5444
5445 (defun message-make-organization ()
5446   "Make an Organization header."
5447   (let* ((organization
5448           (when message-user-organization
5449             (if (functionp message-user-organization)
5450                 (funcall message-user-organization)
5451               message-user-organization))))
5452     (with-temp-buffer
5453       (mm-enable-multibyte)
5454       (cond ((stringp organization)
5455              (insert organization))
5456             ((and (eq t organization)
5457                   message-user-organization-file
5458                   (file-exists-p message-user-organization-file))
5459              (insert-file-contents message-user-organization-file)))
5460       (goto-char (point-min))
5461       (while (re-search-forward "[\t\n]+" nil t)
5462         (replace-match "" t t))
5463       (unless (zerop (buffer-size))
5464         (buffer-string)))))
5465
5466 (defun message-make-lines ()
5467   "Count the number of lines and return numeric string."
5468   (save-excursion
5469     (save-restriction
5470       (widen)
5471       (message-goto-body)
5472       (int-to-string (count-lines (point) (point-max))))))
5473
5474 (defun message-make-references ()
5475   "Return the References header for this message."
5476   (when message-reply-headers
5477     (let ((message-id (mail-header-id message-reply-headers))
5478           (references (mail-header-references message-reply-headers)))
5479       (if (or references message-id)
5480           (concat (or references "") (and references " ")
5481                   (or message-id ""))
5482         nil))))
5483
5484 (defun message-make-in-reply-to ()
5485   "Return the In-Reply-To header for this message."
5486   (when message-reply-headers
5487     (let ((from (mail-header-from message-reply-headers))
5488           (date (mail-header-date message-reply-headers))
5489           (msg-id (mail-header-id message-reply-headers)))
5490       (when from
5491         (let ((name (mail-extract-address-components from)))
5492           (concat
5493            msg-id (if msg-id " (")
5494            (if (car name)
5495                (if (string-match "[^\000-\177]" (car name))
5496                    ;; Quote a string containing non-ASCII characters.
5497                    ;; It will make the RFC2047 encoder cause an error
5498                    ;; if there are special characters.
5499                    (mm-with-multibyte-buffer
5500                      (insert (car name))
5501                      (goto-char (point-min))
5502                      (while (search-forward "\"" nil t)
5503                        (when (prog2
5504                                  (backward-char)
5505                                  (zerop (% (skip-chars-backward "\\\\") 2))
5506                                (goto-char (match-beginning 0)))
5507                          (insert "\\"))
5508                        (forward-char))
5509                      ;; Those quotes will be removed by the RFC2047 encoder.
5510                      (concat "\"" (buffer-string) "\""))
5511                  (car name))
5512              (nth 1 name))
5513            "'s message of \""
5514            (if (or (not date) (string= date ""))
5515                "(unknown date)" date)
5516            "\"" (if msg-id ")")))))))
5517
5518 (defun message-make-distribution ()
5519   "Make a Distribution header."
5520   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5521     (cond ((functionp message-distribution-function)
5522            (funcall message-distribution-function))
5523           (t orig-distribution))))
5524
5525 (defun message-make-expires ()
5526   "Return an Expires header based on `message-expires'."
5527   (let ((current (current-time))
5528         (future (* 1.0 message-expires 60 60 24)))
5529     ;; Add the future to current.
5530     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5531     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5532     (message-make-date current)))
5533
5534 (defun message-make-path ()
5535   "Return uucp path."
5536   (let ((login-name (user-login-name)))
5537     (cond ((null message-user-path)
5538            (concat (system-name) "!" login-name))
5539           ((stringp message-user-path)
5540            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5541            (concat message-user-path "!" login-name))
5542           (t login-name))))
5543
5544 (defun message-make-from (&optional name address)
5545   "Make a From header."
5546   (let* ((style message-from-style)
5547          (login (or address (message-make-address)))
5548          (fullname (or name
5549                        (and (boundp 'user-full-name)
5550                             user-full-name)
5551                        (user-full-name))))
5552     (when (string= fullname "&")
5553       (setq fullname (user-login-name)))
5554     (with-temp-buffer
5555       (mm-enable-multibyte)
5556       (cond
5557        ((or (null style)
5558             (equal fullname ""))
5559         (insert login))
5560        ((or (eq style 'angles)
5561             (and (not (eq style 'parens))
5562                  ;; Use angles if no quoting is needed, or if parens would
5563                  ;; need quoting too.
5564                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5565                      (let ((tmp (concat fullname nil)))
5566                        (while (string-match "([^()]*)" tmp)
5567                          (aset tmp (match-beginning 0) ?-)
5568                          (aset tmp (1- (match-end 0)) ?-))
5569                        (string-match "[\\()]" tmp)))))
5570         (insert fullname)
5571         (goto-char (point-min))
5572         ;; Look for a character that cannot appear unquoted
5573         ;; according to RFC 822.
5574         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5575           ;; Quote fullname, escaping specials.
5576           (goto-char (point-min))
5577           (insert "\"")
5578           (while (re-search-forward "[\"\\]" nil 1)
5579             (replace-match "\\\\\\&" t))
5580           (insert "\""))
5581         (insert " <" login ">"))
5582        (t                               ; 'parens or default
5583         (insert login " (")
5584         (let ((fullname-start (point)))
5585           (insert fullname)
5586           (goto-char fullname-start)
5587           ;; RFC 822 says \ and nonmatching parentheses
5588           ;; must be escaped in comments.
5589           ;; Escape every instance of ()\ ...
5590           (while (re-search-forward "[()\\]" nil 1)
5591             (replace-match "\\\\\\&" t))
5592           ;; ... then undo escaping of matching parentheses,
5593           ;; including matching nested parentheses.
5594           (goto-char fullname-start)
5595           (while (re-search-forward
5596                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5597                   nil 1)
5598             (replace-match "\\1(\\3)" t)
5599             (goto-char fullname-start)))
5600         (insert ")")))
5601       (buffer-string))))
5602
5603 (defun message-make-sender ()
5604   "Return the \"real\" user address.
5605 This function tries to ignore all user modifications, and
5606 give as trustworthy answer as possible."
5607   (concat (user-login-name) "@" (system-name)))
5608
5609 (defun message-make-address ()
5610   "Make the address of the user."
5611   (or (message-user-mail-address)
5612       (concat (user-login-name) "@" (message-make-domain))))
5613
5614 (defun message-user-mail-address ()
5615   "Return the pertinent part of `user-mail-address'."
5616   (when (and user-mail-address
5617              (string-match "@.*\\." user-mail-address))
5618     (if (string-match " " user-mail-address)
5619         (nth 1 (mail-extract-address-components user-mail-address))
5620       user-mail-address)))
5621
5622 (defun message-sendmail-envelope-from ()
5623   "Return the envelope from."
5624   (cond ((eq message-sendmail-envelope-from 'header)
5625          (nth 1 (mail-extract-address-components
5626                  (message-fetch-field "from"))))
5627         ((stringp message-sendmail-envelope-from)
5628          message-sendmail-envelope-from)
5629         (t
5630          (message-make-address))))
5631
5632 (defun message-make-fqdn ()
5633   "Return user's fully qualified domain name."
5634   (let* ((system-name (system-name))
5635          (user-mail (message-user-mail-address))
5636          (user-domain
5637           (if (and user-mail
5638                    (string-match "@\\(.*\\)\\'" user-mail))
5639               (match-string 1 user-mail)))
5640          (case-fold-search t))
5641     (cond
5642      ((and message-user-fqdn
5643            (stringp message-user-fqdn)
5644            (string-match message-valid-fqdn-regexp message-user-fqdn)
5645            (not (string-match message-bogus-system-names message-user-fqdn)))
5646       ;; `message-user-fqdn' seems to be valid
5647       message-user-fqdn)
5648      ((and (string-match message-valid-fqdn-regexp system-name)
5649            (not (string-match message-bogus-system-names system-name)))
5650       ;; `system-name' returned the right result.
5651       system-name)
5652      ;; Try `mail-host-address'.
5653      ((and (boundp 'mail-host-address)
5654            (stringp mail-host-address)
5655            (string-match message-valid-fqdn-regexp mail-host-address)
5656            (not (string-match message-bogus-system-names mail-host-address)))
5657       mail-host-address)
5658      ;; We try `user-mail-address' as a backup.
5659      ((and user-domain
5660            (stringp user-domain)
5661            (string-match message-valid-fqdn-regexp user-domain)
5662            (not (string-match message-bogus-system-names user-domain)))
5663       user-domain)
5664      ;; Default to this bogus thing.
5665      (t
5666       (concat system-name
5667               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5668
5669 (defun message-make-host-name ()
5670   "Return the name of the host."
5671   (let ((fqdn (message-make-fqdn)))
5672     (string-match "^[^.]+\\." fqdn)
5673     (substring fqdn 0 (1- (match-end 0)))))
5674
5675 (defun message-make-domain ()
5676   "Return the domain name."
5677   (or mail-host-address
5678       (message-make-fqdn)))
5679
5680 (defun message-to-list-only ()
5681   "Send a message to the list only.
5682 Remove all addresses but the list address from To and Cc headers."
5683   (interactive)
5684   (let ((listaddr (message-make-mail-followup-to t)))
5685     (when listaddr
5686       (save-excursion
5687         (message-remove-header "to")
5688         (message-remove-header "cc")
5689         (message-position-on-field "To" "X-Draft-From")
5690         (insert listaddr)))))
5691
5692 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5693   "Return the Mail-Followup-To header.
5694 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5695 subscribed address (and not the additional To and Cc header contents)."
5696   (let* ((case-fold-search t)
5697          (to (message-fetch-field "To"))
5698          (cc (message-fetch-field "cc"))
5699          (msg-recipients (concat to (and to cc ", ") cc))
5700          (recipients
5701           (mapcar 'mail-strip-quoted-names
5702                   (message-tokenize-header msg-recipients)))
5703          (file-regexps
5704           (if message-subscribed-address-file
5705               (let (begin end item re)
5706                 (save-excursion
5707                   (with-temp-buffer
5708                     (insert-file-contents message-subscribed-address-file)
5709                     (while (not (eobp))
5710                       (setq begin (point))
5711                       (forward-line 1)
5712                       (setq end (point))
5713                       (if (bolp) (setq end (1- end)))
5714                       (setq item (regexp-quote (buffer-substring begin end)))
5715                       (if re (setq re (concat re "\\|" item))
5716                         (setq re (concat "\\`\\(" item))))
5717                     (and re (list (concat re "\\)\\'"))))))))
5718          (mft-regexps (apply 'append message-subscribed-regexps
5719                              (mapcar 'regexp-quote
5720                                      message-subscribed-addresses)
5721                              file-regexps
5722                              (mapcar 'funcall
5723                                      message-subscribed-address-functions))))
5724     (save-match-data
5725       (let ((list
5726              (loop for recipient in recipients
5727                when (loop for regexp in mft-regexps
5728                       when (string-match regexp recipient) return t)
5729                return recipient)))
5730         (when list
5731           (if only-show-subscribed
5732               list
5733             msg-recipients))))))
5734
5735 (defun message-idna-to-ascii-rhs-1 (header)
5736   "Interactively potentially IDNA encode domain names in HEADER."
5737   (let ((field (message-fetch-field header))
5738         rhs ace  address)
5739     (when field
5740       (dolist (rhs
5741                (mm-delete-duplicates
5742                 (mapcar (lambda (rhs) (or (cadr (split-string rhs "@")) ""))
5743                         (mapcar 'downcase
5744                                 (mapcar
5745                                  'cadr
5746                                  (mail-extract-address-components field t))))))
5747         ;; Note that `rhs' will be "" if the address does not have
5748         ;; the domain part, i.e., if it is a local user's address.
5749         (setq ace (if (string-match "\\`[[:ascii:]]*\\'" rhs)
5750                       rhs
5751                     (downcase (idna-to-ascii rhs))))
5752         (when (and (not (equal rhs ace))
5753                    (or (not (eq message-use-idna 'ask))
5754                        (y-or-n-p (format "Replace %s with %s in %s:? "
5755                                          rhs ace header))))
5756           (goto-char (point-min))
5757           (while (re-search-forward (concat "^" header ":") nil t)
5758             (message-narrow-to-field)
5759             (while (search-forward (concat "@" rhs) nil t)
5760               (replace-match (concat "@" ace) t t))
5761             (goto-char (point-max))
5762             (widen)))))))
5763
5764 (defun message-idna-to-ascii-rhs ()
5765   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5766 See `message-idna-encode'."
5767   (interactive)
5768   (when message-use-idna
5769     (save-excursion
5770       (save-restriction
5771         ;; `message-narrow-to-head' that recognizes only the first empty
5772         ;; line as the message header separator used to be used here.
5773         ;; However, since there is the "--text follows this line--" line
5774         ;; normally, it failed in narrowing to the headers and potentially
5775         ;; caused the IDNA encoding on lines that look like headers in
5776         ;; the message body.
5777         (message-narrow-to-headers-or-head)
5778         (message-idna-to-ascii-rhs-1 "From")
5779         (message-idna-to-ascii-rhs-1 "To")
5780         (message-idna-to-ascii-rhs-1 "Reply-To")
5781         (message-idna-to-ascii-rhs-1 "Mail-Reply-To")
5782         (message-idna-to-ascii-rhs-1 "Mail-Followup-To")
5783         (message-idna-to-ascii-rhs-1 "Cc")))))
5784
5785 (defun message-generate-headers (headers)
5786   "Prepare article HEADERS.
5787 Headers already prepared in the buffer are not modified."
5788   (setq headers (append headers message-required-headers))
5789   (save-restriction
5790     (message-narrow-to-headers)
5791     (let* ((Date (message-make-date))
5792            (Message-ID (message-make-message-id))
5793            (Organization (message-make-organization))
5794            (From (message-make-from))
5795            (Path (message-make-path))
5796            (Subject nil)
5797            (Newsgroups nil)
5798            (In-Reply-To (message-make-in-reply-to))
5799            (References (message-make-references))
5800            (To nil)
5801            (Distribution (message-make-distribution))
5802            (Lines (message-make-lines))
5803            (User-Agent message-newsreader)
5804            (Expires (message-make-expires))
5805            (case-fold-search t)
5806            (optionalp nil)
5807            header value elem header-string)
5808       ;; First we remove any old generated headers.
5809       (let ((headers message-deletable-headers))
5810         (unless (buffer-modified-p)
5811           (setq headers (delq 'Message-ID (copy-sequence headers))))
5812         (while headers
5813           (goto-char (point-min))
5814           (and (re-search-forward
5815                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5816                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5817                (message-delete-line))
5818           (pop headers)))
5819       ;; Go through all the required headers and see if they are in the
5820       ;; articles already.  If they are not, or are empty, they are
5821       ;; inserted automatically - except for Subject, Newsgroups and
5822       ;; Distribution.
5823       (while headers
5824         (goto-char (point-min))
5825         (setq elem (pop headers))
5826         (if (consp elem)
5827             (if (eq (car elem) 'optional)
5828                 (setq header (cdr elem)
5829                       optionalp t)
5830               (setq header (car elem)))
5831           (setq header elem))
5832         (setq header-string  (if (stringp header)
5833                                  header
5834                                (symbol-name header)))
5835         (when (or (not (re-search-forward
5836                         (concat "^"
5837                                 (regexp-quote (downcase header-string))
5838                                 ":")
5839                         nil t))
5840                   (progn
5841                     ;; The header was found.  We insert a space after the
5842                     ;; colon, if there is none.
5843                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5844                     ;; Find out whether the header is empty.
5845                     (looking-at "[ \t]*\n[^ \t]")))
5846           ;; So we find out what value we should insert.
5847           (setq value
5848                 (cond
5849                  ((and (consp elem)
5850                        (eq (car elem) 'optional)
5851                        (not (member header-string message-inserted-headers)))
5852                   ;; This is an optional header.  If the cdr of this
5853                   ;; is something that is nil, then we do not insert
5854                   ;; this header.
5855                   (setq header (cdr elem))
5856                   (or (and (functionp (cdr elem))
5857                            (funcall (cdr elem)))
5858                       (and (boundp (cdr elem))
5859                            (symbol-value (cdr elem)))))
5860                  ((consp elem)
5861                   ;; The element is a cons.  Either the cdr is a
5862                   ;; string to be inserted verbatim, or it is a
5863                   ;; function, and we insert the value returned from
5864                   ;; this function.
5865                   (or (and (stringp (cdr elem))
5866                            (cdr elem))
5867                       (and (functionp (cdr elem))
5868                            (funcall (cdr elem)))))
5869                  ((and (boundp header)
5870                        (symbol-value header))
5871                   ;; The element is a symbol.  We insert the value
5872                   ;; of this symbol, if any.
5873                   (symbol-value header))
5874                  ((not (message-check-element
5875                         (intern (downcase (symbol-name header)))))
5876                   ;; We couldn't generate a value for this header,
5877                   ;; so we just ask the user.
5878                   (read-from-minibuffer
5879                    (format "Empty header for %s; enter value: " header)))))
5880           ;; Finally insert the header.
5881           (when (and value
5882                      (not (equal value "")))
5883             (save-excursion
5884               (if (bolp)
5885                   (progn
5886                     ;; This header didn't exist, so we insert it.
5887                     (goto-char (point-max))
5888                     (let ((formatter
5889                            (cdr (assq header message-header-format-alist))))
5890                       (if formatter
5891                           (funcall formatter header value)
5892                         (insert header-string ": " value))
5893                       (push header-string message-inserted-headers)
5894                       (goto-char (message-fill-field))
5895                       ;; We check whether the value was ended by a
5896                       ;; newline.  If not, we insert one.
5897                       (unless (bolp)
5898                         (insert "\n"))
5899                       (forward-line -1)))
5900                 ;; The value of this header was empty, so we clear
5901                 ;; totally and insert the new value.
5902                 (delete-region (point) (point-at-eol))
5903                 ;; If the header is optional, and the header was
5904                 ;; empty, we can't insert it anyway.
5905                 (unless optionalp
5906                   (push header-string message-inserted-headers)
5907                   (insert value)
5908                   (message-fill-field)))
5909               ;; Add the deletable property to the headers that require it.
5910               (and (memq header message-deletable-headers)
5911                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5912                    (add-text-properties
5913                     (point) (match-end 0)
5914                     '(message-deletable t face italic) (current-buffer)))))))
5915       ;; Insert new Sender if the From is strange.
5916       (let ((from (message-fetch-field "from"))
5917             (sender (message-fetch-field "sender"))
5918             (secure-sender (message-make-sender)))
5919         (when (and from
5920                    (not (message-check-element 'sender))
5921                    (not (string=
5922                          (downcase
5923                           (cadr (mail-extract-address-components from)))
5924                          (downcase secure-sender)))
5925                    (or (null sender)
5926                        (not
5927                         (string=
5928                          (downcase
5929                           (cadr (mail-extract-address-components sender)))
5930                          (downcase secure-sender)))))
5931           (goto-char (point-min))
5932           ;; Rename any old Sender headers to Original-Sender.
5933           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5934             (beginning-of-line)
5935             (insert "Original-")
5936             (beginning-of-line))
5937           (when (or (message-news-p)
5938                     (string-match "@.+\\.." secure-sender))
5939             (insert "Sender: " secure-sender "\n"))))
5940       ;; Check for IDNA
5941       (message-idna-to-ascii-rhs))))
5942
5943 (defun message-insert-courtesy-copy ()
5944   "Insert a courtesy message in mail copies of combined messages."
5945   (let (newsgroups)
5946     (save-excursion
5947       (save-restriction
5948         (message-narrow-to-headers)
5949         (when (setq newsgroups (message-fetch-field "newsgroups"))
5950           (goto-char (point-max))
5951           (insert "Posted-To: " newsgroups "\n")))
5952       (forward-line 1)
5953       (when message-courtesy-message
5954         (cond
5955          ((string-match "%s" message-courtesy-message)
5956           (insert (format message-courtesy-message newsgroups)))
5957          (t
5958           (insert message-courtesy-message)))))))
5959
5960 ;;;
5961 ;;; Setting up a message buffer
5962 ;;;
5963
5964 (defun message-skip-to-next-address ()
5965   (let ((end (save-excursion
5966                (message-next-header)
5967                (point)))
5968         quoted char)
5969     (when (looking-at ",")
5970       (forward-char 1))
5971     (while (and (not (= (point) end))
5972                 (or (not (eq char ?,))
5973                     quoted))
5974       (skip-chars-forward "^,\"" (point-max))
5975       (when (eq (setq char (following-char)) ?\")
5976         (setq quoted (not quoted)))
5977       (unless (= (point) end)
5978         (forward-char 1)))
5979     (skip-chars-forward " \t\n")))
5980
5981 (defun message-fill-address (header value)
5982   (insert (capitalize (symbol-name header))
5983           ": "
5984           (if (consp value) (car value) value)
5985           "\n")
5986   (message-fill-field-address))
5987
5988 (defun message-split-line ()
5989   "Split current line, moving portion beyond point vertically down.
5990 If the current line has `message-yank-prefix', insert it on the new line."
5991   (interactive "*")
5992   (condition-case nil
5993       (split-line message-yank-prefix) ;; Emacs 22.1+ supports arg.
5994     (error
5995      (split-line))))
5996
5997 (defun message-insert-header (header value)
5998   (insert (capitalize (symbol-name header))
5999           ": "
6000           (if (consp value) (car value) value)))
6001
6002 (defun message-field-name ()
6003   (save-excursion
6004     (goto-char (point-min))
6005     (when (looking-at "\\([^:]+\\):")
6006       (intern (capitalize (match-string 1))))))
6007
6008 (defun message-fill-field ()
6009   (save-excursion
6010     (save-restriction
6011       (message-narrow-to-field)
6012       (let ((field-name (message-field-name)))
6013         (funcall (or (cadr (assq field-name message-field-fillers))
6014                      'message-fill-field-general)))
6015       (point-max))))
6016
6017 (defun message-fill-field-address ()
6018   (while (not (eobp))
6019     (message-skip-to-next-address)
6020     (let (last)
6021       (if (and (> (current-column) 78)
6022                last)
6023           (progn
6024             (save-excursion
6025               (goto-char last)
6026               (insert "\n\t"))
6027             (setq last (1+ (point))))
6028         (setq last (1+ (point)))))))
6029
6030 (defun message-fill-field-general ()
6031   (let ((begin (point))
6032         (fill-column 78)
6033         (fill-prefix "\t"))
6034     (while (and (search-forward "\n" nil t)
6035                 (not (eobp)))
6036       (replace-match " " t t))
6037     (fill-region-as-paragraph begin (point-max))
6038     ;; Tapdance around looong Message-IDs.
6039     (forward-line -1)
6040     (when (looking-at "[ \t]*$")
6041       (message-delete-line))
6042     (goto-char begin)
6043     (search-forward ":" nil t)
6044     (when (looking-at "\n[ \t]+")
6045       (replace-match " " t t))
6046     (goto-char (point-max))))
6047
6048 (defun message-shorten-1 (list cut surplus)
6049   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
6050   (setcdr (nthcdr (- cut 2) list)
6051           (nthcdr (+ (- cut 2) surplus 1) list)))
6052
6053 (defun message-shorten-references (header references)
6054   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
6055 When sending via news, also check that the REFERENCES are less
6056 than 988 characters long, and if they are not, trim them until
6057 they are."
6058   (let ((maxcount 21)
6059         (count 0)
6060         (cut 2)
6061         refs)
6062     (with-temp-buffer
6063       (insert references)
6064       (goto-char (point-min))
6065       ;; Cons a list of valid references.  GNKSA says we must not include MIDs
6066       ;; with whitespace or missing brackets (7.a "Does not propagate broken
6067       ;; Message-IDs in original References").
6068       (while (re-search-forward "<[^ <]+@[^ <]+>" nil t)
6069         (push (match-string 0) refs))
6070       (setq refs (nreverse refs)
6071             count (length refs)))
6072
6073     ;; If the list has more than MAXCOUNT elements, trim it by
6074     ;; removing the CUTth element and the required number of
6075     ;; elements that follow.
6076     (when (> count maxcount)
6077       (let ((surplus (- count maxcount)))
6078         (message-shorten-1 refs cut surplus)
6079         (decf count surplus)))
6080
6081     ;; When sending via news, make sure the total folded length will
6082     ;; be less than 998 characters.  This is to cater to broken INN
6083     ;; 2.3 which counts the total number of characters in a header
6084     ;; rather than the physical line length of each line, as it should.
6085     ;;
6086     ;; This hack should be removed when it's believed than INN 2.3 is
6087     ;; no longer widely used.
6088     ;;
6089     ;; At this point the headers have not been generated, thus we use
6090     ;; message-this-is-news directly.
6091     (when message-this-is-news
6092       (while (< 998
6093                 (with-temp-buffer
6094                   (message-insert-header
6095                    header (mapconcat #'identity refs " "))
6096                   (buffer-size)))
6097         (message-shorten-1 refs cut 1)))
6098     ;; Finally, collect the references back into a string and insert
6099     ;; it into the buffer.
6100     (message-insert-header header (mapconcat #'identity refs " "))))
6101
6102 (defun message-position-point ()
6103   "Move point to where the user probably wants to find it."
6104   (message-narrow-to-headers)
6105   (cond
6106    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
6107     (search-backward ":" )
6108     (widen)
6109     (forward-char 1)
6110     (if (eq (char-after) ? )
6111         (forward-char 1)
6112       (insert " ")))
6113    (t
6114     (goto-char (point-max))
6115     (widen)
6116     (forward-line 1)
6117     (unless (looking-at "$")
6118       (forward-line 2)))
6119    (sit-for 0)))
6120
6121 (defcustom message-beginning-of-line t
6122   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
6123  goes to beginning of header values."
6124   :version "22.1"
6125   :group 'message-buffers
6126   :link '(custom-manual "(message)Movement")
6127   :type 'boolean)
6128
6129 (defun message-beginning-of-line (&optional n)
6130   "Move point to beginning of header value or to beginning of line.
6131 The prefix argument N is passed directly to `beginning-of-line'.
6132
6133 This command is identical to `beginning-of-line' if point is
6134 outside the message header or if the option `message-beginning-of-line'
6135 is nil.
6136
6137 If point is in the message header and on a (non-continued) header
6138 line, move point to the beginning of the header value or the beginning of line,
6139 whichever is closer.  If point is already at beginning of line, move point to
6140 beginning of header value.  Therefore, repeated calls will toggle point
6141 between beginning of field and beginning of line."
6142   (interactive "p")
6143   (let ((zrs 'zmacs-region-stays))
6144     (when (and (featurep 'xemacs) (interactive-p) (boundp zrs))
6145       (set zrs t)))
6146   (if (and message-beginning-of-line
6147            (message-point-in-header-p))
6148       (let* ((here (point))
6149              (bol (progn (beginning-of-line n) (point)))
6150              (eol (point-at-eol))
6151              (eoh (re-search-forward ": *" eol t)))
6152         (goto-char
6153          (if (and eoh (or (< eoh here) (= bol here)))
6154              eoh bol)))
6155     (beginning-of-line n)))
6156
6157 (defun message-buffer-name (type &optional to group)
6158   "Return a new (unique) buffer name based on TYPE and TO."
6159   (cond
6160    ;; Generate a new buffer name The Message Way.
6161    ((memq message-generate-new-buffers '(unique t))
6162     (generate-new-buffer-name
6163      (concat "*" type
6164              (if to
6165                  (concat " to "
6166                          (or (car (mail-extract-address-components to))
6167                              to) "")
6168                "")
6169              (if (and group (not (string= group ""))) (concat " on " group) "")
6170              "*")))
6171    ;; Check whether `message-generate-new-buffers' is a function,
6172    ;; and if so, call it.
6173    ((functionp message-generate-new-buffers)
6174     (funcall message-generate-new-buffers type to group))
6175    ((eq message-generate-new-buffers 'unsent)
6176     (generate-new-buffer-name
6177      (concat "*unsent " type
6178              (if to
6179                  (concat " to "
6180                          (or (car (mail-extract-address-components to))
6181                              to) "")
6182                "")
6183              (if (and group (not (string= group ""))) (concat " on " group) "")
6184              "*")))
6185    ;; Search for the existing message buffer with the specified name.
6186    (t
6187     (let* ((new (if (eq message-generate-new-buffers 'standard)
6188                     (generate-new-buffer-name (concat "*" type " message*"))
6189                   (let ((message-generate-new-buffers 'unique))
6190                     (message-buffer-name type to group))))
6191            (regexp (concat "\\`"
6192                            (regexp-quote
6193                             (if (string-match "<[0-9]+>\\'" new)
6194                                 (substring new 0 (match-beginning 0))
6195                               new))
6196                            "\\(?:<\\([0-9]+\\)>\\)?\\'"))
6197            (case-fold-search nil))
6198       (or (cdar
6199            (last
6200             (sort
6201              (delq nil
6202                    (mapcar
6203                     (lambda (b)
6204                       (when (and (string-match regexp (setq b (buffer-name b)))
6205                                  (eq (with-current-buffer b major-mode)
6206                                      'message-mode))
6207                         (cons (string-to-number (or (match-string 1 b) "1"))
6208                               b)))
6209                     (buffer-list)))
6210              'car-less-than-car)))
6211           new)))))
6212
6213 (defun message-pop-to-buffer (name &optional switch-function)
6214   "Pop to buffer NAME, and warn if it already exists and is modified."
6215   (let ((buffer (get-buffer name)))
6216     (if (and buffer
6217              (buffer-name buffer))
6218         (let ((window (get-buffer-window buffer 0)))
6219           (if window
6220               ;; Raise the frame already displaying the message buffer.
6221               (progn
6222                 (gnus-select-frame-set-input-focus (window-frame window))
6223                 (select-window window))
6224             (funcall (or switch-function 'pop-to-buffer) buffer)
6225             (set-buffer buffer))
6226           (when (and (buffer-modified-p)
6227                      (not (prog1
6228                               (y-or-n-p
6229                                "Message already being composed; erase? ")
6230                             (message nil))))
6231             (error "Message being composed")))
6232       (funcall (or switch-function 'pop-to-buffer) name)
6233       (set-buffer name))
6234     (erase-buffer)
6235     (message-mode)))
6236
6237 (defun message-do-send-housekeeping ()
6238   "Kill old message buffers."
6239   ;; We might have sent this buffer already.  Delete it from the
6240   ;; list of buffers.
6241   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
6242   (while (and message-max-buffers
6243               message-buffer-list
6244               (>= (length message-buffer-list) message-max-buffers))
6245     ;; Kill the oldest buffer -- unless it has been changed.
6246     (let ((buffer (pop message-buffer-list)))
6247       (when (and (buffer-name buffer)
6248                  (not (buffer-modified-p buffer)))
6249         (kill-buffer buffer))))
6250   ;; Rename the buffer.
6251   (if message-send-rename-function
6252       (funcall message-send-rename-function)
6253     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
6254     (when (string-match
6255            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
6256            (buffer-name))
6257       (let ((name (match-string 2 (buffer-name)))
6258             to group)
6259         (if (not (or (null name)
6260                      (string-equal name "mail")
6261                      (string-equal name "posting")))
6262             (setq name (concat "*sent " name "*"))
6263           (message-narrow-to-headers)
6264           (setq to (message-fetch-field "to"))
6265           (setq group (message-fetch-field "newsgroups"))
6266           (widen)
6267           (setq name
6268                 (cond
6269                  (to (concat "*sent mail to "
6270                              (or (car (mail-extract-address-components to))
6271                                  to) "*"))
6272                  ((and group (not (string= group "")))
6273                   (concat "*sent posting on " group "*"))
6274                  (t "*sent mail*"))))
6275         (unless (string-equal name (buffer-name))
6276           (rename-buffer name t)))))
6277   ;; Push the current buffer onto the list.
6278   (when message-max-buffers
6279     (setq message-buffer-list
6280           (nconc message-buffer-list (list (current-buffer))))))
6281
6282 (defun message-mail-user-agent ()
6283   (let ((mua (cond
6284               ((not message-mail-user-agent) nil)
6285               ((eq message-mail-user-agent t) mail-user-agent)
6286               (t message-mail-user-agent))))
6287     (if (memq mua '(message-user-agent gnus-user-agent))
6288         nil
6289       mua)))
6290
6291 ;; YANK-ACTION, if non-nil, can be a buffer or a yank action of the
6292 ;; form (FUNCTION . ARGS).
6293 (defun message-setup (headers &optional yank-action actions
6294                               continue switch-function)
6295   (let ((mua (message-mail-user-agent))
6296         subject to field)
6297     (if (not (and message-this-is-mail mua))
6298         (message-setup-1 headers yank-action actions)
6299       (setq headers (copy-sequence headers))
6300       (setq field (assq 'Subject headers))
6301       (when field
6302         (setq subject (cdr field))
6303         (setq headers (delq field headers)))
6304       (setq field (assq 'To headers))
6305       (when field
6306         (setq to (cdr field))
6307         (setq headers (delq field headers)))
6308       (let ((mail-user-agent mua))
6309         (compose-mail to subject
6310                       (mapcar (lambda (item)
6311                                 (cons
6312                                  (format "%s" (car item))
6313                                  (cdr item)))
6314                               headers)
6315                       continue switch-function
6316                       (if (bufferp yank-action)
6317                           (list 'insert-buffer yank-action)
6318                         yank-action)
6319                       actions)))))
6320
6321 (defun message-headers-to-generate (headers included-headers excluded-headers)
6322   "Return a list that includes all headers from HEADERS.
6323 If INCLUDED-HEADERS is a list, just include those headers.  If it is
6324 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
6325 are not included."
6326   (let ((result nil)
6327         header-name)
6328     (dolist (header headers)
6329       (setq header-name (cond
6330                          ((and (consp header)
6331                                (eq (car header) 'optional))
6332                           ;; On the form (optional . Header)
6333                           (cdr header))
6334                          ((consp header)
6335                           ;; On the form (Header . function)
6336                           (car header))
6337                          (t
6338                           ;; Just a Header.
6339                           header)))
6340       (when (and (not (memq header-name excluded-headers))
6341                  (or (eq included-headers t)
6342                      (memq header-name included-headers)))
6343         (push header result)))
6344     (nreverse result)))
6345
6346 (defun message-setup-1 (headers &optional yank-action actions)
6347   (dolist (action actions)
6348     (condition-case nil
6349         (add-to-list 'message-send-actions
6350                      `(apply ',(car action) ',(cdr action)))))
6351   (setq message-reply-buffer
6352         (if (and (consp yank-action)
6353                  (eq (car yank-action) 'insert-buffer))
6354             (nth 1 yank-action)
6355           yank-action))
6356   (goto-char (point-min))
6357   ;; Insert all the headers.
6358   (mail-header-format
6359    (let ((h headers)
6360          (alist message-header-format-alist))
6361      (while h
6362        (unless (assq (caar h) message-header-format-alist)
6363          (push (list (caar h)) alist))
6364        (pop h))
6365      alist)
6366    headers)
6367   (delete-region (point) (progn (forward-line -1) (point)))
6368   (when message-default-headers
6369     (insert message-default-headers)
6370     (or (bolp) (insert ?\n)))
6371   (insert mail-header-separator "\n")
6372   (forward-line -1)
6373   (when (message-news-p)
6374     (when message-default-news-headers
6375       (insert message-default-news-headers)
6376       (or (bolp) (insert ?\n)))
6377     (when message-generate-headers-first
6378       (message-generate-headers
6379        (message-headers-to-generate
6380         (append message-required-news-headers
6381                 message-required-headers)
6382         message-generate-headers-first
6383         '(Lines Subject)))))
6384   (when (message-mail-p)
6385     (when message-default-mail-headers
6386       (insert message-default-mail-headers)
6387       (or (bolp) (insert ?\n)))
6388     (when message-generate-headers-first
6389       (message-generate-headers
6390        (message-headers-to-generate
6391         (append message-required-mail-headers
6392                 message-required-headers)
6393         message-generate-headers-first
6394         '(Lines Subject)))))
6395   (run-hooks 'message-signature-setup-hook)
6396   (message-insert-signature)
6397   (save-restriction
6398     (message-narrow-to-headers)
6399     (run-hooks 'message-header-setup-hook))
6400   (setq buffer-undo-list nil)
6401   (when message-generate-hashcash
6402     ;; Generate hashcash headers for recipients already known
6403     (mail-add-payment-async))
6404   ;; Gnus posting styles are applied via buffer-local `message-setup-hook'
6405   ;; values.
6406   (run-hooks 'message-setup-hook)
6407   ;; Do this last to give it precedence over posting styles, etc.
6408   (when (message-mail-p)
6409     (save-restriction
6410       (message-narrow-to-headers)
6411       (if message-alternative-emails
6412           (message-use-alternative-email-as-from))))
6413   (message-position-point)
6414   ;; Allow correct handling of `message-checksum' in `message-yank-original':
6415   (set-buffer-modified-p nil)
6416   (undo-boundary))
6417
6418 (defun message-set-auto-save-file-name ()
6419   "Associate the message buffer with a file in the drafts directory."
6420   (when message-auto-save-directory
6421     (unless (file-directory-p
6422              (directory-file-name message-auto-save-directory))
6423       (make-directory message-auto-save-directory t))
6424     (if (gnus-alive-p)
6425         (setq message-draft-article
6426               (nndraft-request-associate-buffer "drafts"))
6427
6428       ;; If Gnus were alive, draft messages would be saved in the drafts folder.
6429       ;; But Gnus is not alive, so arrange to save the draft message in a
6430       ;; regular file in message-auto-save-directory.  Append a unique
6431       ;; time-based suffix to the filename to allow multiple drafts to be saved
6432       ;; simultaneously without overwriting each other (which mimics the
6433       ;; functionality of the Gnus drafts folder).
6434       (setq buffer-file-name (expand-file-name
6435                               (concat
6436                               (if (memq system-type
6437                                         '(ms-dos windows-nt cygwin))
6438                                   "message"
6439                                 "*message*")
6440                                (format-time-string "-%Y%m%d-%H%M%S"))
6441                               message-auto-save-directory))
6442       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6443     (clear-visited-file-modtime)
6444     (setq buffer-file-coding-system message-draft-coding-system)))
6445
6446 (defun message-disassociate-draft ()
6447   "Disassociate the message buffer from the drafts directory."
6448   (when message-draft-article
6449     (nndraft-request-expire-articles
6450      (list message-draft-article) "drafts" nil t)))
6451
6452 (defun message-insert-headers ()
6453   "Generate the headers for the article."
6454   (interactive)
6455   (save-excursion
6456     (save-restriction
6457       (message-narrow-to-headers)
6458       (when (message-news-p)
6459         (message-generate-headers
6460          (delq 'Lines
6461                (delq 'Subject
6462                      (copy-sequence message-required-news-headers)))))
6463       (when (message-mail-p)
6464         (message-generate-headers
6465          (delq 'Lines
6466                (delq 'Subject
6467                      (copy-sequence message-required-mail-headers))))))))
6468
6469 \f
6470
6471 ;;;
6472 ;;; Commands for interfacing with message
6473 ;;;
6474
6475 ;;;###autoload
6476 (defun message-mail (&optional to subject
6477                                other-headers continue switch-function
6478                                yank-action send-actions)
6479   "Start editing a mail message to be sent.
6480 OTHER-HEADERS is an alist of header/value pairs.  CONTINUE says whether
6481 to continue editing a message already being composed.  SWITCH-FUNCTION
6482 is a function used to switch to and display the mail buffer."
6483   (interactive)
6484   (let ((message-this-is-mail t))
6485     (unless (message-mail-user-agent)
6486       (message-pop-to-buffer
6487        ;; Search for the existing message buffer if `continue' is non-nil.
6488        (let ((message-generate-new-buffers
6489               (when (or (not continue)
6490                         (eq message-generate-new-buffers 'standard)
6491                         (functionp message-generate-new-buffers))
6492                 message-generate-new-buffers)))
6493          (message-buffer-name "mail" to))
6494        switch-function))
6495     (message-setup
6496      (nconc
6497       `((To . ,(or to "")) (Subject . ,(or subject "")))
6498       (when other-headers other-headers))
6499      yank-action send-actions continue switch-function)
6500     ;; FIXME: Should return nil if failure.
6501     t))
6502
6503 ;;;###autoload
6504 (defun message-news (&optional newsgroups subject)
6505   "Start editing a news article to be sent."
6506   (interactive)
6507   (let ((message-this-is-news t))
6508     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6509     (message-setup `((Newsgroups . ,(or newsgroups ""))
6510                      (Subject . ,(or subject ""))))))
6511
6512 (defun message-alter-recipients-discard-bogus-full-name (addrcell)
6513   "Discard mail address in full names.
6514 When the full name in reply headers contains the mail
6515 address (e.g. \"foo@bar <foo@bar>\"), discard full name.
6516 ADDRCELL is a cons cell where the car is the mail address and the
6517 cdr is the complete address (full name and mail address)."
6518   (if (string-match (concat (regexp-quote (car addrcell)) ".*"
6519                             (regexp-quote (car addrcell)))
6520                     (cdr addrcell))
6521       (cons (car addrcell) (car addrcell))
6522     addrcell))
6523
6524 (defcustom message-alter-recipients-function nil
6525   "Function called to allow alteration of reply header structures.
6526 It is called in `message-get-reply-headers' for each recipient.
6527 The function is called with one parameter, a cons cell ..."
6528   :type '(choice (const :tag "None" nil)
6529                  (const :tag "Discard bogus full name"
6530                         message-alter-recipients-discard-bogus-full-name)
6531                  function)
6532   :version "23.1" ;; No Gnus
6533   :group 'message-headers)
6534
6535 (defun message-get-reply-headers (wide &optional to-address address-headers)
6536   (let (follow-to mct never-mct to cc author mft recipients extra)
6537     ;; Find all relevant headers we need.
6538     (save-restriction
6539       (message-narrow-to-headers-or-head)
6540       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
6541       ;; message-header-synonyms.
6542       (setq to (or (message-fetch-field "to")
6543                    (and (loop for synonym in message-header-synonyms
6544                               when (memq 'Original-To synonym)
6545                               return t)
6546                         (message-fetch-field "original-to")))
6547             cc (message-fetch-field "cc")
6548             extra (when message-extra-wide-headers
6549                     (mapconcat 'identity
6550                                (mapcar 'message-fetch-field
6551                                        message-extra-wide-headers)
6552                                ", "))
6553             mct (message-fetch-field "mail-copies-to")
6554             author (or (message-fetch-field "mail-reply-to")
6555                        (message-fetch-field "reply-to")
6556                        (message-fetch-field "from")
6557                        "")
6558             mft (and message-use-mail-followup-to
6559                      (message-fetch-field "mail-followup-to"))))
6560
6561     ;; Handle special values of Mail-Copies-To.
6562     (when mct
6563       (cond ((or (equal (downcase mct) "never")
6564                  (equal (downcase mct) "nobody"))
6565              (setq never-mct t)
6566              (setq mct nil))
6567             ((or (equal (downcase mct) "always")
6568                  (equal (downcase mct) "poster"))
6569              (setq mct author))))
6570
6571     (save-match-data
6572       ;; Build (textual) list of new recipient addresses.
6573       (cond
6574        ((not wide)
6575         (setq recipients (concat ", " author)))
6576        (address-headers
6577         (dolist (header address-headers)
6578           (let ((value (message-fetch-field header)))
6579             (when value
6580               (setq recipients (concat recipients ", " value))))))
6581        ((and mft
6582              (string-match "[^ \t,]" mft)
6583              (or (not (eq message-use-mail-followup-to 'ask))
6584                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6585 You should normally obey the Mail-Followup-To: header.  In this
6586 article, it has the value of
6587
6588 " mft "
6589
6590 which directs your response to " (if (string-match "," mft)
6591                                      "the specified addresses"
6592                                    "that address only") ".
6593
6594 Most commonly, Mail-Followup-To is used by a mailing list poster to
6595 express that responses should be sent to just the list, and not the
6596 poster as well.
6597
6598 If a message is posted to several mailing lists, Mail-Followup-To may
6599 also be used to direct the following discussion to one list only,
6600 because discussions that are spread over several lists tend to be
6601 fragmented and very difficult to follow.
6602
6603 Also, some source/announcement lists are not intended for discussion;
6604 responses here are directed to other addresses.
6605
6606 You may customize the variable `message-use-mail-followup-to', if you
6607 want to get rid of this query permanently.")))
6608         (setq recipients (concat ", " mft)))
6609        (to-address
6610         (setq recipients (concat ", " to-address))
6611         ;; If the author explicitly asked for a copy, we don't deny it to them.
6612         (if mct (setq recipients (concat recipients ", " mct))))
6613        (t
6614         (setq recipients (if never-mct "" (concat ", " author)))
6615         (if to (setq recipients (concat recipients ", " to)))
6616         (if cc (setq recipients (concat recipients ", " cc)))
6617         (if extra (setq recipients (concat recipients ", " extra)))
6618         (if mct (setq recipients (concat recipients ", " mct)))))
6619       (if (>= (length recipients) 2)
6620           ;; Strip the leading ", ".
6621           (setq recipients (substring recipients 2)))
6622       ;; Squeeze whitespace.
6623       (while (string-match "[ \t][ \t]+" recipients)
6624         (setq recipients (replace-match " " t t recipients)))
6625       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6626       (let ((rmail-dont-reply-to-names (message-dont-reply-to-names)))
6627         (setq recipients (rmail-dont-reply-to recipients)))
6628       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6629       (if (string-equal recipients "")
6630           (setq recipients author))
6631       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6632       (setq recipients
6633             (mapcar
6634              (lambda (addr)
6635                (if message-alter-recipients-function
6636                    (funcall message-alter-recipients-function
6637                             (cons (downcase (mail-strip-quoted-names addr))
6638                                   addr))
6639                  (cons (downcase (mail-strip-quoted-names addr)) addr)))
6640              (message-tokenize-header recipients)))
6641       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6642       (let ((s recipients))
6643         (while s
6644           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6645
6646       ;; Remove hierarchical lists that are contained within each other,
6647       ;; if message-hierarchical-addresses is defined.
6648       (when message-hierarchical-addresses
6649         (let ((plain-addrs (mapcar 'car recipients))
6650               subaddrs recip)
6651           (while plain-addrs
6652             (setq subaddrs (assoc (car plain-addrs)
6653                                   message-hierarchical-addresses)
6654                   plain-addrs (cdr plain-addrs))
6655             (when subaddrs
6656               (setq subaddrs (cdr subaddrs))
6657               (while subaddrs
6658                 (setq recip (assoc (car subaddrs) recipients)
6659                       subaddrs (cdr subaddrs))
6660                 (if recip
6661                     (setq recipients (delq recip recipients))))))))
6662
6663       (setq recipients (message-prune-recipients recipients))
6664
6665       ;; Build the header alist.  Allow the user to be asked whether
6666       ;; or not to reply to all recipients in a wide reply.
6667       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6668       (when (and recipients
6669                  (or (not message-wide-reply-confirm-recipients)
6670                      (y-or-n-p "Reply to all recipients? ")))
6671         (setq recipients (mapconcat
6672                           (lambda (addr) (cdr addr)) recipients ", "))
6673         (if (string-match "^ +" recipients)
6674             (setq recipients (substring recipients (match-end 0))))
6675         (push (cons 'Cc recipients) follow-to)))
6676     follow-to))
6677
6678 (defun message-prune-recipients (recipients)
6679   (dolist (rule message-prune-recipient-rules)
6680     (let ((match (car rule))
6681           dup-match
6682           address)
6683       (dolist (recipient recipients)
6684         (setq address (car recipient))
6685         (when (string-match match address)
6686           (setq dup-match (replace-match (cadr rule) nil nil address))
6687           (dolist (recipient recipients)
6688             ;; Don't delete the address that triggered this.
6689             (when (and (not (eq address (car recipient)))
6690                        (string-match dup-match (car recipient)))
6691               (setq recipients (delq recipient recipients))))))))
6692   recipients)
6693
6694 (defcustom message-simplify-subject-functions
6695   '(message-strip-list-identifiers
6696     message-strip-subject-re
6697     message-strip-subject-trailing-was
6698     message-strip-subject-encoded-words)
6699   "List of functions taking a string argument that simplify subjects.
6700 The functions are applied when replying to a message.
6701
6702 Useful functions to put in this list include:
6703 `message-strip-list-identifiers', `message-strip-subject-re',
6704 `message-strip-subject-trailing-was', and
6705 `message-strip-subject-encoded-words'."
6706   :version "22.1" ;; Gnus 5.10.9
6707   :group 'message-various
6708   :type '(repeat function))
6709
6710 (defun message-simplify-subject (subject &optional functions)
6711   "Return simplified SUBJECT."
6712   (unless functions
6713     ;; Simplify fully:
6714     (setq functions message-simplify-subject-functions))
6715   (when (and (memq 'message-strip-list-identifiers functions)
6716              gnus-list-identifiers)
6717     (setq subject (message-strip-list-identifiers subject)))
6718   (when (memq 'message-strip-subject-re functions)
6719     (setq subject (concat "Re: " (message-strip-subject-re subject))))
6720   (when (and (memq 'message-strip-subject-trailing-was functions)
6721              message-subject-trailing-was-query)
6722     (setq subject (message-strip-subject-trailing-was subject)))
6723   (when (memq 'message-strip-subject-encoded-words functions)
6724     (setq subject (message-strip-subject-encoded-words subject)))
6725   subject)
6726
6727 ;;;###autoload
6728 (defun message-reply (&optional to-address wide)
6729   "Start editing a reply to the article in the current buffer."
6730   (interactive)
6731   (require 'gnus-sum)                   ; for gnus-list-identifiers
6732   (let ((cur (current-buffer))
6733         from subject date reply-to to cc
6734         references message-id follow-to
6735         (inhibit-point-motion-hooks t)
6736         (message-this-is-mail t)
6737         gnus-warning)
6738     (save-restriction
6739       (message-narrow-to-head-1)
6740       ;; Allow customizations to have their say.
6741       (if (not wide)
6742           ;; This is a regular reply.
6743           (when (functionp message-reply-to-function)
6744             (save-excursion
6745               (setq follow-to (funcall message-reply-to-function))))
6746         ;; This is a followup.
6747         (when (functionp message-wide-reply-to-function)
6748           (save-excursion
6749             (setq follow-to
6750                   (funcall message-wide-reply-to-function)))))
6751       (setq message-id (message-fetch-field "message-id" t)
6752             references (message-fetch-field "references")
6753             date (message-fetch-field "date")
6754             from (or (message-fetch-field "from") "nobody")
6755             subject (or (message-fetch-field "subject") "none"))
6756
6757       ;; Strip list identifiers, "Re: ", and "was:"
6758       (setq subject (message-simplify-subject subject))
6759
6760       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6761                  (string-match "<[^>]+>" gnus-warning))
6762         (setq message-id (match-string 0 gnus-warning)))
6763
6764       (unless follow-to
6765         (setq follow-to (message-get-reply-headers wide to-address))))
6766
6767     (unless (message-mail-user-agent)
6768       (message-pop-to-buffer
6769        (message-buffer-name
6770         (if wide "wide reply" "reply") from
6771         (if wide to-address nil))))
6772
6773     (setq message-reply-headers
6774           (vector 0 subject from date message-id references 0 0 ""))
6775
6776     (message-setup
6777      `((Subject . ,subject)
6778        ,@follow-to)
6779      cur)))
6780
6781 ;;;###autoload
6782 (defun message-wide-reply (&optional to-address)
6783   "Make a \"wide\" reply to the message in the current buffer."
6784   (interactive)
6785   (message-reply to-address t))
6786
6787 ;;;###autoload
6788 (defun message-followup (&optional to-newsgroups)
6789   "Follow up to the message in the current buffer.
6790 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6791   (interactive)
6792   (require 'gnus-sum)                   ; for gnus-list-identifiers
6793   (let ((cur (current-buffer))
6794         from subject date reply-to mrt mct
6795         references message-id follow-to
6796         (inhibit-point-motion-hooks t)
6797         (message-this-is-news t)
6798         followup-to distribution newsgroups gnus-warning posted-to)
6799     (save-restriction
6800       (narrow-to-region
6801        (goto-char (point-min))
6802        (if (search-forward "\n\n" nil t)
6803            (1- (point))
6804          (point-max)))
6805       (when (functionp message-followup-to-function)
6806         (setq follow-to
6807               (funcall message-followup-to-function)))
6808       (setq from (message-fetch-field "from")
6809             date (message-fetch-field "date")
6810             subject (or (message-fetch-field "subject") "none")
6811             references (message-fetch-field "references")
6812             message-id (message-fetch-field "message-id" t)
6813             followup-to (message-fetch-field "followup-to")
6814             newsgroups (message-fetch-field "newsgroups")
6815             posted-to (message-fetch-field "posted-to")
6816             reply-to (message-fetch-field "reply-to")
6817             mrt (message-fetch-field "mail-reply-to")
6818             distribution (message-fetch-field "distribution")
6819             mct (message-fetch-field "mail-copies-to"))
6820       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6821                  (string-match "<[^>]+>" gnus-warning))
6822         (setq message-id (match-string 0 gnus-warning)))
6823       ;; Remove bogus distribution.
6824       (when (and (stringp distribution)
6825                  (let ((case-fold-search t))
6826                    (string-match "world" distribution)))
6827         (setq distribution nil))
6828       ;; Strip list identifiers, "Re: ", and "was:"
6829       (setq subject (message-simplify-subject subject))
6830       (widen))
6831
6832     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6833
6834     (setq message-reply-headers
6835           (vector 0 subject from date message-id references 0 0 ""))
6836
6837     (message-setup
6838      `((Subject . ,subject)
6839        ,@(cond
6840           (to-newsgroups
6841            (list (cons 'Newsgroups to-newsgroups)))
6842           (follow-to follow-to)
6843           ((and followup-to message-use-followup-to)
6844            (list
6845             (cond
6846              ((equal (downcase followup-to) "poster")
6847               (if (or (eq message-use-followup-to 'use)
6848                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
6849 You should normally obey the Followup-To: header.
6850
6851 `Followup-To: poster' sends your response via e-mail instead of news.
6852
6853 A typical situation where `Followup-To: poster' is used is when the poster
6854 does not read the newsgroup, so he wouldn't see any replies sent to it.
6855
6856 You may customize the variable `message-use-followup-to', if you
6857 want to get rid of this query permanently."))
6858                   (progn
6859                     (setq message-this-is-news nil)
6860                     (cons 'To (or mrt reply-to from "")))
6861                 (cons 'Newsgroups newsgroups)))
6862              (t
6863               (if (or (equal followup-to newsgroups)
6864                       (not (eq message-use-followup-to 'ask))
6865                       (message-y-or-n-p
6866                        (concat "Obey Followup-To: " followup-to "? ") t "\
6867 You should normally obey the Followup-To: header.
6868
6869         `Followup-To: " followup-to "'
6870 directs your response to " (if (string-match "," followup-to)
6871                                "the specified newsgroups"
6872                              "that newsgroup only") ".
6873
6874 If a message is posted to several newsgroups, Followup-To is often
6875 used to direct the following discussion to one newsgroup only,
6876 because discussions that are spread over several newsgroup tend to
6877 be fragmented and very difficult to follow.
6878
6879 Also, some source/announcement newsgroups are not intended for discussion;
6880 responses here are directed to other newsgroups.
6881
6882 You may customize the variable `message-use-followup-to', if you
6883 want to get rid of this query permanently."))
6884                   (cons 'Newsgroups followup-to)
6885                 (cons 'Newsgroups newsgroups))))))
6886           (posted-to
6887            `((Newsgroups . ,posted-to)))
6888           (t
6889            `((Newsgroups . ,newsgroups))))
6890        ,@(and distribution (list (cons 'Distribution distribution)))
6891        ,@(when (and mct
6892                     (not (or (equal (downcase mct) "never")
6893                              (equal (downcase mct) "nobody"))))
6894            (list (cons 'Cc (if (or (equal (downcase mct) "always")
6895                                    (equal (downcase mct) "poster"))
6896                                (or mrt reply-to from "")
6897                              mct)))))
6898
6899      cur)))
6900
6901 (defun message-is-yours-p ()
6902   "Non-nil means current article is yours.
6903 If you have added 'cancel-messages to `message-shoot-gnksa-feet', all articles
6904 are yours except those that have Cancel-Lock header not belonging to you.
6905 Instead of shooting GNKSA feet, you should modify `message-alternative-emails'
6906 regexp to match all of yours addresses."
6907   ;; Canlock-logic as suggested by Per Abrahamsen
6908   ;; <abraham@dina.kvl.dk>
6909   ;;
6910   ;; IF article has cancel-lock THEN
6911   ;;   IF we can verify it THEN
6912   ;;     issue cancel
6913   ;;   ELSE
6914   ;;     error: cancellock: article is not yours
6915   ;; ELSE
6916   ;;   Use old rules, comparing sender...
6917   (save-excursion
6918     (save-restriction
6919       (message-narrow-to-head-1)
6920       (if (message-fetch-field "Cancel-Lock")
6921           (if (null (canlock-verify))
6922               t
6923             (error "Failed to verify Cancel-lock: This article is not yours"))
6924         (let (sender from)
6925           (or
6926            (message-gnksa-enable-p 'cancel-messages)
6927            (and (setq sender (message-fetch-field "sender"))
6928                 (string-equal (downcase sender)
6929                               (downcase (message-make-sender))))
6930            ;; Email address in From field equals to our address
6931            (and (setq from (message-fetch-field "from"))
6932                 (string-equal
6933                  (downcase (car (mail-header-parse-address from)))
6934                  (downcase (car (mail-header-parse-address
6935                                  (message-make-from))))))
6936            ;; Email address in From field matches
6937            ;; 'message-alternative-emails' regexp
6938            (and from
6939                 message-alternative-emails
6940                 (string-match
6941                  message-alternative-emails
6942                  (car (mail-header-parse-address from))))))))))
6943
6944 ;;;###autoload
6945 (defun message-cancel-news (&optional arg)
6946   "Cancel an article you posted.
6947 If ARG, allow editing of the cancellation message."
6948   (interactive "P")
6949   (unless (message-news-p)
6950     (error "This is not a news article; canceling is impossible"))
6951   (let (from newsgroups message-id distribution buf)
6952     (save-excursion
6953       ;; Get header info from original article.
6954       (save-restriction
6955         (message-narrow-to-head-1)
6956         (setq from (message-fetch-field "from")
6957               newsgroups (message-fetch-field "newsgroups")
6958               message-id (message-fetch-field "message-id" t)
6959               distribution (message-fetch-field "distribution")))
6960       ;; Make sure that this article was written by the user.
6961       (unless (message-is-yours-p)
6962         (error "This article is not yours"))
6963       (when (yes-or-no-p "Do you really want to cancel this article? ")
6964         ;; Make control message.
6965         (if arg
6966             (message-news)
6967           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6968         (erase-buffer)
6969         (insert "Newsgroups: " newsgroups "\n"
6970                 "From: " from "\n"
6971                 "Subject: cmsg cancel " message-id "\n"
6972                 "Control: cancel " message-id "\n"
6973                 (if distribution
6974                     (concat "Distribution: " distribution "\n")
6975                   "")
6976                 mail-header-separator "\n"
6977                 message-cancel-message)
6978         (run-hooks 'message-cancel-hook)
6979         (unless arg
6980           (message "Canceling your article...")
6981           (if (let ((message-syntax-checks
6982                      'dont-check-for-anything-just-trust-me))
6983                 (funcall message-send-news-function))
6984               (message "Canceling your article...done"))
6985           (kill-buffer buf))))))
6986
6987 ;;;###autoload
6988 (defun message-supersede ()
6989   "Start composing a message to supersede the current message.
6990 This is done simply by taking the old article and adding a Supersedes
6991 header line with the old Message-ID."
6992   (interactive)
6993   (let ((cur (current-buffer)))
6994     ;; Check whether the user owns the article that is to be superseded.
6995     (unless (message-is-yours-p)
6996       (error "This article is not yours"))
6997     ;; Get a normal message buffer.
6998     (message-pop-to-buffer (message-buffer-name "supersede"))
6999     (insert-buffer-substring cur)
7000     (mime-to-mml)
7001     (message-narrow-to-head-1)
7002     ;; Remove unwanted headers.
7003     (when message-ignored-supersedes-headers
7004       (message-remove-header message-ignored-supersedes-headers t))
7005     (goto-char (point-min))
7006     (if (not (re-search-forward "^Message-ID: " nil t))
7007         (error "No Message-ID in this article")
7008       (replace-match "Supersedes: " t t))
7009     (goto-char (point-max))
7010     (insert mail-header-separator)
7011     (widen)
7012     (forward-line 1)))
7013
7014 ;;;###autoload
7015 (defun message-recover ()
7016   "Reread contents of current buffer from its last auto-save file."
7017   (interactive)
7018   (let ((file-name (make-auto-save-file-name)))
7019     (cond ((save-window-excursion
7020              (with-output-to-temp-buffer "*Directory*"
7021                (with-current-buffer standard-output
7022                  (fundamental-mode))    ; for Emacs 20.4+
7023                (buffer-disable-undo standard-output)
7024                (let ((default-directory "/"))
7025                  (call-process
7026                   "ls" nil standard-output nil "-l" file-name)))
7027              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
7028            (let ((buffer-read-only nil))
7029              (erase-buffer)
7030              (insert-file-contents file-name nil)))
7031           (t (error "message-recover cancelled")))))
7032
7033 ;;; Washing Subject:
7034
7035 (defun message-wash-subject (subject)
7036   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
7037 Previous forwarders, replyers, etc. may add it."
7038   (with-temp-buffer
7039     (insert subject)
7040     (goto-char (point-min))
7041     ;; strip Re/Fwd stuff off the beginning
7042     (while (re-search-forward
7043             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
7044       (replace-match ""))
7045
7046     ;; and gnus-style forwards [foo@bar.com] subject
7047     (goto-char (point-min))
7048     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
7049       (replace-match ""))
7050
7051     ;; and off the end
7052     (goto-char (point-max))
7053     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
7054       (replace-match ""))
7055
7056     ;; and finally, any whitespace that was left-over
7057     (goto-char (point-min))
7058     (while (re-search-forward "^[ \t]+" nil t)
7059       (replace-match ""))
7060     (goto-char (point-max))
7061     (while (re-search-backward "[ \t]+$" nil t)
7062       (replace-match ""))
7063
7064     (buffer-string)))
7065
7066 ;;; Forwarding messages.
7067
7068 (defvar message-forward-decoded-p nil
7069   "Non-nil means the original message is decoded.")
7070
7071 (defun message-forward-subject-name-subject (subject)
7072   "Generate a SUBJECT for a forwarded message.
7073 The form is: [Source] Subject, where if the original message was mail,
7074 Source is the name of the sender, and if the original message was
7075 news, Source is the list of newsgroups is was posted to."
7076   (let* ((group (message-fetch-field "newsgroups"))
7077          (from (message-fetch-field "from"))
7078          (prefix
7079           (if group
7080               (gnus-group-decoded-name group)
7081             (or (and from (or
7082                            (car (gnus-extract-address-components from))
7083                            (cadr (gnus-extract-address-components from))))
7084                 "(nowhere)"))))
7085     (concat "["
7086             (if message-forward-decoded-p
7087                 prefix
7088               (mail-decode-encoded-word-string prefix))
7089             "] " subject)))
7090
7091 (defun message-forward-subject-author-subject (subject)
7092   "Generate a SUBJECT for a forwarded message.
7093 The form is: [Source] Subject, where if the original message was mail,
7094 Source is the sender, and if the original message was news, Source is
7095 the list of newsgroups is was posted to."
7096   (let* ((group (message-fetch-field "newsgroups"))
7097          (prefix
7098           (if group
7099               (gnus-group-decoded-name group)
7100             (or (message-fetch-field "from")
7101                 "(nowhere)"))))
7102     (concat "["
7103             (if message-forward-decoded-p
7104                 prefix
7105               (mail-decode-encoded-word-string prefix))
7106             "] " subject)))
7107
7108 (defun message-forward-subject-fwd (subject)
7109   "Generate a SUBJECT for a forwarded message.
7110 The form is: Fwd: Subject, where Subject is the original subject of
7111 the message."
7112   (if (string-match "^Fwd: " subject)
7113       subject
7114     (concat "Fwd: " subject)))
7115
7116 (defun message-make-forward-subject ()
7117   "Return a Subject header suitable for the message in the current buffer."
7118   (save-excursion
7119     (save-restriction
7120       (message-narrow-to-head-1)
7121       (let ((funcs message-make-forward-subject-function)
7122             (subject (message-fetch-field "Subject")))
7123         (setq subject
7124               (if subject
7125                   (if message-forward-decoded-p
7126                       subject
7127                     (mail-decode-encoded-word-string subject))
7128                 ""))
7129         (when message-wash-forwarded-subjects
7130           (setq subject (message-wash-subject subject)))
7131         ;; Make sure funcs is a list.
7132         (and funcs
7133              (not (listp funcs))
7134              (setq funcs (list funcs)))
7135         ;; Apply funcs in order, passing subject generated by previous
7136         ;; func to the next one.
7137         (dolist (func funcs)
7138           (when (functionp func)
7139             (setq subject (funcall func subject))))
7140         subject))))
7141
7142 (defvar gnus-article-decoded-p)
7143
7144
7145 ;;;###autoload
7146 (defun message-forward (&optional news digest)
7147   "Forward the current message via mail.
7148 Optional NEWS will use news to forward instead of mail.
7149 Optional DIGEST will use digest to forward."
7150   (interactive "P")
7151   (let* ((cur (current-buffer))
7152          (message-forward-decoded-p
7153           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
7154               gnus-article-decoded-p ;; In an article buffer.
7155             message-forward-decoded-p))
7156          (subject (message-make-forward-subject)))
7157     (if news
7158         (message-news nil subject)
7159       (message-mail nil subject))
7160     (message-forward-make-body cur digest)))
7161
7162 (defun message-forward-make-body-plain (forward-buffer)
7163   (insert
7164    "\n-------------------- Start of forwarded message --------------------\n")
7165   (let ((b (point))
7166         (contents (with-current-buffer forward-buffer (buffer-string)))
7167         e)
7168     (unless (featurep 'xemacs)
7169       (unless (mm-multibyte-string-p contents)
7170         (error "Attempt to insert unibyte string from the buffer \"%s\"\
7171  to the multibyte buffer \"%s\""
7172                (if (bufferp forward-buffer)
7173                    (buffer-name forward-buffer)
7174                  forward-buffer)
7175                (buffer-name))))
7176     (insert (mm-with-multibyte-buffer
7177               (insert contents)
7178               (mime-to-mml)
7179               (goto-char (point-min))
7180               (when (looking-at "From ")
7181                 (replace-match "X-From-Line: "))
7182               (buffer-string)))
7183     (unless (bolp) (insert "\n"))
7184     (setq e (point))
7185     (insert
7186      "-------------------- End of forwarded message --------------------\n")
7187     (message-remove-ignored-headers b e)))
7188
7189 (defun message-remove-ignored-headers (b e)
7190   (when message-forward-ignored-headers
7191     (save-restriction
7192       (narrow-to-region b e)
7193       (goto-char b)
7194       (narrow-to-region (point)
7195                         (or (search-forward "\n\n" nil t) (point)))
7196       (let ((ignored (if (stringp message-forward-ignored-headers)
7197                          (list message-forward-ignored-headers)
7198                        message-forward-ignored-headers)))
7199         (dolist (elem ignored)
7200           (message-remove-header elem t))))))
7201
7202 (defun message-forward-make-body-mime (forward-buffer)
7203   (let ((b (point)))
7204     (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
7205     (save-restriction
7206       (narrow-to-region (point) (point))
7207       (mml-insert-buffer forward-buffer)
7208       (goto-char (point-min))
7209       (when (looking-at "From ")
7210         (replace-match "X-From-Line: "))
7211       (goto-char (point-max)))
7212     (insert "<#/part>\n")
7213     ;; Consider there is no illegible text.
7214     (add-text-properties
7215      b (point)
7216      `(no-illegible-text t rear-nonsticky t start-open t))))
7217
7218 (defun message-forward-make-body-mml (forward-buffer)
7219   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
7220   (let ((b (point)) e)
7221     (if (not message-forward-decoded-p)
7222         (let ((contents (with-current-buffer forward-buffer (buffer-string))))
7223           (unless (featurep 'xemacs)
7224             (unless (mm-multibyte-string-p contents)
7225               (error "Attempt to insert unibyte string from the buffer \"%s\"\
7226  to the multibyte buffer \"%s\""
7227                      (if (bufferp forward-buffer)
7228                          (buffer-name forward-buffer)
7229                        forward-buffer)
7230                      (buffer-name))))
7231           (insert (mm-with-multibyte-buffer
7232                     (insert contents)
7233                     (mime-to-mml)
7234                     (goto-char (point-min))
7235                     (when (looking-at "From ")
7236                       (replace-match "X-From-Line: "))
7237                     (buffer-string))))
7238       (save-restriction
7239         (narrow-to-region (point) (point))
7240         (mml-insert-buffer forward-buffer)
7241         (goto-char (point-min))
7242         (when (looking-at "From ")
7243           (replace-match "X-From-Line: "))
7244         (goto-char (point-max))))
7245     (setq e (point))
7246     (insert "<#/mml>\n")
7247     (when (and (not message-forward-decoded-p)
7248                message-forward-ignored-headers)
7249       (message-remove-ignored-headers b e))))
7250
7251 (defun message-forward-make-body-digest-plain (forward-buffer)
7252   (insert
7253    "\n-------------------- Start of forwarded message --------------------\n")
7254   (let ((b (point)) e)
7255     (mml-insert-buffer forward-buffer)
7256     (setq e (point))
7257     (insert
7258      "\n-------------------- End of forwarded message --------------------\n")))
7259
7260 (defun message-forward-make-body-digest-mime (forward-buffer)
7261   (insert "\n<#multipart type=digest>\n")
7262   (let ((b (point)) e)
7263     (insert-buffer-substring forward-buffer)
7264     (setq e (point))
7265     (insert "<#/multipart>\n")
7266     (save-restriction
7267       (narrow-to-region b e)
7268       (goto-char b)
7269       (narrow-to-region (point)
7270                         (or (search-forward "\n\n" nil t) (point)))
7271       (delete-region (point-min) (point-max)))))
7272
7273 (defun message-forward-make-body-digest (forward-buffer)
7274   (if message-forward-as-mime
7275       (message-forward-make-body-digest-mime forward-buffer)
7276     (message-forward-make-body-digest-plain forward-buffer)))
7277
7278 (autoload 'mm-uu-dissect-text-parts "mm-uu")
7279 (autoload 'mm-uu-dissect "mm-uu")
7280
7281 (defun message-signed-or-encrypted-p (&optional dont-emulate-mime handles)
7282   "Say whether the current buffer contains signed or encrypted message.
7283 If DONT-EMULATE-MIME is nil, this function does the MIME emulation on
7284 messages that don't conform to PGP/MIME described in RFC2015.  HANDLES
7285 is for the internal use."
7286   (unless handles
7287     (let ((mm-decrypt-option 'never)
7288           (mm-verify-option 'never))
7289       (if (setq handles (mm-dissect-buffer nil t))
7290           (unless dont-emulate-mime
7291             (mm-uu-dissect-text-parts handles))
7292         (unless dont-emulate-mime
7293           (setq handles (mm-uu-dissect))))))
7294   ;; Check text/plain message in which there is a signed or encrypted
7295   ;; body that has been encoded by B or Q.
7296   (unless (or handles dont-emulate-mime)
7297     (let ((cur (current-buffer))
7298           (mm-decrypt-option 'never)
7299           (mm-verify-option 'never))
7300       (with-temp-buffer
7301         (insert-buffer-substring cur)
7302         (when (setq handles (mm-dissect-buffer t t))
7303           (if (and (prog1
7304                        (bufferp (car handles))
7305                      (mm-destroy-parts handles))
7306                    (equal (mm-handle-media-type handles) "text/plain"))
7307               (progn
7308                 (mm-decode-content-transfer-encoding
7309                  (mm-handle-encoding handles))
7310                 (setq handles (mm-uu-dissect)))
7311             (setq handles nil))))))
7312   (when handles
7313     (prog1
7314         (catch 'found
7315           (dolist (handle (if (stringp (car handles))
7316                               (if (member (car handles)
7317                                           '("multipart/signed"
7318                                             "multipart/encrypted"))
7319                                   (throw 'found t)
7320                                 (cdr handles))
7321                             (list handles)))
7322             (if (stringp (car handle))
7323                 (when (message-signed-or-encrypted-p dont-emulate-mime handle)
7324                   (throw 'found t))
7325               (when (and (bufferp (car handle))
7326                          (equal (mm-handle-media-type handle)
7327                                 "message/rfc822"))
7328                 (with-current-buffer (mm-handle-buffer handle)
7329                   (when (message-signed-or-encrypted-p dont-emulate-mime)
7330                     (throw 'found t)))))))
7331       (mm-destroy-parts handles))))
7332
7333 ;;;###autoload
7334 (defun message-forward-make-body (forward-buffer &optional digest)
7335   ;; Put point where we want it before inserting the forwarded
7336   ;; message.
7337   (if message-forward-before-signature
7338       (message-goto-body)
7339     (goto-char (point-max)))
7340   (if digest
7341       (message-forward-make-body-digest forward-buffer)
7342     (if message-forward-as-mime
7343         (if (and message-forward-show-mml
7344                  (not (and (eq message-forward-show-mml 'best)
7345                            ;; Use the raw form in the body if it contains
7346                            ;; signed or encrypted message so as not to be
7347                            ;; destroyed by re-encoding.
7348                            (with-current-buffer forward-buffer
7349                              (condition-case nil
7350                                  (message-signed-or-encrypted-p)
7351                                (error t))))))
7352             (message-forward-make-body-mml forward-buffer)
7353           (message-forward-make-body-mime forward-buffer))
7354       (message-forward-make-body-plain forward-buffer)))
7355   (message-position-point))
7356
7357 (declare-function rmail-toggle-header "rmail" (&optional arg))
7358
7359 ;;;###autoload
7360 (defun message-forward-rmail-make-body (forward-buffer)
7361   (save-window-excursion
7362     (set-buffer forward-buffer)
7363     (if (rmail-msg-is-pruned)
7364         (if (fboundp 'rmail-msg-restore-non-pruned-header)
7365             (rmail-msg-restore-non-pruned-header) ; Emacs 22
7366           (rmail-toggle-header 0))))              ; Emacs 23
7367   (message-forward-make-body forward-buffer))
7368
7369 ;; Fixme: Should have defcustom.
7370 ;;;###autoload
7371 (defun message-insinuate-rmail ()
7372   "Let RMAIL use message to forward."
7373   (interactive)
7374   (setq rmail-enable-mime-composing t)
7375   (setq rmail-insert-mime-forwarded-message-function
7376         'message-forward-rmail-make-body))
7377
7378 ;;;###autoload
7379 (defun message-resend (address)
7380   "Resend the current article to ADDRESS."
7381   (interactive
7382    (list (message-read-from-minibuffer "Resend message to: ")))
7383   (message "Resending message to %s..." address)
7384   (save-excursion
7385     (let ((cur (current-buffer))
7386           beg)
7387       ;; We first set up a normal mail buffer.
7388       (unless (message-mail-user-agent)
7389         (set-buffer (get-buffer-create " *message resend*"))
7390         (erase-buffer))
7391       (let ((message-this-is-mail t)
7392             message-generate-hashcash
7393             message-setup-hook)
7394         (message-setup `((To . ,address))))
7395       ;; Insert our usual headers.
7396       (message-generate-headers '(From Date To Message-ID))
7397       (message-narrow-to-headers)
7398       ;; Remove X-Draft-From header etc.
7399       (message-remove-header message-ignored-mail-headers t)
7400       ;; Rename them all to "Resent-*".
7401       (goto-char (point-min))
7402       (while (re-search-forward "^[A-Za-z]" nil t)
7403         (forward-char -1)
7404         (insert "Resent-"))
7405       (widen)
7406       (forward-line)
7407       (delete-region (point) (point-max))
7408       (setq beg (point))
7409       ;; Insert the message to be resent.
7410       (insert-buffer-substring cur)
7411       (goto-char (point-min))
7412       (search-forward "\n\n")
7413       (forward-char -1)
7414       (save-restriction
7415         (narrow-to-region beg (point))
7416         (message-remove-header message-ignored-resent-headers t)
7417         (goto-char (point-max)))
7418       (insert mail-header-separator)
7419       ;; Rename all old ("Also-")Resent headers.
7420       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
7421         (beginning-of-line)
7422         (insert "Also-"))
7423       ;; Quote any "From " lines at the beginning.
7424       (goto-char beg)
7425       (when (looking-at "From ")
7426         (replace-match "X-From-Line: "))
7427       ;; Send it.
7428       (let ((message-inhibit-body-encoding t)
7429             (message-inhibit-ecomplete t)
7430             message-required-mail-headers
7431             message-generate-hashcash
7432             rfc2047-encode-encoded-words)
7433         (message-send-mail))
7434       (kill-buffer (current-buffer)))
7435     (message "Resending message to %s...done" address)))
7436
7437 ;;;###autoload
7438 (defun message-bounce ()
7439   "Re-mail the current message.
7440 This only makes sense if the current message is a bounce message that
7441 contains some mail you have written which has been bounced back to
7442 you."
7443   (interactive)
7444   (let ((handles (mm-dissect-buffer t))
7445         boundary)
7446     (message-pop-to-buffer (message-buffer-name "bounce"))
7447     (if (stringp (car handles))
7448         ;; This is a MIME bounce.
7449         (mm-insert-part (car (last handles)))
7450       ;; This is a non-MIME bounce, so we try to remove things
7451       ;; manually.
7452       (mm-insert-part handles)
7453       (undo-boundary)
7454       (goto-char (point-min))
7455       (re-search-forward "\n\n+" nil t)
7456       (setq boundary (point))
7457       ;; We remove everything before the bounced mail.
7458       (if (or (re-search-forward message-unsent-separator nil t)
7459               (progn
7460                 (search-forward "\n\n" nil 'move)
7461                 (re-search-backward "^Return-Path:.*\n" boundary t)))
7462           (progn
7463             (forward-line 1)
7464             (delete-region (point-min)
7465                            (if (re-search-forward "^[^ \n\t]+:" nil t)
7466                                (match-beginning 0)
7467                              (point))))
7468         (goto-char boundary)
7469         (when (re-search-backward "^.?From .*\n" nil t)
7470           (delete-region (match-beginning 0) (match-end 0)))))
7471     (mime-to-mml)
7472     (save-restriction
7473       (message-narrow-to-head-1)
7474       (message-remove-header message-ignored-bounced-headers t)
7475       (goto-char (point-max))
7476       (insert mail-header-separator))
7477     (message-position-point)))
7478
7479 ;;;
7480 ;;; Interactive entry points for new message buffers.
7481 ;;;
7482
7483 ;;;###autoload
7484 (defun message-mail-other-window (&optional to subject)
7485   "Like `message-mail' command, but display mail buffer in another window."
7486   (interactive)
7487   (unless (message-mail-user-agent)
7488     (let ((pop-up-windows t)
7489           (special-display-buffer-names nil)
7490           (special-display-regexps nil)
7491           (same-window-buffer-names nil)
7492           (same-window-regexps nil))
7493       (message-pop-to-buffer (message-buffer-name "mail" to))))
7494   (let ((message-this-is-mail t))
7495     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7496                    nil nil nil 'switch-to-buffer-other-window)))
7497
7498 ;;;###autoload
7499 (defun message-mail-other-frame (&optional to subject)
7500   "Like `message-mail' command, but display mail buffer in another frame."
7501   (interactive)
7502   (unless (message-mail-user-agent)
7503     (let ((pop-up-frames t)
7504           (special-display-buffer-names nil)
7505           (special-display-regexps nil)
7506           (same-window-buffer-names nil)
7507           (same-window-regexps nil))
7508       (message-pop-to-buffer (message-buffer-name "mail" to))))
7509   (let ((message-this-is-mail t))
7510     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7511                    nil nil nil 'switch-to-buffer-other-frame)))
7512
7513 ;;;###autoload
7514 (defun message-news-other-window (&optional newsgroups subject)
7515   "Start editing a news article to be sent."
7516   (interactive)
7517   (let ((pop-up-windows t)
7518         (special-display-buffer-names nil)
7519         (special-display-regexps nil)
7520         (same-window-buffer-names nil)
7521         (same-window-regexps nil))
7522     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7523   (let ((message-this-is-news t))
7524     (message-setup `((Newsgroups . ,(or newsgroups ""))
7525                      (Subject . ,(or subject ""))))))
7526
7527 ;;;###autoload
7528 (defun message-news-other-frame (&optional newsgroups subject)
7529   "Start editing a news article to be sent."
7530   (interactive)
7531   (let ((pop-up-frames t)
7532         (special-display-buffer-names nil)
7533         (special-display-regexps nil)
7534         (same-window-buffer-names nil)
7535         (same-window-regexps nil))
7536     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7537   (let ((message-this-is-news t))
7538     (message-setup `((Newsgroups . ,(or newsgroups ""))
7539                      (Subject . ,(or subject ""))))))
7540
7541 ;;; underline.el
7542
7543 ;; This code should be moved to underline.el (from which it is stolen).
7544
7545 ;;;###autoload
7546 (defun message-bold-region (start end)
7547   "Bold all nonblank characters in the region.
7548 Works by overstriking characters.
7549 Called from program, takes two arguments START and END
7550 which specify the range to operate on."
7551   (interactive "r")
7552   (save-excursion
7553     (let ((end1 (make-marker)))
7554       (move-marker end1 (max start end))
7555       (goto-char (min start end))
7556       (while (< (point) end1)
7557         (or (looking-at "[_\^@- ]")
7558             (insert (char-after) "\b"))
7559         (forward-char 1)))))
7560
7561 ;;;###autoload
7562 (defun message-unbold-region (start end)
7563   "Remove all boldness (overstruck characters) in the region.
7564 Called from program, takes two arguments START and END
7565 which specify the range to operate on."
7566   (interactive "r")
7567   (save-excursion
7568     (let ((end1 (make-marker)))
7569       (move-marker end1 (max start end))
7570       (goto-char (min start end))
7571       (while (search-forward "\b" end1 t)
7572         (if (eq (char-after) (char-after (- (point) 2)))
7573             (delete-char -2))))))
7574
7575 (defun message-exchange-point-and-mark ()
7576   "Exchange point and mark, but don't activate region if it was inactive."
7577   (goto-char (prog1 (mark t)
7578                (set-marker (mark-marker) (point)))))
7579
7580 (defalias 'message-make-overlay 'make-overlay)
7581 (defalias 'message-delete-overlay 'delete-overlay)
7582 (defalias 'message-overlay-put 'overlay-put)
7583 (defun message-kill-all-overlays ()
7584   (if (featurep 'xemacs)
7585       (map-extents (lambda (extent ignore) (delete-extent extent)))
7586     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7587
7588 ;; Support for toolbar
7589 (defvar tool-bar-mode)
7590
7591 ;; Note: The :set function in the `message-tool-bar*' variables will only
7592 ;; affect _new_ message buffers.  We might add a function that walks thru all
7593 ;; message-mode buffers and force the update.
7594 (defun message-tool-bar-update (&optional symbol value)
7595   "Update message mode toolbar.
7596 Setter function for custom variables."
7597   (setq-default message-tool-bar-map nil)
7598   (when symbol
7599     ;; When used as ":set" function:
7600     (set-default symbol value)))
7601
7602 (defcustom message-tool-bar (if (eq gmm-tool-bar-style 'gnome)
7603                                 'message-tool-bar-gnome
7604                               'message-tool-bar-retro)
7605   "Specifies the message mode tool bar.
7606
7607 It can be either a list or a symbol refering to a list.  See
7608 `gmm-tool-bar-from-list' for the format of the list.  The
7609 default key map is `message-mode-map'.
7610
7611 Pre-defined symbols include `message-tool-bar-gnome' and
7612 `message-tool-bar-retro'."
7613   :type '(repeat gmm-tool-bar-list-item)
7614   :type '(choice (const :tag "GNOME style" message-tool-bar-gnome)
7615                  (const :tag "Retro look"  message-tool-bar-retro)
7616                  (repeat :tag "User defined list" gmm-tool-bar-item)
7617                  (symbol))
7618   :version "23.1" ;; No Gnus
7619   :initialize 'custom-initialize-default
7620   :set 'message-tool-bar-update
7621   :group 'message)
7622
7623 (defcustom message-tool-bar-gnome
7624   '((ispell-message "spell" nil
7625                     :visible (or (not (boundp 'flyspell-mode))
7626                                  (not flyspell-mode)))
7627     (flyspell-buffer "spell" t
7628                      :visible (and (boundp 'flyspell-mode)
7629                                    flyspell-mode)
7630                      :help "Flyspell whole buffer")
7631     (gmm-ignore "separator")
7632     (message-send-and-exit "mail/send")
7633     (message-dont-send "mail/save-draft")
7634     (message-kill-buffer "close") ;; stock_cancel
7635     (mml-attach-file "attach" mml-mode-map)
7636     (mml-preview "mail/preview" mml-mode-map)
7637     (mml-secure-message-sign-encrypt "lock" mml-mode-map :visible nil)
7638     (message-insert-importance-high "important" nil :visible nil)
7639     (message-insert-importance-low "unimportant" nil :visible nil)
7640     (message-insert-disposition-notification-to "receipt" nil :visible nil)
7641     (gmm-customize-mode "preferences" t :help "Edit mode preferences")
7642     (message-info "help" t :help "Message manual"))
7643   "List of items for the message tool bar (GNOME style).
7644
7645 See `gmm-tool-bar-from-list' for details on the format of the list."
7646   :type '(repeat gmm-tool-bar-item)
7647   :version "23.1" ;; No Gnus
7648   :initialize 'custom-initialize-default
7649   :set 'message-tool-bar-update
7650   :group 'message)
7651
7652 (defcustom message-tool-bar-retro
7653   '(;; Old Emacs 21 icon for consistency.
7654     (message-send-and-exit "gnus/mail-send")
7655     (message-kill-buffer "close")
7656     (message-dont-send "cancel")
7657     (mml-attach-file "attach" mml-mode-map)
7658     (ispell-message "spell")
7659     (mml-preview "preview" mml-mode-map)
7660     (message-insert-importance-high "gnus/important")
7661     (message-insert-importance-low "gnus/unimportant")
7662     (message-insert-disposition-notification-to "gnus/receipt"))
7663   "List of items for the message tool bar (retro style).
7664
7665 See `gmm-tool-bar-from-list' for details on the format of the list."
7666   :type '(repeat gmm-tool-bar-item)
7667   :version "23.1" ;; No Gnus
7668   :initialize 'custom-initialize-default
7669   :set 'message-tool-bar-update
7670   :group 'message)
7671
7672 (defcustom message-tool-bar-zap-list
7673   '(new-file open-file dired kill-buffer write-file
7674              print-buffer customize help)
7675   "List of icon items from the global tool bar.
7676 These items are not displayed on the message mode tool bar.
7677
7678 See `gmm-tool-bar-from-list' for the format of the list."
7679   :type 'gmm-tool-bar-zap-list
7680   :version "23.1" ;; No Gnus
7681   :initialize 'custom-initialize-default
7682   :set 'message-tool-bar-update
7683   :group 'message)
7684
7685 (defvar image-load-path)
7686
7687 (defun message-make-tool-bar (&optional force)
7688   "Make a message mode tool bar from `message-tool-bar-list'.
7689 When FORCE, rebuild the tool bar."
7690   (when (and (not (featurep 'xemacs))
7691              (boundp 'tool-bar-mode)
7692              tool-bar-mode
7693              (or (not message-tool-bar-map) force))
7694     (setq message-tool-bar-map
7695           (let* ((load-path
7696                   (gmm-image-load-path-for-library "message"
7697                                                    "mail/save-draft.xpm"
7698                                                    nil t))
7699                  (image-load-path (cons (car load-path)
7700                                         (when (boundp 'image-load-path)
7701                                           image-load-path))))
7702             (gmm-tool-bar-from-list message-tool-bar
7703                                     message-tool-bar-zap-list
7704                                     'message-mode-map))))
7705   message-tool-bar-map)
7706
7707 ;;; Group name completion.
7708
7709 (defcustom message-newgroups-header-regexp
7710   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7711   "Regexp that match headers that lists groups."
7712   :group 'message
7713   :type 'regexp)
7714
7715 (defcustom message-completion-alist
7716   (list (cons message-newgroups-header-regexp 'message-expand-group)
7717         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7718         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7719           . message-expand-name)
7720         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7721           . message-expand-name))
7722   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7723   :version "22.1"
7724   :group 'message
7725   :type '(alist :key-type regexp :value-type function))
7726
7727 (defcustom message-expand-name-databases
7728   (list 'bbdb 'eudc)
7729   "List of databases to try for name completion (`message-expand-name').
7730 Each element is a symbol and can be `bbdb' or `eudc'."
7731   :group 'message
7732   :type '(set (const bbdb) (const eudc)))
7733
7734 (defcustom message-tab-body-function nil
7735   "*Function to execute when `message-tab' (TAB) is executed in the body.
7736 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7737   :version "22.1"
7738   :group 'message
7739   :link '(custom-manual "(message)Various Commands")
7740   :type '(choice (const nil)
7741                  function))
7742
7743 (declare-function mail-abbrev-in-expansion-header-p "mailabbrev" ())
7744
7745 (defun message-tab ()
7746   "Complete names according to `message-completion-alist'.
7747 Execute function specified by `message-tab-body-function' when not in
7748 those headers."
7749   (interactive)
7750   (let ((alist message-completion-alist))
7751     (while (and alist
7752                 (let ((mail-abbrev-mode-regexp (caar alist)))
7753                   (not (mail-abbrev-in-expansion-header-p))))
7754       (setq alist (cdr alist)))
7755     (funcall (or (cdar alist) message-tab-body-function
7756                  (lookup-key text-mode-map "\t")
7757                  (lookup-key global-map "\t")
7758                  'indent-relative))))
7759
7760 (eval-and-compile
7761   (condition-case nil
7762       (with-temp-buffer
7763         (let ((standard-output (current-buffer)))
7764           (eval '(display-completion-list nil "")))
7765         (defalias 'message-display-completion-list 'display-completion-list))
7766     (error ;; Don't use `wrong-number-of-arguments' here because of XEmacs.
7767      (defun message-display-completion-list (completions &optional ignore)
7768        "Display the list of completions, COMPLETIONS, using `standard-output'."
7769        (display-completion-list completions)))))
7770
7771 (defun message-expand-group ()
7772   "Expand the group name under point."
7773   (let* ((b (save-excursion
7774               (save-restriction
7775                 (narrow-to-region
7776                  (save-excursion
7777                    (beginning-of-line)
7778                    (skip-chars-forward "^:")
7779                    (1+ (point)))
7780                  (point))
7781                 (skip-chars-backward "^, \t\n") (point))))
7782          (completion-ignore-case t)
7783          (e (progn (skip-chars-forward "^,\t\n ") (point)))
7784          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb)))
7785     (message-completion-in-region e b hashtb)))
7786
7787 (defalias 'message-completion-in-region
7788   (if (fboundp 'completion-in-region)
7789       'completion-in-region
7790     (lambda (e b hashtb)
7791       (let* ((string (buffer-substring b e))
7792              (completions (all-completions string hashtb))
7793              comp)
7794         (delete-region b (point))
7795         (cond
7796          ((= (length completions) 1)
7797           (if (string= (car completions) string)
7798               (progn
7799                 (insert string)
7800                 (message "Only matching group"))
7801             (insert (car completions))))
7802          ((and (setq comp (try-completion string hashtb))
7803                (not (string= comp string)))
7804           (insert comp))
7805          (t
7806           (insert string)
7807           (if (not comp)
7808               (message "No matching groups")
7809             (save-selected-window
7810               (pop-to-buffer "*Completions*")
7811               (buffer-disable-undo)
7812               (let ((buffer-read-only nil))
7813                 (erase-buffer)
7814                 (let ((standard-output (current-buffer)))
7815                   (message-display-completion-list (sort completions 'string<)
7816                                                    string))
7817                 (setq buffer-read-only nil)
7818                 (goto-char (point-min))
7819                 (delete-region (point)
7820                                (progn (forward-line 3) (point))))))))))))
7821
7822 (defun message-expand-name ()
7823   (cond ((and (memq 'eudc message-expand-name-databases)
7824                     (boundp 'eudc-protocol)
7825                     eudc-protocol)
7826          (eudc-expand-inline))
7827         ((and (memq 'bbdb message-expand-name-databases)
7828               (fboundp 'bbdb-complete-name))
7829          (bbdb-complete-name))
7830         (t
7831          (expand-abbrev))))
7832
7833 ;;; Help stuff.
7834
7835 (defun message-talkative-question (ask question show &rest text)
7836   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7837 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7838 The following arguments may contain lists of values."
7839   (if (and show
7840            (setq text (message-flatten-list text)))
7841       (save-window-excursion
7842         (with-output-to-temp-buffer " *MESSAGE information message*"
7843           (with-current-buffer " *MESSAGE information message*"
7844             (fundamental-mode)          ; for Emacs 20.4+
7845             (mapc 'princ text)
7846             (goto-char (point-min))))
7847         (funcall ask question))
7848     (funcall ask question)))
7849
7850 (defun message-flatten-list (list)
7851   "Return a new, flat list that contains all elements of LIST.
7852
7853 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7854 => (1 2 3 4 5 6 7)"
7855   (cond ((consp list)
7856          (apply 'append (mapcar 'message-flatten-list list)))
7857         (list
7858          (list list))))
7859
7860 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7861   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7862 Then clone the local variables and values from the old buffer to the
7863 new one, cloning only the locals having a substring matching the
7864 regexp VARSTR."
7865   (let ((oldbuf (current-buffer)))
7866     (with-current-buffer (generate-new-buffer name)
7867       (message-clone-locals oldbuf varstr)
7868       (current-buffer))))
7869
7870 (defun message-clone-locals (buffer &optional varstr)
7871   "Clone the local variables from BUFFER to the current buffer."
7872   (let ((locals (with-current-buffer buffer (buffer-local-variables)))
7873         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address"))
7874     (mapcar
7875      (lambda (local)
7876        (when (and (consp local)
7877                   (car local)
7878                   (string-match regexp (symbol-name (car local)))
7879                   (or (null varstr)
7880                       (string-match varstr (symbol-name (car local)))))
7881          (ignore-errors
7882            (set (make-local-variable (car local))
7883                 (cdr local)))))
7884      locals)))
7885
7886 ;;;
7887 ;;; MIME functions
7888 ;;;
7889
7890 (defvar message-inhibit-body-encoding nil)
7891
7892 (defun message-encode-message-body ()
7893   (unless message-inhibit-body-encoding
7894     (let ((mail-parse-charset (or mail-parse-charset
7895                                   message-default-charset))
7896           (case-fold-search t)
7897           lines content-type-p)
7898       (message-goto-body)
7899       (save-restriction
7900         (narrow-to-region (point) (point-max))
7901         (let ((new (mml-generate-mime)))
7902           (when new
7903             (delete-region (point-min) (point-max))
7904             (insert new)
7905             (goto-char (point-min))
7906             (if (eq (aref new 0) ?\n)
7907                 (delete-char 1)
7908               (search-forward "\n\n")
7909               (setq lines (buffer-substring (point-min) (1- (point))))
7910               (delete-region (point-min) (point))))))
7911       (save-restriction
7912         (message-narrow-to-headers-or-head)
7913         (message-remove-header "Mime-Version")
7914         (goto-char (point-max))
7915         (insert "MIME-Version: 1.0\n")
7916         (when lines
7917           (insert lines))
7918         (setq content-type-p
7919               (or mml-boundary
7920                   (re-search-backward "^Content-Type:" nil t))))
7921       (save-restriction
7922         (message-narrow-to-headers-or-head)
7923         (message-remove-first-header "Content-Type")
7924         (message-remove-first-header "Content-Transfer-Encoding"))
7925       ;; We always make sure that the message has a Content-Type
7926       ;; header.  This is because some broken MTAs and MUAs get
7927       ;; awfully confused when confronted with a message with a
7928       ;; MIME-Version header and without a Content-Type header.  For
7929       ;; instance, Solaris' /usr/bin/mail.
7930       (unless content-type-p
7931         (goto-char (point-min))
7932         ;; For unknown reason, MIME-Version doesn't exist.
7933         (when (re-search-forward "^MIME-Version:" nil t)
7934           (forward-line 1)
7935           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7936
7937 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7938   "Read from the minibuffer while providing abbrev expansion."
7939   (if (fboundp 'mail-abbrevs-setup)
7940       (let ((mail-abbrev-mode-regexp "")
7941             (minibuffer-setup-hook 'mail-abbrevs-setup)
7942             (minibuffer-local-map message-minibuffer-local-map))
7943         (read-from-minibuffer prompt initial-contents))
7944     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7945           (minibuffer-local-map message-minibuffer-local-map))
7946       (read-string prompt initial-contents))))
7947
7948 (defun message-use-alternative-email-as-from ()
7949   "Set From field of the outgoing message to the first matching
7950 address in `message-alternative-emails', looking at To, Cc and
7951 From headers in the original article."
7952   (require 'mail-utils)
7953   (let* ((fields '("To" "Cc" "From"))
7954          (emails
7955           (split-string
7956            (mail-strip-quoted-names
7957             (mapconcat 'message-fetch-reply-field fields ","))
7958            "[ \f\t\n\r\v,]+"))
7959          email)
7960     (while emails
7961       (if (string-match message-alternative-emails (car emails))
7962           (setq email (car emails)
7963                 emails nil))
7964       (pop emails))
7965     (unless (or (not email) (equal email user-mail-address))
7966       (message-remove-header "From")
7967       (goto-char (point-max))
7968       (insert "From: " (let ((user-mail-address email)) (message-make-from))
7969               "\n"))))
7970
7971 (defun message-options-get (symbol)
7972   (cdr (assq symbol message-options)))
7973
7974 (defun message-options-set (symbol value)
7975   (let ((the-cons (assq symbol message-options)))
7976     (if the-cons
7977         (if value
7978             (setcdr the-cons value)
7979           (setq message-options (delq the-cons message-options)))
7980       (and value
7981            (push (cons symbol value) message-options))))
7982   value)
7983
7984 (defun message-options-set-recipient ()
7985   (save-restriction
7986     (message-narrow-to-headers-or-head)
7987     (message-options-set 'message-sender
7988                          (mail-strip-quoted-names
7989                           (message-fetch-field "from")))
7990     (message-options-set 'message-recipients
7991                          (mail-strip-quoted-names
7992                           (let ((to (message-fetch-field "to"))
7993                                 (cc (message-fetch-field "cc"))
7994                                 (bcc (message-fetch-field "bcc")))
7995                             (concat
7996                              (or to "")
7997                              (if (and to cc) ", ")
7998                              (or cc "")
7999                              (if (and (or to cc) bcc) ", ")
8000                              (or bcc "")))))))
8001
8002 (defun message-hide-headers ()
8003   "Hide headers based on the `message-hidden-headers' variable."
8004   (let ((regexps (if (stringp message-hidden-headers)
8005                      (list message-hidden-headers)
8006                    message-hidden-headers))
8007         (inhibit-point-motion-hooks t)
8008         (after-change-functions nil)
8009         (end-of-headers (point-min)))
8010     (when regexps
8011       (save-excursion
8012         (save-restriction
8013           (message-narrow-to-headers)
8014           (goto-char (point-min))
8015           (while (not (eobp))
8016             (if (not (message-hide-header-p regexps))
8017                 (message-next-header)
8018               (let ((begin (point))
8019                     header header-len)
8020                 (message-next-header)
8021                 (setq header (buffer-substring begin (point))
8022                       header-len (- (point) begin))
8023                 (delete-region begin (point))
8024                 (goto-char end-of-headers)
8025                 (insert header)
8026                 (setq end-of-headers
8027                       (+ end-of-headers header-len))))))))
8028     (narrow-to-region end-of-headers (point-max))))
8029
8030 (defun message-hide-header-p (regexps)
8031   (let ((result nil)
8032         (reverse nil))
8033     (when (eq (car regexps) 'not)
8034       (setq reverse t)
8035       (pop regexps))
8036     (dolist (regexp regexps)
8037       (setq result (or result (looking-at regexp))))
8038     (if reverse
8039         (not result)
8040       result)))
8041
8042 (declare-function ecomplete-add-item "ecomplete" (type key text))
8043 (declare-function ecomplete-save "ecomplete" ())
8044
8045 (defun message-put-addresses-in-ecomplete ()
8046   (require 'ecomplete)
8047   (dolist (header '("to" "cc" "from" "reply-to"))
8048     (let ((value (message-field-value header)))
8049       (dolist (string (mail-header-parse-addresses value 'raw))
8050         (setq string
8051               (gnus-replace-in-string
8052                (gnus-replace-in-string string "^ +\\| +$" "") "\n" ""))
8053         (ecomplete-add-item 'mail (car (mail-header-parse-address string))
8054                             string))))
8055   (ecomplete-save))
8056
8057 (autoload 'ecomplete-display-matches "ecomplete")
8058
8059 (defun message-display-abbrev (&optional choose)
8060   "Display the next possible abbrev for the text before point."
8061   (interactive (list t))
8062   (when (and (memq (char-after (point-at-bol)) '(?C ?T ?\t ? ))
8063              (message-point-in-header-p)
8064              (save-excursion
8065                (beginning-of-line)
8066                (while (and (memq (char-after) '(?\t ? ))
8067                            (zerop (forward-line -1))))
8068                (looking-at "To:\\|Cc:")))
8069     (let* ((end (point))
8070            (start (save-excursion
8071                     (and (re-search-backward "[\n\t ]" nil t)
8072                          (1+ (point)))))
8073            (word (when start (buffer-substring start end)))
8074            (match (when (and word
8075                              (not (zerop (length word))))
8076                     (ecomplete-display-matches 'mail word choose))))
8077       (when (and choose match)
8078         (delete-region start end)
8079         (insert match)))))
8080
8081 ;; To send pre-formatted letters like the example below, you can use
8082 ;; `message-send-form-letter':
8083 ;; --8<---------------cut here---------------start------------->8---
8084 ;; To: alice@invalid.invalid
8085 ;; Subject: Verification of your contact information
8086 ;; From: Contact verification <admin@foo.invalid>
8087 ;; --text follows this line--
8088 ;; Hi Alice,
8089 ;; please verify that your contact information is still valid:
8090 ;; Alice A, A avenue 11, 1111 A town, Austria
8091 ;; ----------next form letter message follows this line----------
8092 ;; To: bob@invalid.invalid
8093 ;; Subject: Verification of your contact information
8094 ;; From: Contact verification <admin@foo.invalid>
8095 ;; --text follows this line--
8096 ;; Hi Bob,
8097 ;; please verify that your contact information is still valid:
8098 ;; Bob, B street 22, 22222 Be town, Belgium
8099 ;; ----------next form letter message follows this line----------
8100 ;; To: charlie@invalid.invalid
8101 ;; Subject: Verification of your contact information
8102 ;; From: Contact verification <admin@foo.invalid>
8103 ;; --text follows this line--
8104 ;; Hi Charlie,
8105 ;; please verify that your contact information is still valid:
8106 ;; Charlie Chaplin, C plaza 33, 33333 C town, Chile
8107 ;; --8<---------------cut here---------------end--------------->8---
8108
8109 ;; FIXME: What is the most common term (circular letter, form letter, serial
8110 ;; letter, standard letter) for such kind of letter?  See also
8111 ;; <http://en.wikipedia.org/wiki/Form_letter>
8112
8113 ;; FIXME: Maybe extent message-mode's font-lock support to recognize
8114 ;; `message-form-letter-separator', i.e. highlight each message like a single
8115 ;; message.
8116
8117 (defcustom message-form-letter-separator
8118   "\n----------next form letter message follows this line----------\n"
8119   "Separator for `message-send-form-letter'."
8120   ;; :group 'message-form-letter
8121   :group 'message-various
8122   :version "23.1" ;; No Gnus
8123   :type 'string)
8124
8125 (defcustom message-send-form-letter-delay 1
8126   "Delay in seconds when sending a message with `message-send-form-letter'.
8127 Only used when `message-send-form-letter' is called with non-nil
8128 argument `force'."
8129   ;; :group 'message-form-letter
8130   :group 'message-various
8131   :version "23.1" ;; No Gnus
8132   :type 'integer)
8133
8134 (defun message-send-form-letter (&optional force)
8135   "Sent all form letter messages from current buffer.
8136 Unless FORCE, prompt before sending.
8137
8138 The messages are separated by `message-form-letter-separator'.
8139 Header and body are separated by `mail-header-separator'."
8140   (interactive "P")
8141   (let ((sent 0) (skipped 0)
8142         start end text
8143         buff
8144         to done)
8145     (goto-char (point-min))
8146     (while (not done)
8147       (setq start (point)
8148             end (if (search-forward message-form-letter-separator nil t)
8149                     (- (point) (length message-form-letter-separator) -1)
8150                   (setq done t)
8151                   (point-max)))
8152       (setq text
8153             (buffer-substring-no-properties start end))
8154       (setq buff (generate-new-buffer "*mail - form letter*"))
8155       (with-current-buffer buff
8156         (insert text)
8157         (message-mode)
8158         (setq to (message-fetch-field "To"))
8159         (switch-to-buffer buff)
8160         (when force
8161           (sit-for message-send-form-letter-delay))
8162         (if (or force
8163                   (y-or-n-p (format "Send message to `%s'? " to)))
8164             (progn
8165               (setq sent (1+ sent))
8166               (message-send-and-exit))
8167           (message (format "Message to `%s' skipped." to))
8168           (setq skipped (1+ skipped)))
8169         (when (buffer-live-p buff)
8170           (kill-buffer buff))))
8171     (message "%s message(s) sent, %s skipped." sent skipped)))
8172
8173 (defun message-replace-header (header new-value &optional after force)
8174   "Remove HEADER and insert the NEW-VALUE.
8175 If AFTER, insert after this header.  If FORCE, insert new field
8176 even if NEW-VALUE is empty."
8177   ;; Similar to `nnheader-replace-header' but for message buffers.
8178   (save-excursion
8179     (save-restriction
8180       (message-narrow-to-headers)
8181       (message-remove-header header))
8182     (when (or force (> (length new-value) 0))
8183       (if after
8184           (message-position-on-field header after)
8185         (message-position-on-field header))
8186       (insert new-value))))
8187
8188 (defcustom message-recipients-without-full-name
8189   (list "ding@gnus.org"
8190         "bugs@gnus.org"
8191         "emacs-devel@gnu.org"
8192         "emacs-pretest-bug@gnu.org"
8193         "bug-gnu-emacs@gnu.org")
8194   "Mail addresses that have no full name.
8195 Used in `message-simplify-recipients'."
8196   ;; Maybe the addresses could be extracted from
8197   ;; `gnus-parameter-to-list-alist'?
8198   :type '(choice (const :tag "None" nil)
8199                  (repeat string))
8200   :version "23.1" ;; No Gnus
8201   :group 'message-headers)
8202
8203 (defun message-simplify-recipients ()
8204   (interactive)
8205   (dolist (hdr '("Cc" "To"))
8206     (message-replace-header
8207      hdr
8208      (mapconcat
8209       (lambda (addrcomp)
8210         (if (and message-recipients-without-full-name
8211                  (string-match
8212                   (regexp-opt message-recipients-without-full-name)
8213                   (cadr addrcomp)))
8214             (cadr addrcomp)
8215           (if (car addrcomp)
8216               (message-make-from (car addrcomp) (cadr addrcomp))
8217             (cadr addrcomp))))
8218       (when (message-fetch-field hdr)
8219         (mail-extract-address-components
8220          (message-fetch-field hdr) t))
8221       ", "))))
8222
8223 (when (featurep 'xemacs)
8224   (require 'messagexmas)
8225   (message-xmas-redefine))
8226
8227 (provide 'message)
8228
8229 (run-hooks 'message-load-hook)
8230
8231 ;; Local Variables:
8232 ;; coding: iso-8859-1
8233 ;; End:
8234
8235 ;;; message.el ends here