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