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