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