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