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