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