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