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