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