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