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