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