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