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