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