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