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