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