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