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