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