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