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