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