sync with 0.8.11cvs5
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gdk/gdkkeysyms.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkmenu.h>
30 #include <gtk/gtkmenuitem.h>
31 #include <gtk/gtkitemfactory.h>
32 #include <gtk/gtkcheckmenuitem.h>
33 #include <gtk/gtkoptionmenu.h>
34 #include <gtk/gtkwidget.h>
35 #include <gtk/gtkclist.h>
36 #include <gtk/gtkctree.h>
37 #include <gtk/gtkvpaned.h>
38 #include <gtk/gtkentry.h>
39 #include <gtk/gtkeditable.h>
40 #include <gtk/gtkwindow.h>
41 #include <gtk/gtksignal.h>
42 #include <gtk/gtkvbox.h>
43 #include <gtk/gtkcontainer.h>
44 #include <gtk/gtkhandlebox.h>
45 #include <gtk/gtktoolbar.h>
46 #include <gtk/gtktable.h>
47 #include <gtk/gtkhbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkscrolledwindow.h>
50 #include <gtk/gtkthemes.h>
51 #include <gtk/gtkdnd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <sys/types.h>
57 #include <sys/stat.h>
58 #include <unistd.h>
59 #include <time.h>
60 /* #include <sys/utsname.h> */
61 #include <stdlib.h>
62 #include <sys/wait.h>
63 #include <signal.h>
64 #include <errno.h>
65
66 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
67 #  include <wchar.h>
68 #  include <wctype.h>
69 #endif
70
71 #include "intl.h"
72 #include "main.h"
73 #include "mainwindow.h"
74 #include "compose.h"
75 #include "gtkstext.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "stock_pixmap.h"
81 #include "send.h"
82 #include "imap.h"
83 #include "news.h"
84 #include "customheader.h"
85 #include "prefs_common.h"
86 #include "prefs_account.h"
87 #include "prefs_actions.h"
88 #include "account.h"
89 #include "filesel.h"
90 #include "procheader.h"
91 #include "procmime.h"
92 #include "statusbar.h"
93 #include "about.h"
94 #include "base64.h"
95 #include "quoted-printable.h"
96 #include "codeconv.h"
97 #include "utils.h"
98 #include "gtkutils.h"
99 #include "socket.h"
100 #include "alertpanel.h"
101 #include "manage_window.h"
102 #include "gtkshruler.h"
103 #include "folder.h"
104 #include "addr_compl.h"
105 #include "quote_fmt.h"
106 #include "template.h"
107 #include "undo.h"
108 #include "foldersel.h"
109 #include "toolbar.h"
110
111 #if USE_GPGME
112 #  include "rfc2015.h"
113 #endif
114
115 typedef enum
116 {
117         COL_MIMETYPE = 0,
118         COL_SIZE     = 1,
119         COL_NAME     = 2
120 } AttachColumnPos;
121
122 #define N_ATTACH_COLS           3
123
124 typedef enum
125 {
126         COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE,
127         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_CHARACTER,
128         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_CHARACTER,
129         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_WORD,
130         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_WORD,
131         COMPOSE_CALL_GTK_STEXT_MOVE_END_OF_LINE,
132         COMPOSE_CALL_GTK_STEXT_MOVE_NEXT_LINE,
133         COMPOSE_CALL_GTK_STEXT_MOVE_PREVIOUS_LINE,
134         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_CHARACTER,
135         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_CHARACTER,
136         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_WORD,
137         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_WORD,
138         COMPOSE_CALL_GTK_STEXT_DELETE_LINE,
139         COMPOSE_CALL_GTK_STEXT_DELETE_LINE_N,
140         COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END
141 } ComposeCallGtkSTextAction;
142
143 typedef enum
144 {
145         PRIORITY_HIGHEST = 1,
146         PRIORITY_HIGH,
147         PRIORITY_NORMAL,
148         PRIORITY_LOW,
149         PRIORITY_LOWEST
150 } PriorityLevel;
151
152 #define B64_LINE_SIZE           57
153 #define B64_BUFFSIZE            77
154
155 #define MAX_REFERENCES_LEN      999
156
157 static GdkColor quote_color = {0, 0, 0, 0xbfff};
158
159 static GList *compose_list = NULL;
160
161 Compose *compose_generic_new                    (PrefsAccount   *account,
162                                                  const gchar    *to,
163                                                  FolderItem     *item,
164                                                  GPtrArray      *attach_files);
165
166 static Compose *compose_create                  (PrefsAccount   *account,
167                                                  ComposeMode     mode);
168
169 static GtkWidget *compose_account_option_menu_create
170                                                 (Compose        *compose);
171 static void compose_set_template_menu           (Compose        *compose);
172 static void compose_template_apply              (Compose        *compose,
173                                                  Template       *tmpl,
174                                                  gboolean        replace);
175 static void compose_destroy                     (Compose        *compose);
176
177 static void compose_entries_set                 (Compose        *compose,
178                                                  const gchar    *mailto);
179 static gint compose_parse_header                (Compose        *compose,
180                                                  MsgInfo        *msginfo);
181 static gchar *compose_parse_references          (const gchar    *ref,
182                                                  const gchar    *msgid);
183
184 static gchar *compose_quote_fmt                 (Compose        *compose,
185                                                  MsgInfo        *msginfo,
186                                                  const gchar    *fmt,
187                                                  const gchar    *qmark,
188                                                  const gchar    *body);
189
190 static void compose_reply_set_entry             (Compose        *compose,
191                                                  MsgInfo        *msginfo,
192                                                  gboolean        to_all,
193                                                  gboolean        to_ml,
194                                                  gboolean        to_sender,
195                                                  gboolean
196                                                  followup_and_reply_to);
197 static void compose_reedit_set_entry            (Compose        *compose,
198                                                  MsgInfo        *msginfo);
199 static void compose_insert_sig                  (Compose        *compose);
200 static void compose_insert_file                 (Compose        *compose,
201                                                  const gchar    *file);
202 static void compose_insert_command_output       (Compose        *compose,
203                                                  const gchar    *cmdline);
204 static void compose_attach_append               (Compose        *compose,
205                                                  const gchar    *file,
206                                                  const gchar    *type,
207                                                  const gchar    *content_type);
208 static void compose_attach_parts                (Compose        *compose,
209                                                  MsgInfo        *msginfo);
210 static void compose_wrap_line                   (Compose        *compose);
211 static void compose_wrap_line_all               (Compose        *compose);
212 static void compose_wrap_line_all_full          (Compose        *compose,
213                                                  gboolean        autowrap);
214 static void compose_set_title                   (Compose        *compose);
215 static void compose_select_account              (Compose        *compose,
216                                                  PrefsAccount   *account);
217
218 static PrefsAccount *compose_current_mail_account(void);
219 /* static gint compose_send                     (Compose        *compose); */
220 static gboolean compose_check_for_valid_recipient
221                                                 (Compose        *compose);
222 static gboolean compose_check_entries           (Compose        *compose,
223                                                  gboolean       check_subject);
224 static gint compose_write_to_file               (Compose        *compose,
225                                                  const gchar    *file,
226                                                  gboolean        is_draft);
227 static gint compose_write_body_to_file          (Compose        *compose,
228                                                  const gchar    *file);
229 static gint compose_remove_reedit_target        (Compose        *compose);
230 void compose_remove_draft                       (Compose        *compose);
231 static gint compose_queue                       (Compose        *compose,
232                                                  gint           *msgnum,
233                                                  FolderItem     **item);
234 static gint compose_queue_sub                   (Compose        *compose,
235                                                  gint           *msgnum,
236                                                  FolderItem     **item,
237                                                  gboolean       check_subject);
238 static void compose_write_attach                (Compose        *compose,
239                                                  FILE           *fp);
240 static gint compose_write_headers               (Compose        *compose,
241                                                  FILE           *fp,
242                                                  const gchar    *charset,
243                                                  EncodingType    encoding,
244                                                  gboolean        is_draft);
245
246 static void compose_convert_header              (gchar          *dest,
247                                                  gint            len,
248                                                  gchar          *src,
249                                                  gint            header_len);
250 static void compose_generate_msgid              (Compose        *compose,
251                                                  gchar          *buf,
252                                                  gint            len);
253
254 static void compose_attach_info_free            (AttachInfo     *ainfo);
255 static void compose_attach_remove_selected      (Compose        *compose);
256
257 static void compose_attach_property             (Compose        *compose);
258 static void compose_attach_property_create      (gboolean       *cancelled);
259 static void attach_property_ok                  (GtkWidget      *widget,
260                                                  gboolean       *cancelled);
261 static void attach_property_cancel              (GtkWidget      *widget,
262                                                  gboolean       *cancelled);
263 static gint attach_property_delete_event        (GtkWidget      *widget,
264                                                  GdkEventAny    *event,
265                                                  gboolean       *cancelled);
266 static void attach_property_key_pressed         (GtkWidget      *widget,
267                                                  GdkEventKey    *event,
268                                                  gboolean       *cancelled);
269
270 static void compose_exec_ext_editor             (Compose           *compose);
271 static gint compose_exec_ext_editor_real        (const gchar       *file);
272 static gboolean compose_ext_editor_kill         (Compose           *compose);
273 static void compose_input_cb                    (gpointer           data,
274                                                  gint               source,
275                                                  GdkInputCondition  condition);
276 static void compose_set_ext_editor_sensitive    (Compose           *compose,
277                                                  gboolean           sensitive);
278
279 static void compose_undo_state_changed          (UndoMain       *undostruct,
280                                                  gint            undo_state,
281                                                  gint            redo_state,
282                                                  gpointer        data);
283
284 static gint calc_cursor_xpos    (GtkSText       *text,
285                                  gint            extra,
286                                  gint            char_width);
287
288 static void compose_create_header_entry (Compose *compose);
289 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
290 static void compose_update_priority_menu_item(Compose * compose);
291
292 /* callback functions */
293
294 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
295                                          GtkAllocation  *allocation,
296                                          GtkSHRuler     *shruler);
297 static void account_activated           (GtkMenuItem    *menuitem,
298                                          gpointer        data);
299 static void attach_selected             (GtkCList       *clist,
300                                          gint            row,
301                                          gint            column,
302                                          GdkEvent       *event,
303                                          gpointer        data);
304 static void attach_button_pressed       (GtkWidget      *widget,
305                                          GdkEventButton *event,
306                                          gpointer        data);
307 static void attach_key_pressed          (GtkWidget      *widget,
308                                          GdkEventKey    *event,
309                                          gpointer        data);
310
311 static void compose_send_cb             (gpointer        data,
312                                          guint           action,
313                                          GtkWidget      *widget);
314 static void compose_send_later_cb       (gpointer        data,
315                                          guint           action,
316                                          GtkWidget      *widget);
317
318 static void compose_draft_cb            (gpointer        data,
319                                          guint           action,
320                                          GtkWidget      *widget);
321
322 static void compose_attach_cb           (gpointer        data,
323                                          guint           action,
324                                          GtkWidget      *widget);
325 static void compose_insert_file_cb      (gpointer        data,
326                                          guint           action,
327                                          GtkWidget      *widget);
328
329 static void compose_close_cb            (gpointer        data,
330                                          guint           action,
331                                          GtkWidget      *widget);
332
333 static void compose_address_cb          (gpointer        data,
334                                          guint           action,
335                                          GtkWidget      *widget);
336 static void compose_template_activate_cb(GtkWidget      *widget,
337                                          gpointer        data);
338
339 static void compose_ext_editor_cb       (gpointer        data,
340                                          guint           action,
341                                          GtkWidget      *widget);
342
343 static gint compose_delete_cb           (GtkWidget      *widget,
344                                          GdkEventAny    *event,
345                                          gpointer        data);
346 static void compose_destroy_cb          (GtkWidget      *widget,
347                                          Compose        *compose);
348
349 static void compose_undo_cb             (Compose        *compose);
350 static void compose_redo_cb             (Compose        *compose);
351 static void compose_cut_cb              (Compose        *compose);
352 static void compose_copy_cb             (Compose        *compose);
353 static void compose_paste_cb            (Compose        *compose);
354 static void compose_paste_as_quote_cb   (Compose        *compose);
355 static void compose_allsel_cb           (Compose        *compose);
356
357 static void compose_gtk_stext_action_cb (Compose                   *compose,
358                                          ComposeCallGtkSTextAction  action);
359
360 static void compose_grab_focus_cb       (GtkWidget      *widget,
361                                          Compose        *compose);
362
363 static void compose_changed_cb          (GtkEditable    *editable,
364                                          Compose        *compose);
365 static void compose_button_press_cb     (GtkWidget      *widget,
366                                          GdkEventButton *event,
367                                          Compose        *compose);
368 #if 0
369 static void compose_key_press_cb        (GtkWidget      *widget,
370                                          GdkEventKey    *event,
371                                          Compose        *compose);
372 #endif
373
374 #if 0
375 static void compose_toggle_to_cb        (gpointer        data,
376                                          guint           action,
377                                          GtkWidget      *widget);
378 static void compose_toggle_cc_cb        (gpointer        data,
379                                          guint           action,
380                                          GtkWidget      *widget);
381 static void compose_toggle_bcc_cb       (gpointer        data,
382                                          guint           action,
383                                          GtkWidget      *widget);
384 static void compose_toggle_replyto_cb   (gpointer        data,
385                                          guint           action,
386                                          GtkWidget      *widget);
387 static void compose_toggle_followupto_cb(gpointer        data,
388                                          guint           action,
389                                          GtkWidget      *widget);
390 static void compose_toggle_attach_cb    (gpointer        data,
391                                          guint           action,
392                                          GtkWidget      *widget);
393 #endif
394 static void compose_toggle_ruler_cb     (gpointer        data,
395                                          guint           action,
396                                          GtkWidget      *widget);
397 #if USE_GPGME
398 static void compose_toggle_sign_cb      (gpointer        data,
399                                          guint           action,
400                                          GtkWidget      *widget);
401 static void compose_toggle_encrypt_cb   (gpointer        data,
402                                          guint           action,
403                                          GtkWidget      *widget);
404 static void compose_set_gnupg_mode_cb   (gpointer        data,
405                                          guint           action,
406                                          GtkWidget      *widget);
407 static void compose_update_gnupg_mode_menu_item(Compose * compose);
408 static void activate_gnupg_mode         (Compose *compose, 
409                                          PrefsAccount *account);
410 #endif
411 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
412                                              GtkWidget *widget);
413 static void compose_set_priority_cb     (gpointer        data,
414                                          guint           action,
415                                          GtkWidget      *widget);
416
417 static void compose_attach_drag_received_cb (GtkWidget          *widget,
418                                              GdkDragContext     *drag_context,
419                                              gint                x,
420                                              gint                y,
421                                              GtkSelectionData   *data,
422                                              guint               info,
423                                              guint               time,
424                                              gpointer            user_data);
425 static void compose_insert_drag_received_cb (GtkWidget          *widget,
426                                              GdkDragContext     *drag_context,
427                                              gint                x,
428                                              gint                y,
429                                              GtkSelectionData   *data,
430                                              guint               info,
431                                              guint               time,
432                                              gpointer            user_data);
433
434 #if 0
435 static void to_activated                (GtkWidget      *widget,
436                                          Compose        *compose);
437 static void newsgroups_activated        (GtkWidget      *widget,
438                                          Compose        *compose);
439 static void cc_activated                (GtkWidget      *widget,
440                                          Compose        *compose);
441 static void bcc_activated               (GtkWidget      *widget,
442                                          Compose        *compose);
443 static void replyto_activated           (GtkWidget      *widget,
444                                          Compose        *compose);
445 static void followupto_activated        (GtkWidget      *widget,
446                                          Compose        *compose);
447 static void subject_activated           (GtkWidget      *widget,
448                                          Compose        *compose);
449 #endif
450
451 static void text_activated              (GtkWidget      *widget,
452                                          Compose        *compose);
453 static void text_inserted               (GtkWidget      *widget,
454                                          const gchar    *text,
455                                          gint            length,
456                                          gint           *position,
457                                          Compose        *compose);
458 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
459                                   gboolean to_all, gboolean to_ml,
460                                   gboolean to_sender,
461                                   gboolean followup_and_reply_to,
462                                   const gchar *body);
463
464 void compose_headerentry_changed_cb        (GtkWidget          *entry,
465                                             ComposeHeaderEntry *headerentry);
466 void compose_headerentry_key_press_event_cb(GtkWidget          *entry,
467                                             GdkEventKey        *event,
468                                             ComposeHeaderEntry *headerentry);
469
470 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
471
472 #if USE_ASPELL
473 static void compose_check_all              (Compose *compose);
474 static void compose_highlight_all          (Compose *compose);
475 static void compose_check_backwards        (Compose *compose);
476 static void compose_check_forwards_go      (Compose *compose);
477 #endif
478
479 static gboolean compose_send_control_enter      (Compose        *compose);
480
481 static GtkItemFactoryEntry compose_popup_entries[] =
482 {
483         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
484         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
485         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
486         {N_("/_Properties..."), NULL, compose_attach_property, 0, NULL}
487 };
488
489 static GtkItemFactoryEntry compose_entries[] =
490 {
491         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
492         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
493         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
494         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
495         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
496         {N_("/_File/_Close"),                   "<control>W", compose_close_cb, 0, NULL},
497
498         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
499         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
500         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
501         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
502         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
503         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
504         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
505         {N_("/_Edit/Paste as _quotation"),
506                                         NULL, compose_paste_as_quote_cb, 0, NULL},
507         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
508         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
509         {N_("/_Edit/A_dvanced/Move a character backward"),
510                                         "<control>B",
511                                         compose_gtk_stext_action_cb,
512                                         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_CHARACTER,
513                                         NULL},
514         {N_("/_Edit/A_dvanced/Move a character forward"),
515                                         "<control>F",
516                                         compose_gtk_stext_action_cb,
517                                         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_CHARACTER,
518                                         NULL},
519         {N_("/_Edit/A_dvanced/Move a word backward"),
520                                         NULL, /* "<alt>B" */
521                                         compose_gtk_stext_action_cb,
522                                         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_WORD,
523                                         NULL},
524         {N_("/_Edit/A_dvanced/Move a word forward"),
525                                         NULL, /* "<alt>F" */
526                                         compose_gtk_stext_action_cb,
527                                         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_WORD,
528                                         NULL},
529         {N_("/_Edit/A_dvanced/Move to beginning of line"),
530                                         NULL, /* "<control>A" */
531                                         compose_gtk_stext_action_cb,
532                                         COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE,
533                                         NULL},
534         {N_("/_Edit/A_dvanced/Move to end of line"),
535                                         "<control>E",
536                                         compose_gtk_stext_action_cb,
537                                         COMPOSE_CALL_GTK_STEXT_MOVE_END_OF_LINE,
538                                         NULL},
539         {N_("/_Edit/A_dvanced/Move to previous line"),
540                                         "<control>P",
541                                         compose_gtk_stext_action_cb,
542                                         COMPOSE_CALL_GTK_STEXT_MOVE_PREVIOUS_LINE,
543                                         NULL},
544         {N_("/_Edit/A_dvanced/Move to next line"),
545                                         "<control>N",
546                                         compose_gtk_stext_action_cb,
547                                         COMPOSE_CALL_GTK_STEXT_MOVE_NEXT_LINE,
548                                         NULL},
549         {N_("/_Edit/A_dvanced/Delete a character backward"),
550                                         "<control>H",
551                                         compose_gtk_stext_action_cb,
552                                         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_CHARACTER,
553                                         NULL},
554         {N_("/_Edit/A_dvanced/Delete a character forward"),
555                                         "<control>D",
556                                         compose_gtk_stext_action_cb,
557                                         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_CHARACTER,
558                                         NULL},
559         {N_("/_Edit/A_dvanced/Delete a word backward"),
560                                         NULL, /* "<control>W" */
561                                         compose_gtk_stext_action_cb,
562                                         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_WORD,
563                                         NULL},
564         {N_("/_Edit/A_dvanced/Delete a word forward"),
565                                         NULL, /* "<alt>D", */
566                                         compose_gtk_stext_action_cb,
567                                         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_WORD,
568                                         NULL},
569         {N_("/_Edit/A_dvanced/Delete line"),
570                                         "<control>U",
571                                         compose_gtk_stext_action_cb,
572                                         COMPOSE_CALL_GTK_STEXT_DELETE_LINE,
573                                         NULL},
574         {N_("/_Edit/A_dvanced/Delete entire line"),
575                                         NULL,
576                                         compose_gtk_stext_action_cb,
577                                         COMPOSE_CALL_GTK_STEXT_DELETE_LINE_N,
578                                         NULL},
579         {N_("/_Edit/A_dvanced/Delete to end of line"),
580                                         "<control>K",
581                                         compose_gtk_stext_action_cb,
582                                         COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END,
583                                         NULL},
584         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
585         {N_("/_Edit/_Wrap current paragraph"),
586                                         "<control>L", compose_wrap_line, 0, NULL},
587         {N_("/_Edit/Wrap all long _lines"),
588                                         "<control><alt>L", compose_wrap_line_all, 0, NULL},
589         {N_("/_Edit/Edit with e_xternal editor"),
590                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
591 #if USE_ASPELL
592         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
593         {N_("/_Spelling/_Check all or check selection"),
594                                         NULL, compose_check_all, 0, NULL},
595         {N_("/_Spelling/_Highlight all misspelled words"),
596                                         NULL, compose_highlight_all, 0, NULL},
597         {N_("/_Spelling/Check _backwards misspelled word"),
598                                         NULL, compose_check_backwards , 0, NULL},
599         {N_("/_Spelling/_Forward to next misspelled word"),
600                                         NULL, compose_check_forwards_go, 0, NULL},
601         {N_("/_Spelling/---"),          NULL, NULL, 0, "<Separator>"},
602         {N_("/_Spelling/_Spelling Configuration"),
603                                         NULL, NULL, 0, "<Branch>"},
604 #endif
605 #if 0 /* NEW COMPOSE GUI */
606         {N_("/_View"),                  NULL, NULL, 0, "<Branch>"},
607         {N_("/_View/_To"),              NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
608         {N_("/_View/_Cc"),              NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
609         {N_("/_View/_Bcc"),             NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
610         {N_("/_View/_Reply to"),        NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
611         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
612         {N_("/_View/_Followup to"),     NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
613         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
614         {N_("/_View/R_uler"),           NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
615         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
616         {N_("/_View/_Attachment"),      NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
617 #endif
618         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
619         {N_("/_Message/_Send"),         "<control>Return",
620                                         compose_send_cb, 0, NULL},
621         {N_("/_Message/Send _later"),   "<shift><control>S",
622                                         compose_send_later_cb,  0, NULL},
623         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
624         {N_("/_Message/Save to _draft folder"),
625                                         "<shift><control>D", compose_draft_cb, 0, NULL},
626         {N_("/_Message/Save and _keep editing"),
627                                         "<control>S", compose_draft_cb, 1, NULL},
628 #if 0 /* NEW COMPOSE GUI */
629         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
630         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
631         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
632         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
633         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
634         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
635         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
636         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
637         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
638 #endif
639 #if USE_GPGME
640         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
641         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
642         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
643         {N_("/_Message/Mode/MIME"),             NULL, compose_set_gnupg_mode_cb,   GNUPG_MODE_DETACH, "<RadioItem>"},   
644         {N_("/_Message/Mode/Inline"),   NULL, compose_set_gnupg_mode_cb,   GNUPG_MODE_INLINE, "/Message/Mode/MIME"},    
645 #endif /* USE_GPGME */
646         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
647         {N_("/_Message/_Priority"),     NULL,           NULL,   0, "<Branch>"},
648         {N_("/_Message/Priority/_Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
649         {N_("/_Message/Priority/Hi_gh"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Message/Priority/Highest"},
650         {N_("/_Message/Priority/_Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Message/Priority/Highest"},
651         {N_("/_Message/Priority/Lo_w"),    NULL, compose_set_priority_cb, PRIORITY_LOW, "/Message/Priority/Highest"},
652         {N_("/_Message/Priority/_Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Message/Priority/Highest"},
653         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
654         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
655         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
656         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
657         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
658         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
659         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
660         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
661         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
662 };
663
664 static GtkTargetEntry compose_mime_types[] =
665 {
666         {"text/uri-list", 0, 0}
667 };
668
669 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
670                      GPtrArray *attach_files)
671 {
672         return compose_generic_new(account, mailto, NULL, attach_files);
673 }
674
675 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
676 {
677         return compose_generic_new(account, NULL, item, NULL);
678 }
679
680 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
681                              GPtrArray *attach_files)
682 {
683         Compose *compose;
684         GtkSText *text;
685         GtkItemFactory *ifactory;
686         gboolean grab_focus_on_last = TRUE;
687
688         if (item && item->prefs && item->prefs->enable_default_account)
689                 account = account_find_from_id(item->prefs->default_account);
690
691         if (!account) account = cur_account;
692         g_return_val_if_fail(account != NULL, NULL);
693
694         compose = compose_create(account, COMPOSE_NEW);
695         ifactory = gtk_item_factory_from_widget(compose->menubar);
696
697         compose->replyinfo = NULL;
698         compose->fwdinfo   = NULL;
699
700         text = GTK_STEXT(compose->text);
701         gtk_stext_freeze(text);
702
703         if (account->auto_sig)
704                 compose_insert_sig(compose);
705         gtk_editable_set_position(GTK_EDITABLE(text), 0);
706         gtk_stext_set_point(text, 0);
707
708         gtk_stext_thaw(text);
709
710         if (account->protocol != A_NNTP) {
711                 if (mailto && *mailto != '\0') {
712                         compose_entries_set(compose, mailto);
713
714                 } else if (item && item->prefs->enable_default_to) {
715                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
716                         compose_entry_select(compose, item->prefs->default_to);
717                         grab_focus_on_last = FALSE;
718                 }
719                 if (item && item->ret_rcpt) {
720                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
721                 }
722         } else {
723                 if (mailto) {
724                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
725                 }
726                 /*
727                  * CLAWS: just don't allow return receipt request, even if the user
728                  * may want to send an email. simple but foolproof.
729                  */
730                 menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE); 
731         }
732
733         if (attach_files) {
734                 gint i;
735                 gchar *file;
736
737                 for (i = 0; i < attach_files->len; i++) {
738                         file = g_ptr_array_index(attach_files, i);
739                         compose_attach_append(compose, file, file, NULL);
740                 }
741         }
742
743         compose_show_first_last_header(compose, TRUE);
744
745         /* Set save folder */
746         if (item && item->prefs && item->prefs->save_copy_to_folder) {
747                 gchar *folderidentifier;
748
749                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
750                 folderidentifier = folder_item_get_identifier(item);
751                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
752                 g_free(folderidentifier);
753         }
754         
755         /* Grab focus on last header only if no default_to was set */
756         if (grab_focus_on_last)
757                 gtk_widget_grab_focus(compose->header_last->entry);
758
759         if (prefs_common.auto_exteditor)
760                 compose_exec_ext_editor(compose);
761
762         return compose;
763 }
764
765 /*
766 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
767                                            const gchar *followupto, gchar * to)
768 {
769         Compose *compose;
770
771         if (!account) account = cur_account;
772         g_return_val_if_fail(account != NULL, NULL);
773         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
774
775         compose = compose_create(account, COMPOSE_NEW);
776
777         if (prefs_common.auto_sig)
778                 compose_insert_sig(compose);
779         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
780         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
781
782         compose_entry_append(compose, to, COMPOSE_TO);
783         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
784         gtk_widget_grab_focus(compose->subject_entry);
785
786         return compose;
787 }
788 */
789
790 void compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
791 {
792         MsgInfo *msginfo;
793         guint list_len;
794
795         g_return_if_fail(msginfo_list != NULL);
796
797         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
798         g_return_if_fail(msginfo != NULL);
799
800         list_len = g_slist_length(msginfo_list);
801
802         switch (mode) {
803         case COMPOSE_REPLY:
804                 compose_reply(msginfo, prefs_common.reply_with_quote,
805                               FALSE, prefs_common.default_reply_list, FALSE, body);
806                 break;
807         case COMPOSE_REPLY_WITH_QUOTE:
808                 compose_reply(msginfo, TRUE, FALSE, prefs_common.default_reply_list, FALSE, body);
809                 break;
810         case COMPOSE_REPLY_WITHOUT_QUOTE:
811                 compose_reply(msginfo, FALSE, FALSE, prefs_common.default_reply_list, FALSE, NULL);
812                 break;
813         case COMPOSE_REPLY_TO_SENDER:
814                 compose_reply(msginfo, prefs_common.reply_with_quote,
815                               FALSE, FALSE, TRUE, body);
816                 break;
817         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
818                 compose_followup_and_reply_to(msginfo,
819                                               prefs_common.reply_with_quote,
820                                               FALSE, FALSE, body);
821                 break;
822         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
823                 compose_reply(msginfo, TRUE, FALSE, FALSE, TRUE, body);
824                 break;
825         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
826                 compose_reply(msginfo, FALSE, FALSE, FALSE, TRUE, NULL);
827                 break;
828         case COMPOSE_REPLY_TO_ALL:
829                 compose_reply(msginfo, prefs_common.reply_with_quote,
830                               TRUE, FALSE, FALSE, body);
831                 break;
832         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
833                 compose_reply(msginfo, TRUE, TRUE, FALSE, FALSE, body);
834                 break;
835         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
836                 compose_reply(msginfo, FALSE, TRUE, FALSE, FALSE, NULL);
837                 break;
838         case COMPOSE_REPLY_TO_LIST:
839                 compose_reply(msginfo, prefs_common.reply_with_quote,
840                               FALSE, TRUE, FALSE, body);
841                 break;
842         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
843                 compose_reply(msginfo, TRUE, FALSE, TRUE, FALSE, body);
844                 break;
845         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
846                 compose_reply(msginfo, FALSE, FALSE, TRUE, FALSE, NULL);
847                 break;
848         case COMPOSE_FORWARD:
849                 if (prefs_common.forward_as_attachment) {
850                         compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
851                         return;
852                 } else {
853                         compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
854                         return;
855                 }
856                 break;
857         case COMPOSE_FORWARD_INLINE:
858                 /* check if we reply to more than one Message */
859                 if (list_len == 1) {
860                         compose_forward(NULL, msginfo, FALSE, body);
861                         break;
862                 } 
863                 /* more messages FALL THROUGH */
864         case COMPOSE_FORWARD_AS_ATTACH:
865                 compose_forward_multiple(NULL, msginfo_list);
866                 break;
867         case COMPOSE_REDIRECT:
868                 compose_redirect(NULL, msginfo);
869                 break;
870         default:
871                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
872         }
873 }
874
875 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
876                    gboolean to_ml, gboolean to_sender, 
877                    const gchar *body)
878 {
879         compose_generic_reply(msginfo, quote, to_all, to_ml, 
880                               to_sender, FALSE, body);
881 }
882
883 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
884                                    gboolean to_all,
885                                    gboolean to_sender,
886                                    const gchar *body)
887 {
888         compose_generic_reply(msginfo, quote, to_all, FALSE, 
889                               to_sender, TRUE, body);
890 }
891
892 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
893                                   gboolean to_all, gboolean to_ml,
894                                   gboolean to_sender,
895                                   gboolean followup_and_reply_to,
896                                   const gchar *body)
897 {
898         Compose *compose;
899         PrefsAccount *account = NULL;
900         PrefsAccount *reply_account;
901         GtkSText *text;
902
903         g_return_if_fail(msginfo != NULL);
904         g_return_if_fail(msginfo->folder != NULL);
905
906         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
907         
908         g_return_if_fail(account != NULL);
909
910         if (to_sender && account->protocol == A_NNTP &&
911             !followup_and_reply_to) {
912                 reply_account =
913                         account_find_from_address(account->address);
914                 if (!reply_account)
915                         reply_account = compose_current_mail_account();
916                 if (!reply_account)
917                         return;
918         } else
919                 reply_account = account;
920
921         compose = compose_create(account, COMPOSE_REPLY);
922
923         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
924         if (!compose->replyinfo)
925                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
926
927         if (msginfo->folder && msginfo->folder->ret_rcpt) {
928                 GtkItemFactory *ifactory;
929         
930                 ifactory = gtk_item_factory_from_widget(compose->menubar);
931                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
932         }
933
934         /* Set save folder */
935         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
936                 gchar *folderidentifier;
937
938                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
939                 folderidentifier = folder_item_get_identifier(msginfo->folder);
940                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
941                 g_free(folderidentifier);
942         }
943
944         if (compose_parse_header(compose, msginfo) < 0) return;
945         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
946                                 to_sender, followup_and_reply_to);
947         compose_show_first_last_header(compose, TRUE);
948
949         text = GTK_STEXT(compose->text);
950         gtk_stext_freeze(text);
951
952         if (quote) {
953                 gchar *qmark;
954                 gchar *quote_str;
955
956                 if (prefs_common.quotemark && *prefs_common.quotemark)
957                         qmark = prefs_common.quotemark;
958                 else
959                         qmark = "> ";
960
961                 quote_str = compose_quote_fmt(compose, compose->replyinfo,
962                                               prefs_common.quotefmt,
963                                               qmark, body);
964         }
965
966         if (account->auto_sig)
967                 compose_insert_sig(compose);
968
969         if (quote && prefs_common.linewrap_quote)
970                 compose_wrap_line_all(compose);
971
972         gtk_editable_set_position(GTK_EDITABLE(text), 0);
973         gtk_stext_set_point(text, 0);
974
975         gtk_stext_thaw(text);
976         gtk_widget_grab_focus(compose->text);
977
978         if (prefs_common.auto_exteditor)
979                 compose_exec_ext_editor(compose);
980 }
981
982 #define INSERT_FW_HEADER(var, hdr) \
983 if (msginfo->var && *msginfo->var) { \
984         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
985         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
986         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
987 }
988
989 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
990                          gboolean as_attach, const gchar *body)
991 {
992         Compose *compose;
993         GtkSText *text;
994
995         g_return_val_if_fail(msginfo != NULL, NULL);
996         g_return_val_if_fail(msginfo->folder != NULL, NULL);
997
998         if (msginfo->folder->prefs->enable_default_account)
999                 account = account_find_from_id(msginfo->folder->prefs->default_account);
1000         if (!account) 
1001                 account = msginfo->folder->folder->account;
1002         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1003                 gchar *to;
1004                 Xstrdup_a(to, msginfo->to, return NULL);
1005                 extract_address(to);
1006                 account = account_find_from_address(to);
1007         }
1008
1009         if (!account && prefs_common.forward_account_autosel) {
1010                 gchar cc[BUFFSIZE];
1011                 if (!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1012                         extract_address(cc);
1013                         account = account_find_from_address(cc);
1014                 }
1015         }
1016
1017         if (account == NULL) {
1018                 account = cur_account;
1019                 /*
1020                 account = msginfo->folder->folder->account;
1021                 if (!account) account = cur_account;
1022                 */
1023         }
1024         g_return_val_if_fail(account != NULL, NULL);
1025
1026         compose = compose_create(account, COMPOSE_FORWARD);
1027
1028         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1029         if (!compose->fwdinfo)
1030                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1031
1032         if (msginfo->subject && *msginfo->subject) {
1033                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1034                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1035                                       msginfo->subject);
1036         }
1037
1038         text = GTK_STEXT(compose->text);
1039         gtk_stext_freeze(text);
1040
1041
1042                 if (as_attach) {
1043                         gchar *msgfile;
1044
1045                         msgfile = procmsg_get_message_file_path(msginfo);
1046                         if (!is_file_exist(msgfile))
1047                                 g_warning("%s: file not exist\n", msgfile);
1048                         else
1049                                 compose_attach_append(compose, msgfile, msgfile,
1050                                                       "message/rfc822");
1051
1052                         g_free(msgfile);
1053                 } else {
1054                         gchar *qmark;
1055                         gchar *quote_str;
1056                         MsgInfo *full_msginfo;
1057
1058                         full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1059                         if (!full_msginfo)
1060                                 full_msginfo = procmsg_msginfo_copy(msginfo);
1061
1062                         if (prefs_common.fw_quotemark &&
1063                             *prefs_common.fw_quotemark)
1064                                 qmark = prefs_common.fw_quotemark;
1065                         else
1066                                 qmark = "> ";
1067
1068                         quote_str = compose_quote_fmt(compose, full_msginfo,
1069                                                       prefs_common.fw_quotefmt,
1070                                                       qmark, body);
1071                         compose_attach_parts(compose, msginfo);
1072
1073                         procmsg_msginfo_free(full_msginfo);
1074                 }
1075
1076         if (account->auto_sig)
1077                 compose_insert_sig(compose);
1078
1079         if (prefs_common.linewrap_quote)
1080                 compose_wrap_line_all(compose);
1081
1082         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1083         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1084
1085         gtk_stext_thaw(text);
1086 #if 0 /* NEW COMPOSE GUI */
1087         if (account->protocol != A_NNTP)
1088                 gtk_widget_grab_focus(compose->to_entry);
1089         else
1090                 gtk_widget_grab_focus(compose->newsgroups_entry);
1091 #endif
1092         gtk_widget_grab_focus(compose->header_last->entry);
1093
1094         if (prefs_common.auto_exteditor)
1095                 compose_exec_ext_editor(compose);
1096         
1097         /*save folder*/
1098         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1099                 gchar *folderidentifier;
1100
1101                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1102                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1103                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1104                 g_free(folderidentifier);
1105         }
1106
1107         return compose;
1108 }
1109
1110 #undef INSERT_FW_HEADER
1111
1112 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1113 {
1114         Compose *compose;
1115         GtkSText *text;
1116         GSList *msginfo;
1117         gchar *msgfile;
1118
1119         g_return_val_if_fail(msginfo_list != NULL, NULL);
1120         
1121         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1122                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1123                         return NULL;
1124         }
1125
1126         if (account == NULL) {
1127                 account = cur_account;
1128                 /*
1129                 account = msginfo->folder->folder->account;
1130                 if (!account) account = cur_account;
1131                 */
1132         }
1133         g_return_val_if_fail(account != NULL, NULL);
1134
1135         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1136                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1137                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1138         }
1139
1140         compose = compose_create(account, COMPOSE_FORWARD);
1141
1142         text = GTK_STEXT(compose->text);
1143         gtk_stext_freeze(text);
1144
1145         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1146                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1147                 if (!is_file_exist(msgfile))
1148                         g_warning("%s: file not exist\n", msgfile);
1149                 else
1150                         compose_attach_append(compose, msgfile, msgfile,
1151                                 "message/rfc822");
1152                 g_free(msgfile);
1153         }
1154
1155         if (account->auto_sig)
1156                 compose_insert_sig(compose);
1157
1158         if (prefs_common.linewrap_quote)
1159                 compose_wrap_line_all(compose);
1160
1161         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1162         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1163
1164         gtk_stext_thaw(text);
1165         gtk_widget_grab_focus(compose->header_last->entry);
1166         
1167 #if 0 /* NEW COMPOSE GUI */
1168         if (account->protocol != A_NNTP)
1169                 gtk_widget_grab_focus(compose->to_entry);
1170         else
1171                 gtk_widget_grab_focus(compose->newsgroups_entry);
1172 #endif
1173
1174         return compose;
1175 }
1176
1177 void compose_reedit(MsgInfo *msginfo)
1178 {
1179         Compose *compose;
1180         PrefsAccount *account = NULL;
1181         GtkSText *text;
1182         FILE *fp;
1183         gchar buf[BUFFSIZE];
1184
1185         g_return_if_fail(msginfo != NULL);
1186         g_return_if_fail(msginfo->folder != NULL);
1187
1188         if (msginfo->folder->stype == F_QUEUE || msginfo->folder->stype == F_DRAFT) {
1189                 gchar queueheader_buf[BUFFSIZE];
1190                 gint id;
1191
1192                 /* Select Account from queue headers */
1193                 if (!get_header_from_msginfo(msginfo, queueheader_buf, 
1194                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1195                         id = atoi(&queueheader_buf[22]);
1196                         account = account_find_from_id(id);
1197                 }
1198                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1199                                              sizeof(queueheader_buf), "NAID:")) {
1200                         id = atoi(&queueheader_buf[5]);
1201                         account = account_find_from_id(id);
1202                 }
1203                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1204                                                     sizeof(queueheader_buf), "MAID:")) {
1205                         id = atoi(&queueheader_buf[5]);
1206                         account = account_find_from_id(id);
1207                 }
1208                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1209                                                                 sizeof(queueheader_buf), "S:")) {
1210                         account = account_find_from_address(queueheader_buf);
1211                 }
1212         } else 
1213                 account = msginfo->folder->folder->account;
1214
1215         if (!account && prefs_common.reedit_account_autosel) {
1216                 gchar from[BUFFSIZE];
1217                 if (!get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1218                         extract_address(from);
1219                         account = account_find_from_address(from);
1220                 }
1221         }
1222         if (!account) account = cur_account;
1223         g_return_if_fail(account != NULL);
1224
1225         compose = compose_create(account, COMPOSE_REEDIT);
1226         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1227
1228         if (msginfo->folder->stype == F_QUEUE
1229         ||  msginfo->folder->stype == F_DRAFT) {
1230                 gchar queueheader_buf[BUFFSIZE];
1231
1232                 /* Set message save folder */
1233                 if (!get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1234                         gint startpos = 0;
1235
1236                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1237                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1238                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1239                 }
1240         }
1241         
1242         if (compose_parse_header(compose, msginfo) < 0) return;
1243         compose_reedit_set_entry(compose, msginfo);
1244
1245         text = GTK_STEXT(compose->text);
1246         gtk_stext_freeze(text);
1247
1248         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1249                 g_warning("Can't get text part\n");
1250         else {
1251                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1252                         strcrchomp(buf);
1253                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1254                 }
1255                 fclose(fp);
1256         }
1257         compose_attach_parts(compose, msginfo);
1258
1259         gtk_stext_thaw(text);
1260         gtk_widget_grab_focus(compose->text);
1261
1262         if (prefs_common.auto_exteditor)
1263                 compose_exec_ext_editor(compose);
1264 }
1265
1266 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1267 {
1268         Compose *compose;
1269         gchar *filename;
1270         GtkItemFactory *ifactory;
1271
1272         g_return_val_if_fail(msginfo != NULL, NULL);
1273
1274         if (!account)
1275                 account = cur_account;
1276         g_return_val_if_fail(account != NULL, NULL);
1277
1278         compose = compose_create(account, COMPOSE_REDIRECT);
1279         ifactory = gtk_item_factory_from_widget(compose->menubar);
1280
1281         compose->replyinfo = NULL;
1282         compose->fwdinfo = NULL;
1283
1284         compose_show_first_last_header(compose, TRUE);
1285
1286         gtk_widget_grab_focus(compose->header_last->entry);
1287
1288         filename = procmsg_get_message_file(msginfo);
1289         if (filename == NULL)
1290                 return NULL;
1291
1292         compose->redirect_filename = filename;
1293         
1294         compose_attach_parts(compose, msginfo);
1295
1296         if (msginfo->subject)
1297                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1298                                    msginfo->subject);
1299         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1300
1301         gtk_stext_freeze(GTK_STEXT(compose->text));
1302         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL);
1303         gtk_editable_set_editable(GTK_EDITABLE(compose->text), FALSE);
1304         gtk_stext_thaw(GTK_STEXT(compose->text));
1305
1306         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1307         menu_set_sensitive(ifactory, "/Add...", FALSE);
1308         menu_set_sensitive(ifactory, "/Remove", FALSE);
1309         menu_set_sensitive(ifactory, "/Property...", FALSE);
1310
1311         ifactory = gtk_item_factory_from_widget(compose->menubar);
1312         menu_set_sensitive(ifactory, "/File/Insert file", FALSE);
1313         menu_set_sensitive(ifactory, "/File/Attach file", FALSE);
1314         menu_set_sensitive(ifactory, "/File/Insert signature", FALSE);
1315         menu_set_sensitive(ifactory, "/Edit", FALSE);
1316         menu_set_sensitive(ifactory, "/Message/Save to draft folder", FALSE);
1317         menu_set_sensitive(ifactory, "/Message/Save and keep editing", FALSE);
1318 #if USE_GPGME
1319         menu_set_sensitive(ifactory, "/Message/Sign", FALSE);
1320         menu_set_sensitive(ifactory, "/Message/Encrypt", FALSE);
1321         menu_set_sensitive(ifactory, "/Message/Mode/MIME", FALSE);
1322         menu_set_sensitive(ifactory, "/Message/Mode/Inline", FALSE);
1323 #endif
1324         menu_set_sensitive(ifactory, "/Message/Priority", FALSE);
1325         menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE);
1326         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1327         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1328         
1329         gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1330         gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1331         gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1332         gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1333         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1334         gtk_widget_set_sensitive(compose->toolbar->linewrap_btn, FALSE);
1335
1336         return compose;
1337 }
1338
1339 GList *compose_get_compose_list(void)
1340 {
1341         return compose_list;
1342 }
1343
1344 void compose_entry_append(Compose *compose, const gchar *address,
1345                           ComposeEntryType type)
1346 {
1347         gchar *header;
1348
1349         if (!address || *address == '\0') return;
1350
1351 #if 0 /* NEW COMPOSE GUI */
1352         switch (type) {
1353         case COMPOSE_CC:
1354                 entry = GTK_ENTRY(compose->cc_entry);
1355                 break;
1356         case COMPOSE_BCC:
1357                 entry = GTK_ENTRY(compose->bcc_entry);
1358                 break;
1359         case COMPOSE_NEWSGROUPS:
1360                 entry = GTK_ENTRY(compose->newsgroups_entry);
1361                 break;
1362         case COMPOSE_TO:
1363         default:
1364                 entry = GTK_ENTRY(compose->to_entry);
1365                 break;
1366         }
1367
1368         text = gtk_entry_get_text(entry);
1369         if (*text != '\0')
1370                 gtk_entry_append_text(entry, ", ");
1371         gtk_entry_append_text(entry, address);
1372 #endif
1373
1374         switch (type) {
1375         case COMPOSE_CC:
1376                 header = N_("Cc:");
1377                 break;
1378         case COMPOSE_BCC:
1379                 header = N_("Bcc:");
1380                 break;
1381         case COMPOSE_REPLYTO:
1382                 header = N_("Reply-To:");
1383                 break;
1384         case COMPOSE_NEWSGROUPS:
1385                 header = N_("Newsgroups:");
1386                 break;
1387         case COMPOSE_FOLLOWUPTO:
1388                 header = N_( "Followup-To:");
1389                 break;
1390         case COMPOSE_TO:
1391         default:
1392                 header = N_("To:");
1393                 break;
1394         }
1395         header = prefs_common.trans_hdr ? gettext(header) : header;
1396
1397         compose_add_header_entry(compose, header, (gchar *)address);
1398 }
1399
1400 void compose_entry_select (Compose *compose, const gchar *mailto)
1401 {
1402         GSList *header_list;
1403                 
1404         for (header_list = compose->header_list; header_list != NULL; header_list = header_list->next) {
1405                 GtkEntry * entry = GTK_ENTRY(((ComposeHeaderEntry *)header_list->data)->entry);
1406
1407                 if (gtk_entry_get_text(entry) && !g_strcasecmp(gtk_entry_get_text(entry), mailto)) {
1408                         gtk_entry_select_region(entry, 0, -1);
1409                         gtk_widget_grab_focus(GTK_WIDGET(entry));
1410                 }
1411         }
1412 }
1413
1414 void compose_toolbar_cb(gint action, gpointer data)
1415 {
1416         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1417         Compose *compose = (Compose*)toolbar_item->parent;
1418         
1419         g_return_if_fail(compose != NULL);
1420
1421         switch(action) {
1422         case A_SEND:
1423                 compose_send_cb(compose, 0, NULL);
1424                 break;
1425         case A_SENDL:
1426                 compose_send_later_cb(compose, 0, NULL);
1427                 break;
1428         case A_DRAFT:
1429                 compose_draft_cb(compose, 0, NULL);
1430                 break;
1431         case A_INSERT:
1432                 compose_insert_file_cb(compose, 0, NULL);
1433                 break;
1434         case A_ATTACH:
1435                 compose_attach_cb(compose, 0, NULL);
1436                 break;
1437         case A_SIG:
1438                 compose_insert_sig(compose);
1439                 break;
1440         case A_EXTEDITOR:
1441                 compose_ext_editor_cb(compose, 0, NULL);
1442                 break;
1443         case A_LINEWRAP:
1444                 compose_wrap_line(compose);
1445                 break;
1446         case A_ADDRBOOK:
1447                 compose_address_cb(compose, 0, NULL);
1448                 break;
1449         default:
1450                 break;
1451         }
1452 }
1453
1454 static void compose_entries_set(Compose *compose, const gchar *mailto)
1455 {
1456         gchar *to = NULL;
1457         gchar *cc = NULL;
1458         gchar *bcc = NULL;
1459         gchar *subject = NULL;
1460         gchar *body = NULL;
1461
1462         scan_mailto_url(mailto, &to, &cc, &bcc, &subject, &body);
1463
1464         if (to)
1465                 compose_entry_append(compose, to, COMPOSE_TO);
1466         if (cc)
1467                 compose_entry_append(compose, cc, COMPOSE_CC);
1468         if (bcc)
1469                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1470         if (subject)
1471                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1472         if (body) {
1473                 gtk_stext_insert(GTK_STEXT(compose->text),
1474                                 NULL, NULL, NULL, body, -1);
1475                 gtk_stext_insert(GTK_STEXT(compose->text),
1476                                 NULL, NULL, NULL, "\n", 1);
1477         }
1478
1479         g_free(to);
1480         g_free(cc);
1481         g_free(bcc);
1482         g_free(subject);
1483         g_free(body);
1484 }
1485
1486 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1487 {
1488         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1489                                        {"Cc:",          NULL, FALSE},
1490                                        {"References:",  NULL, FALSE},
1491                                        {"Bcc:",         NULL, FALSE},
1492                                        {"Newsgroups:",  NULL, FALSE},
1493                                        {"Followup-To:", NULL, FALSE},
1494                                        {"List-Post:",   NULL, FALSE},
1495                                        {"X-Priority:",  NULL, FALSE},
1496                                        {NULL,           NULL, FALSE}};
1497
1498         enum
1499         {
1500                 H_REPLY_TO      = 0,
1501                 H_CC            = 1,
1502                 H_REFERENCES    = 2,
1503                 H_BCC           = 3,
1504                 H_NEWSGROUPS    = 4,
1505                 H_FOLLOWUP_TO   = 5,
1506                 H_LIST_POST     = 6,
1507                 H_X_PRIORITY    = 7
1508         };
1509
1510         FILE *fp;
1511
1512         g_return_val_if_fail(msginfo != NULL, -1);
1513
1514         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1515         procheader_get_header_fields(fp, hentry);
1516         fclose(fp);
1517
1518         if (hentry[H_REPLY_TO].body != NULL) {
1519                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1520                 compose->replyto = hentry[H_REPLY_TO].body;
1521                 hentry[H_REPLY_TO].body = NULL;
1522         }
1523         if (hentry[H_CC].body != NULL) {
1524                 conv_unmime_header_overwrite(hentry[H_CC].body);
1525                 compose->cc = hentry[H_CC].body;
1526                 hentry[H_CC].body = NULL;
1527         }
1528         if (hentry[H_REFERENCES].body != NULL) {
1529                 if (compose->mode == COMPOSE_REEDIT)
1530                         compose->references = hentry[H_REFERENCES].body;
1531                 else {
1532                         compose->references = compose_parse_references
1533                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1534                         g_free(hentry[H_REFERENCES].body);
1535                 }
1536                 hentry[H_REFERENCES].body = NULL;
1537         }
1538         if (hentry[H_BCC].body != NULL) {
1539                 if (compose->mode == COMPOSE_REEDIT) {
1540                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1541                         compose->bcc = hentry[H_BCC].body;
1542                 } else
1543                         g_free(hentry[H_BCC].body);
1544                 hentry[H_BCC].body = NULL;
1545         }
1546         if (hentry[H_NEWSGROUPS].body != NULL) {
1547                 conv_unmime_header_overwrite(hentry[H_NEWSGROUPS].body);
1548                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1549                 hentry[H_NEWSGROUPS].body = NULL;
1550         }
1551         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1552                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1553                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1554                 hentry[H_FOLLOWUP_TO].body = NULL;
1555         }
1556         if (hentry[H_LIST_POST].body != NULL) {
1557                 gchar *to = NULL;
1558
1559                 extract_address(hentry[H_LIST_POST].body);
1560                 if (hentry[H_LIST_POST].body[0] != '\0') {
1561                         scan_mailto_url(hentry[H_LIST_POST].body,
1562                                         &to, NULL, NULL, NULL, NULL);
1563                         if (to) {
1564                                 g_free(compose->ml_post);
1565                                 compose->ml_post = to;
1566                         }
1567                 }
1568                 g_free(hentry[H_LIST_POST].body);
1569                 hentry[H_LIST_POST].body = NULL;
1570         }
1571
1572         /* CLAWS - X-Priority */
1573         if (compose->mode == COMPOSE_REEDIT)
1574                 if (hentry[H_X_PRIORITY].body != NULL) {
1575                         gint priority;
1576                         
1577                         priority = atoi(hentry[H_X_PRIORITY].body);
1578                         g_free(hentry[H_X_PRIORITY].body);
1579                         
1580                         hentry[H_X_PRIORITY].body = NULL;
1581                         
1582                         if (priority < PRIORITY_HIGHEST || 
1583                             priority > PRIORITY_LOWEST)
1584                                 priority = PRIORITY_NORMAL;
1585                         
1586                         compose->priority =  priority;
1587                 }
1588  
1589         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1590                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1591         else if (compose->mode != COMPOSE_REEDIT &&
1592                  msginfo->msgid && *msginfo->msgid) {
1593                 compose->inreplyto = g_strdup(msginfo->msgid);
1594
1595                 if (!compose->references) {
1596                         if (msginfo->inreplyto && *msginfo->inreplyto)
1597                                 compose->references =
1598                                         g_strdup_printf("<%s>\n\t<%s>",
1599                                                         msginfo->inreplyto,
1600                                                         msginfo->msgid);
1601                         else
1602                                 compose->references =
1603                                         g_strconcat("<", msginfo->msgid, ">",
1604                                                     NULL);
1605                 }
1606         }
1607
1608         return 0;
1609 }
1610
1611 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1612 {
1613         GSList *ref_id_list, *cur;
1614         GString *new_ref;
1615         gchar *new_ref_str;
1616
1617         ref_id_list = references_list_append(NULL, ref);
1618         if (!ref_id_list) return NULL;
1619         if (msgid && *msgid)
1620                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1621
1622         for (;;) {
1623                 gint len = 0;
1624
1625                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1626                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1627                         len += strlen((gchar *)cur->data) + 5;
1628
1629                 if (len > MAX_REFERENCES_LEN) {
1630                         /* remove second message-ID */
1631                         if (ref_id_list && ref_id_list->next &&
1632                             ref_id_list->next->next) {
1633                                 g_free(ref_id_list->next->data);
1634                                 ref_id_list = g_slist_remove
1635                                         (ref_id_list, ref_id_list->next->data);
1636                         } else {
1637                                 slist_free_strings(ref_id_list);
1638                                 g_slist_free(ref_id_list);
1639                                 return NULL;
1640                         }
1641                 } else
1642                         break;
1643         }
1644
1645         new_ref = g_string_new("");
1646         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1647                 if (new_ref->len > 0)
1648                         g_string_append(new_ref, "\n\t");
1649                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1650         }
1651
1652         slist_free_strings(ref_id_list);
1653         g_slist_free(ref_id_list);
1654
1655         new_ref_str = new_ref->str;
1656         g_string_free(new_ref, FALSE);
1657
1658         return new_ref_str;
1659 }
1660
1661 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1662                                 const gchar *fmt, const gchar *qmark,
1663                                 const gchar *body)
1664 {
1665         GtkSText *text = GTK_STEXT(compose->text);
1666         static MsgInfo dummyinfo;
1667         gchar *quote_str = NULL;
1668         gchar *buf;
1669         gchar *p, *lastp;
1670         gint len;
1671
1672         if (!msginfo)
1673                 msginfo = &dummyinfo;
1674
1675         if (qmark != NULL) {
1676                 quote_fmt_init(msginfo, NULL, NULL);
1677                 quote_fmt_scan_string(qmark);
1678                 quote_fmt_parse();
1679
1680                 buf = quote_fmt_get_buffer();
1681                 if (buf == NULL)
1682                         alertpanel_error(_("Quote mark format error."));
1683                 else
1684                         Xstrdup_a(quote_str, buf, return NULL)
1685         }
1686
1687         if (fmt && *fmt != '\0') {
1688                 quote_fmt_init(msginfo, quote_str, body);
1689                 quote_fmt_scan_string(fmt);
1690                 quote_fmt_parse();
1691
1692                 buf = quote_fmt_get_buffer();
1693                 if (buf == NULL) {
1694                         alertpanel_error(_("Message reply/forward format error."));
1695                         return NULL;
1696                 }
1697         } else
1698                 buf = "";
1699
1700         gtk_stext_freeze(text);
1701
1702         for (p = buf; *p != '\0'; ) {
1703                 lastp = strchr(p, '\n');
1704                 len = lastp ? lastp - p + 1 : -1;
1705                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1706                 if (lastp)
1707                         p = lastp + 1;
1708                 else
1709                         break;
1710         }
1711
1712         gtk_stext_thaw(text);
1713
1714         return buf;
1715 }
1716
1717 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1718                                     gboolean to_all, gboolean to_ml,
1719                                     gboolean to_sender,
1720                                     gboolean followup_and_reply_to)
1721 {
1722         GSList *cc_list = NULL;
1723         GSList *cur;
1724         gchar *from = NULL;
1725         gchar *replyto = NULL;
1726         GHashTable *to_table;
1727
1728         g_return_if_fail(compose->account != NULL);
1729         g_return_if_fail(msginfo != NULL);
1730
1731         if (compose->account->protocol != A_NNTP) {
1732                 if (!compose->replyto && to_ml && compose->ml_post
1733                     && !(msginfo->folder && msginfo->folder->prefs->enable_default_reply_to))
1734                         compose_entry_append(compose,
1735                                            compose->ml_post,
1736                                            COMPOSE_TO);
1737                 else if (!(to_all || to_sender)
1738                          && msginfo->folder
1739                          && msginfo->folder->prefs->enable_default_reply_to) {
1740                         compose_entry_append(compose,
1741                             msginfo->folder->prefs->default_reply_to,
1742                             COMPOSE_TO);
1743                 } else
1744                         compose_entry_append(compose,
1745                                  (compose->replyto && !to_sender)
1746                                   ? compose->replyto :
1747                                   msginfo->from ? msginfo->from : "",
1748                                   COMPOSE_TO);
1749         } else {
1750                 if (to_sender || (compose->followup_to && 
1751                         !strncmp(compose->followup_to, "poster", 6)))
1752                         compose_entry_append
1753                                 (compose, 
1754                                  (compose->replyto ? compose->replyto :
1755                                         msginfo->from ? msginfo->from : ""),
1756                                  COMPOSE_TO);
1757                                  
1758                 else if (followup_and_reply_to || to_all) {
1759                         compose_entry_append
1760                                 (compose,
1761                                  (compose->replyto ? compose->replyto :
1762                                  msginfo->from ? msginfo->from : ""),
1763                                  COMPOSE_TO);                           
1764                 
1765                         compose_entry_append
1766                                 (compose,
1767                                  compose->followup_to ? compose->followup_to :
1768                                  compose->newsgroups ? compose->newsgroups : "",
1769                                  COMPOSE_NEWSGROUPS);
1770                 } 
1771                 else 
1772                         compose_entry_append
1773                                 (compose,
1774                                  compose->followup_to ? compose->followup_to :
1775                                  compose->newsgroups ? compose->newsgroups : "",
1776                                  COMPOSE_NEWSGROUPS);
1777         }
1778
1779         if (msginfo->subject && *msginfo->subject) {
1780                 gchar *buf, *buf2, *p;
1781
1782                 buf = g_strdup(msginfo->subject);
1783                 while (!strncasecmp(buf, "Re:", 3)) {
1784                         p = buf + 3;
1785                         while (isspace(*p)) p++;
1786                         memmove(buf, p, strlen(p) + 1);
1787                 }
1788
1789                 buf2 = g_strdup_printf("Re: %s", buf);
1790                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1791                 g_free(buf2);
1792                 g_free(buf);
1793         } else
1794                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1795
1796         if (to_ml && compose->ml_post) return;
1797         if (!to_all || compose->account->protocol == A_NNTP) return;
1798
1799         if (compose->replyto) {
1800                 Xstrdup_a(replyto, compose->replyto, return);
1801                 extract_address(replyto);
1802         }
1803         if (msginfo->from) {
1804                 Xstrdup_a(from, msginfo->from, return);
1805                 extract_address(from);
1806         }
1807
1808         if (replyto && from)
1809                 cc_list = address_list_append_with_comments(cc_list, from);
1810         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
1811         cc_list = address_list_append_with_comments(cc_list, compose->cc);
1812
1813         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1814         if (replyto)
1815                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
1816         if (compose->account)
1817                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
1818                                     GINT_TO_POINTER(1));
1819
1820         /* remove address on To: and that of current account */
1821         for (cur = cc_list; cur != NULL; ) {
1822                 GSList *next = cur->next;
1823                 gchar *addr;
1824
1825                 addr = g_strdup(cur->data);
1826                 extract_address(addr);
1827
1828                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
1829                         cc_list = g_slist_remove(cc_list, cur->data);
1830                 else
1831                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
1832
1833                 cur = next;
1834         }
1835         hash_free_strings(to_table);
1836         g_hash_table_destroy(to_table);
1837
1838         if (cc_list) {
1839                 for (cur = cc_list; cur != NULL; cur = cur->next)
1840                         compose_entry_append(compose, (gchar *)cur->data,
1841                                              COMPOSE_CC);
1842                 slist_free_strings(cc_list);
1843                 g_slist_free(cc_list);
1844         }
1845 }
1846
1847 #define SET_ENTRY(entry, str) \
1848 { \
1849         if (str && *str) \
1850                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1851 }
1852
1853 #define SET_ADDRESS(type, str) \
1854 { \
1855         if (str && *str) \
1856                 compose_entry_append(compose, str, type); \
1857 }
1858
1859 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1860 {
1861         g_return_if_fail(msginfo != NULL);
1862
1863         SET_ENTRY(subject_entry, msginfo->subject);
1864         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1865         SET_ADDRESS(COMPOSE_CC, compose->cc);
1866         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1867         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1868         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
1869         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
1870
1871         compose_update_priority_menu_item(compose);
1872 #if USE_GPGME   
1873         compose_update_gnupg_mode_menu_item(compose);
1874 #endif
1875         compose_show_first_last_header(compose, TRUE);
1876
1877 }
1878
1879 #undef SET_ENTRY
1880 #undef SET_ADDRESS
1881
1882 static void compose_insert_sig(Compose *compose)
1883 {
1884         static gchar *default_sigfile;
1885         gchar *sigfile = NULL;
1886
1887         g_return_if_fail(compose->account != NULL);
1888
1889         if (compose->account->sig_type == SIG_FILE) {
1890                 if (compose->account->sig_path)
1891                         sigfile = compose->account->sig_path;
1892                 else {
1893                         if (!default_sigfile)
1894                                 default_sigfile = g_strconcat
1895                                         (get_home_dir(), G_DIR_SEPARATOR_S,
1896                                          DEFAULT_SIGNATURE, NULL);
1897                         sigfile = default_sigfile;
1898                 }
1899
1900                 if (!is_file_or_fifo_exist(sigfile)) {
1901                         g_warning("can't open signature file: %s\n", sigfile);
1902                         return;
1903                 }
1904         }
1905
1906         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1907         if (compose->account->sig_sep) {
1908                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1909                                  compose->account->sig_sep, -1);
1910                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1911                                 "\n", 1);
1912         }
1913
1914         if (compose->account->sig_type == SIG_COMMAND) {
1915                 if (compose->account->sig_path)
1916                         compose_insert_command_output
1917                                 (compose, compose->account->sig_path);
1918         } else
1919                 compose_insert_file(compose, sigfile);
1920 }
1921
1922 static void compose_insert_file(Compose *compose, const gchar *file)
1923 {
1924         GtkSText *text = GTK_STEXT(compose->text);
1925         gchar buf[BUFFSIZE];
1926         gint len;
1927         FILE *fp;
1928
1929         g_return_if_fail(file != NULL);
1930
1931         if ((fp = fopen(file, "rb")) == NULL) {
1932                 FILE_OP_ERROR(file, "fopen");
1933                 return;
1934         }
1935
1936         gtk_stext_freeze(text);
1937
1938         while (fgets(buf, sizeof(buf), fp) != NULL) {
1939                 /* strip <CR> if DOS/Windows file,
1940                    replace <CR> with <LF> if Macintosh file. */
1941                 strcrchomp(buf);
1942                 len = strlen(buf);
1943                 if (len > 0 && buf[len - 1] != '\n') {
1944                         while (--len >= 0)
1945                                 if (buf[len] == '\r') buf[len] = '\n';
1946                 }
1947                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1948         }
1949
1950         gtk_stext_thaw(text);
1951
1952         fclose(fp);
1953 }
1954
1955 static void compose_insert_command_output(Compose *compose,
1956                                           const gchar *cmdline)
1957 {
1958         GtkSText *text = GTK_STEXT(compose->text);
1959         gchar buf[BUFFSIZE];
1960         gint len;
1961         FILE *fp;
1962
1963         g_return_if_fail(cmdline != NULL);
1964
1965         if ((fp = popen(cmdline, "r")) == NULL) {
1966                 FILE_OP_ERROR(cmdline, "popen");
1967                 return;
1968         }
1969
1970         gtk_stext_freeze(text);
1971
1972         while (fgets(buf, sizeof(buf), fp) != NULL) {
1973                 strcrchomp(buf);
1974                 len = strlen(buf);
1975                 if (len > 0 && buf[len - 1] != '\n') {
1976                         while (--len >= 0)
1977                                 if (buf[len] == '\r') buf[len] = '\n';
1978                 }
1979                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1980         }
1981
1982         gtk_stext_thaw(text);
1983
1984         pclose(fp);
1985 }
1986
1987 static void compose_attach_append(Compose *compose, const gchar *file,
1988                                   const gchar *filename,
1989                                   const gchar *content_type)
1990 {
1991         AttachInfo *ainfo;
1992         gchar *text[N_ATTACH_COLS];
1993         FILE *fp;
1994         off_t size;
1995         gint row;
1996
1997         if (!is_file_exist(file)) {
1998                 g_warning("File %s doesn't exist\n", file);
1999                 return;
2000         }
2001         if ((size = get_file_size(file)) < 0) {
2002                 g_warning("Can't get file size of %s\n", file);
2003                 return;
2004         }
2005         if (size == 0) {
2006                 alertpanel_notice(_("File %s is empty."), file);
2007                 return;
2008         }
2009         if ((fp = fopen(file, "rb")) == NULL) {
2010                 alertpanel_error(_("Can't read %s."), file);
2011                 return;
2012         }
2013         fclose(fp);
2014
2015 #if 0 /* NEW COMPOSE GUI */
2016         if (!compose->use_attach) {
2017                 GtkItemFactory *ifactory;
2018                 GtkWidget *menuitem;
2019
2020                 ifactory = gtk_item_factory_from_widget(compose->menubar);
2021                 menuitem = gtk_item_factory_get_item(ifactory,
2022                                                      "/View/Attachment");
2023                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2024                                                TRUE);
2025         }
2026 #endif
2027         ainfo = g_new0(AttachInfo, 1);
2028         ainfo->file = g_strdup(file);
2029
2030         if (content_type) {
2031                 ainfo->content_type = g_strdup(content_type);
2032                 if (!strcasecmp(content_type, "message/rfc822")) {
2033                         if (procmime_get_encoding_for_file(file) == ENC_7BIT)
2034                                 ainfo->encoding = ENC_7BIT;
2035                         else
2036                                 ainfo->encoding = ENC_8BIT;
2037                         ainfo->name = g_strdup_printf
2038                                 (_("Message: %s"),
2039                                  g_basename(filename ? filename : file));
2040                 } else {
2041                         if (!g_strncasecmp(content_type, "text", 4))
2042                                 ainfo->encoding =
2043                                         procmime_get_encoding_for_file(file);
2044                         else
2045                                 ainfo->encoding = ENC_BASE64;
2046                         ainfo->name = g_strdup
2047                                 (g_basename(filename ? filename : file));
2048                 }
2049         } else {
2050                 ainfo->content_type = procmime_get_mime_type(file);
2051                 if (!ainfo->content_type) {
2052                         ainfo->content_type =
2053                                 g_strdup("application/octet-stream");
2054                         ainfo->encoding = ENC_BASE64;
2055                 } else if (!g_strncasecmp(ainfo->content_type, "text", 4))
2056                         ainfo->encoding = procmime_get_encoding_for_file(file);
2057                 else
2058                         ainfo->encoding = ENC_BASE64;
2059                 ainfo->name = g_strdup(g_basename(filename ? filename : file)); 
2060         }
2061         ainfo->size = size;
2062
2063         text[COL_MIMETYPE] = ainfo->content_type;
2064         text[COL_SIZE] = to_human_readable(size);
2065         text[COL_NAME] = ainfo->name;
2066
2067         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
2068         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
2069 }
2070
2071 #define IS_FIRST_PART_TEXT(info) \
2072         ((info->mime_type == MIME_TEXT || info->mime_type == MIME_TEXT_HTML || \
2073           info->mime_type == MIME_TEXT_ENRICHED) || \
2074          (info->mime_type == MIME_MULTIPART && info->content_type && \
2075           !strcasecmp(info->content_type, "multipart/alternative") && \
2076           (info->children && \
2077            (info->children->mime_type == MIME_TEXT || \
2078             info->children->mime_type == MIME_TEXT_HTML || \
2079             info->children->mime_type == MIME_TEXT_ENRICHED))))
2080
2081 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2082 {
2083         MimeInfo *mimeinfo;
2084         MimeInfo *child;
2085         gchar *infile;
2086         gchar *outfile;
2087
2088         mimeinfo = procmime_scan_message(msginfo);
2089         if (!mimeinfo) return;
2090
2091         /* skip first text (presumably message body) */
2092         child = mimeinfo->children;
2093         if (!child || IS_FIRST_PART_TEXT(mimeinfo)) {
2094                 procmime_mimeinfo_free_all(mimeinfo);
2095                 return;
2096         }
2097
2098         if (IS_FIRST_PART_TEXT(child))
2099                 child = child->next;
2100
2101         infile = procmsg_get_message_file_path(msginfo);
2102
2103         while (child != NULL) {
2104                 if (child->children || child->mime_type == MIME_MULTIPART) {
2105                         child = procmime_mimeinfo_next(child);
2106                         continue;
2107                 }
2108                 if(child->parent && child->parent->parent
2109                 && !strcasecmp(child->parent->parent->content_type, "multipart/signed")
2110                 && child->mime_type == MIME_TEXT) {
2111                         /* this is the main text part of a signed message */
2112                         child = procmime_mimeinfo_next(child);
2113                         continue;
2114                 }
2115                 outfile = procmime_get_tmp_file_name(child);
2116                 if (procmime_get_part(outfile, infile, child) < 0)
2117                         g_warning("Can't get the part of multipart message.");
2118                 else if (compose->mode != COMPOSE_REEDIT || strcmp(child->content_type, "application/pgp-signature"))
2119                         compose_attach_append
2120                                 (compose, outfile,
2121                                  child->filename ? child->filename : child->name,
2122                                  child->content_type);
2123
2124                 child = child->next;
2125         }
2126
2127         g_free(infile);
2128         procmime_mimeinfo_free_all(mimeinfo);
2129 }
2130
2131 #undef IS_FIRST_PART_TEXT
2132
2133 #define GET_CHAR(pos, buf, len)                                              \
2134 {                                                                            \
2135         if (text->use_wchar)                                                 \
2136                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));    \
2137         else {                                                               \
2138                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
2139                 len = 1;                                                     \
2140         }                                                                    \
2141 }
2142
2143 #define DISP_WIDTH(len) \
2144         ((len > 2 && conv_get_current_charset() == C_UTF_8) ? 2 : \
2145          (len == 2 && conv_get_current_charset() == C_UTF_8) ? 1 : len)
2146
2147 #define INDENT_CHARS    ">|#"
2148 #define SPACE_CHARS     " \t"
2149
2150 static void compose_wrap_line(Compose *compose)
2151 {
2152         GtkSText *text = GTK_STEXT(compose->text);
2153         gint ch_len, last_ch_len;
2154         gchar cbuf[MB_LEN_MAX], last_ch;
2155         guint text_len;
2156         guint line_end;
2157         guint quoted;
2158         gint p_start, p_end;
2159         gint line_pos, cur_pos;
2160         gint line_len, cur_len;
2161
2162         gtk_stext_freeze(text);
2163
2164         text_len = gtk_stext_get_length(text);
2165
2166         /* check to see if the point is on the paragraph mark (empty line). */
2167         cur_pos = gtk_stext_get_point(text);
2168         GET_CHAR(cur_pos, cbuf, ch_len);
2169         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2170                 if (cur_pos == 0)
2171                         goto compose_end; /* on the paragraph mark */
2172                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
2173                 if (ch_len == 1 && *cbuf == '\n')
2174                         goto compose_end; /* on the paragraph mark */
2175         }
2176
2177         /* find paragraph start. */
2178         line_end = quoted = 0;
2179         for (p_start = cur_pos; p_start >= 0; --p_start) {
2180                 GET_CHAR(p_start, cbuf, ch_len);
2181                 if (ch_len == 1 && *cbuf == '\n') {
2182                         if (quoted)
2183                                 goto compose_end; /* quoted part */
2184                         if (line_end) {
2185                                 p_start += 2;
2186                                 break;
2187                         }
2188                         line_end = 1;
2189                 } else {
2190                         if (ch_len == 1 
2191                             && strchr(prefs_common.quote_chars, *cbuf))
2192                                 quoted = 1;
2193                         else if (ch_len != 1 || !isspace(*cbuf))
2194                                 quoted = 0;
2195
2196                         line_end = 0;
2197                 }
2198         }
2199         if (p_start < 0)
2200                 p_start = 0;
2201
2202         /* find paragraph end. */
2203         line_end = 0;
2204         for (p_end = cur_pos; p_end < text_len; p_end++) {
2205                 GET_CHAR(p_end, cbuf, ch_len);
2206                 if (ch_len == 1 && *cbuf == '\n') {
2207                         if (line_end) {
2208                                 p_end -= 1;
2209                                 break;
2210                         }
2211                         line_end = 1;
2212                 } else {
2213                         if (line_end && ch_len == 1 &&
2214                             strchr(prefs_common.quote_chars, *cbuf))
2215                                 goto compose_end; /* quoted part */
2216
2217                         line_end = 0;
2218                 }
2219         }
2220         if (p_end >= text_len)
2221                 p_end = text_len;
2222
2223         if (p_start >= p_end)
2224                 goto compose_end;
2225
2226         line_len = cur_len = 0;
2227         last_ch_len = 0;
2228         last_ch = '\0';
2229         line_pos = p_start;
2230         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2231                 guint space = 0;
2232
2233                 GET_CHAR(cur_pos, cbuf, ch_len);
2234
2235                 if (ch_len < 0) {
2236                         cbuf[0] = '\0';
2237                         ch_len = 1;
2238                 }
2239
2240                 if (ch_len == 1 && isspace(*cbuf))
2241                         space = 1;
2242
2243                 if (ch_len == 1 && *cbuf == '\n') {
2244                         guint replace = 0;
2245                         if (last_ch_len == 1 && !isspace(last_ch)) {
2246                                 if (cur_pos + 1 < p_end) {
2247                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2248                                         if (ch_len == 1 && !isspace(*cbuf))
2249                                                 replace = 1;
2250                                 }
2251                         }
2252                         gtk_stext_set_point(text, cur_pos + 1);
2253                         gtk_stext_backward_delete(text, 1);
2254                         if (replace) {
2255                                 gtk_stext_set_point(text, cur_pos);
2256                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2257                                 space = 1;
2258                         }
2259                         else {
2260                                 p_end--;
2261                                 cur_pos--;
2262                                 continue;
2263                         }
2264                 }
2265
2266                 last_ch_len = ch_len;
2267                 last_ch = *cbuf;
2268
2269                 if (space) {
2270                         line_pos = cur_pos + 1;
2271                         line_len = cur_len + ch_len;
2272                 }
2273
2274                 if (cur_len + DISP_WIDTH(ch_len) > prefs_common.linewrap_len &&
2275                     line_len > 0) {
2276                         gint tlen = ch_len;
2277
2278                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2279                         if (ch_len == 1 && isspace(*cbuf)) {
2280                                 gtk_stext_set_point(text, line_pos);
2281                                 gtk_stext_backward_delete(text, 1);
2282                                 p_end--;
2283                                 cur_pos--;
2284                                 line_pos--;
2285                                 cur_len--;
2286                                 line_len--;
2287                         }
2288                         ch_len = tlen;
2289
2290                         gtk_stext_set_point(text, line_pos);
2291                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2292                         p_end++;
2293                         cur_pos++;
2294                         line_pos++;
2295                         cur_len = cur_len - line_len + DISP_WIDTH(ch_len);
2296                         line_len = 0;
2297                         continue;
2298                 }
2299
2300                 if (ch_len > 1) {
2301                         line_pos = cur_pos + 1;
2302                         line_len = cur_len + DISP_WIDTH(ch_len);
2303                 }
2304                 cur_len += DISP_WIDTH(ch_len);
2305         }
2306
2307 compose_end:
2308         gtk_stext_thaw(text);
2309 }
2310
2311 #undef WRAP_DEBUG
2312 #ifdef WRAP_DEBUG
2313 /* Darko: used when I debug wrapping */
2314 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2315 {
2316         gint i, clen;
2317         gchar cbuf[MB_LEN_MAX];
2318
2319         printf("%d [", pos);
2320         for (i = pos; i < tlen; i++) {
2321                 GET_CHAR(i, cbuf, clen);
2322                 if (clen < 0) break;
2323                 if (breakoncr && clen == 1 && cbuf[0] == '\n')
2324                         break;
2325                 fwrite(cbuf, clen, 1, stdout);
2326         }
2327         printf("]\n");
2328 }
2329 #endif
2330
2331 typedef enum {
2332         WAIT_FOR_SPACE,
2333         WAIT_FOR_INDENT_CHAR,
2334         WAIT_FOR_INDENT_CHAR_OR_SPACE
2335 } IndentState;
2336
2337 /* return indent length, we allow:
2338    > followed by spaces/tabs
2339    | followed by spaces/tabs
2340    uppercase characters immediately followed by >,
2341    and the repeating sequences of the above */
2342 /* return indent length */
2343 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2344 {
2345         guint i_len = 0;
2346         guint i, ch_len, alnum_cnt = 0;
2347         IndentState state = WAIT_FOR_INDENT_CHAR;
2348         gchar cbuf[MB_LEN_MAX];
2349         gboolean is_space;
2350         gboolean is_indent;
2351
2352         for (i = start_pos; i < text_len; i++) {
2353                 GET_CHAR(i, cbuf, ch_len);
2354                 if (ch_len > 1)
2355                         break;
2356
2357                 if (cbuf[0] == '\n')
2358                         break;
2359
2360                 is_indent = strchr(prefs_common.quote_chars, cbuf[0]) ? TRUE : FALSE;
2361                 is_space = strchr(SPACE_CHARS, cbuf[0]) ? TRUE : FALSE;
2362
2363                 switch (state) {
2364                 case WAIT_FOR_SPACE:
2365                         if (is_space == FALSE)
2366                                 goto out;
2367                         state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2368                         break;
2369                 case WAIT_FOR_INDENT_CHAR_OR_SPACE:
2370                         if (is_indent == FALSE && is_space == FALSE &&
2371                             !isupper(cbuf[0]))
2372                                 goto out;
2373                         if (is_space == TRUE) {
2374                                 alnum_cnt = 0;
2375                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2376                         } else if (is_indent == TRUE) {
2377                                 alnum_cnt = 0;
2378                                 state = WAIT_FOR_SPACE;
2379                         } else {
2380                                 alnum_cnt++;
2381                                 state = WAIT_FOR_INDENT_CHAR;
2382                         }
2383                         break;
2384                 case WAIT_FOR_INDENT_CHAR:
2385                         if (is_indent == FALSE && !isupper(cbuf[0]))
2386                                 goto out;
2387                         if (is_indent == TRUE) {
2388                                 if (alnum_cnt > 0 
2389                                     && !strchr(prefs_common.quote_chars, cbuf[0]))
2390                                         goto out;
2391                                 alnum_cnt = 0;
2392                                 state = WAIT_FOR_SPACE;
2393                         } else {
2394                                 alnum_cnt++;
2395                         }
2396                         break;
2397                 }
2398
2399                 i_len++;
2400         }
2401
2402 out:
2403         if ((i_len > 0) && (state == WAIT_FOR_INDENT_CHAR))
2404                 i_len -= alnum_cnt;
2405
2406         return i_len;
2407 }
2408
2409 /* insert quotation string when line was wrapped */
2410 static guint ins_quote(GtkSText *text, guint indent_len,
2411                        guint prev_line_pos, guint text_len,
2412                        gchar *quote_fmt)
2413 {
2414         guint i, ins_len = 0;
2415         gchar ch;
2416
2417         if (indent_len) {
2418                 for (i = 0; i < indent_len; i++) {
2419                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2420                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2421                 }
2422                 ins_len = indent_len;
2423         }
2424
2425         return ins_len;
2426 }
2427
2428 /* check if we should join the next line */
2429 static gboolean join_next_line(GtkSText *text, guint start_pos, guint tlen,
2430                                guint prev_ilen, gboolean autowrap)
2431 {
2432         guint indent_len, ch_len;
2433         gboolean do_join = FALSE;
2434         gchar cbuf[MB_LEN_MAX];
2435
2436         indent_len = get_indent_length(text, start_pos, tlen);
2437
2438         if ((autowrap || indent_len > 0) && indent_len == prev_ilen) {
2439                 GET_CHAR(start_pos + indent_len, cbuf, ch_len);
2440                 if (ch_len > 0 && (cbuf[0] != '\n'))
2441                         do_join = TRUE;
2442         }
2443
2444         return do_join;
2445 }
2446
2447 static void compose_wrap_line_all(Compose *compose)
2448 {
2449         compose_wrap_line_all_full(compose, FALSE);
2450 }
2451
2452 #define STEXT_FREEZE() \
2453         if (!frozen) { gtk_stext_freeze(text); frozen = TRUE; }
2454
2455 static void compose_wrap_line_all_full(Compose *compose, gboolean autowrap)
2456 {
2457         GtkSText *text = GTK_STEXT(compose->text);
2458         guint tlen;
2459         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2460         gint line_len = 0, cur_len = 0;
2461         gint ch_len;
2462         gboolean is_new_line = TRUE, do_delete = FALSE;
2463         guint i_len = 0;
2464         gboolean linewrap_quote = TRUE;
2465         gboolean set_editable_pos = FALSE;
2466         gint editable_pos = 0;
2467         gboolean frozen = FALSE;
2468         guint linewrap_len = prefs_common.linewrap_len;
2469         gchar *qfmt = prefs_common.quotemark;
2470         gchar cbuf[MB_LEN_MAX];
2471
2472         tlen = gtk_stext_get_length(text);
2473
2474         for (; cur_pos < tlen; cur_pos++) {
2475                 /* mark position of new line - needed for quotation wrap */
2476                 if (is_new_line) {
2477                         if (linewrap_quote)
2478                                 i_len = get_indent_length(text, cur_pos, tlen);
2479
2480                         is_new_line = FALSE;
2481                         p_pos = cur_pos;
2482 #ifdef WRAP_DEBUG
2483                         g_print("new line i_len=%d p_pos=", i_len);
2484                         dump_text(text, p_pos, tlen, 1);
2485 #endif
2486                 }
2487
2488                 GET_CHAR(cur_pos, cbuf, ch_len);
2489
2490                 /* fix line length for tabs */
2491                 if (ch_len == 1 && *cbuf == '\t') {
2492                         guint tab_width = text->default_tab_width;
2493                         guint tab_offset = line_len % tab_width;
2494
2495 #ifdef WRAP_DEBUG
2496                         g_print("found tab at pos=%d line_len=%d ", cur_pos,
2497                                 line_len);
2498 #endif
2499                         if (tab_offset) {
2500                                 line_len += tab_width - tab_offset - 1;
2501                                 cur_len = line_len;
2502                         }
2503 #ifdef WRAP_DEBUG
2504                         printf("new_len=%d\n", line_len);
2505 #endif
2506                 }
2507
2508                 /* we have encountered line break */
2509                 if (ch_len == 1 && *cbuf == '\n') {
2510                         gint clen;
2511                         gchar cb[MB_LEN_MAX];
2512
2513                         /* should we join the next line */
2514                         if ((autowrap || i_len != cur_len) && do_delete &&
2515                             join_next_line
2516                                 (text, cur_pos + 1, tlen, i_len, autowrap))
2517                                 do_delete = TRUE;
2518                         else
2519                                 do_delete = FALSE;
2520
2521 #ifdef WRAP_DEBUG
2522                         g_print("found CR at %d do_del is %d next line is ",
2523                                cur_pos, do_delete);
2524                         dump_text(text, cur_pos + 1, tlen, 1);
2525 #endif
2526
2527                         /* skip delete if it is continuous URL */
2528                         if (do_delete && (line_pos - p_pos <= i_len) &&
2529                             gtk_stext_is_uri_string(text, line_pos, tlen))
2530                                 do_delete = FALSE;
2531
2532 #ifdef WRAP_DEBUG
2533                         g_print("l_len=%d wrap_len=%d do_del=%d\n",
2534                                 line_len, linewrap_len, do_delete);
2535 #endif
2536                         /* should we delete to perform smart wrapping */
2537                         if (line_len < linewrap_len && do_delete) {
2538                                 STEXT_FREEZE();
2539                                 /* get rid of newline */
2540                                 gtk_stext_set_point(text, cur_pos);
2541                                 gtk_stext_forward_delete(text, 1);
2542                                 tlen--;
2543
2544                                 /* if text starts with quote fmt or with
2545                                    indent string, delete them */
2546                                 if (i_len) {
2547                                         guint ilen;
2548                                         ilen =  gtk_stext_str_compare_n
2549                                                 (text, cur_pos, p_pos, i_len,
2550                                                  tlen);
2551                                         if (ilen) {
2552                                                 gtk_stext_forward_delete
2553                                                         (text, ilen);
2554                                                 tlen -= ilen;
2555                                         }
2556                                 }
2557
2558                                 GET_CHAR(cur_pos, cb, clen);
2559
2560                                 /* insert space if it's alphanumeric */
2561                                 if ((cur_pos != line_pos) &&
2562                                     ((clen > 1) || isalnum(cb[0]))) {
2563                                         gtk_stext_insert(text, NULL, NULL,
2564                                                         NULL, " ", 1);
2565                                         tlen++;
2566                                 }
2567
2568                                 /* and start over with current line */
2569                                 cur_pos = p_pos - 1;
2570                                 line_pos = cur_pos;
2571                                 line_len = cur_len = 0;
2572                                 do_delete = FALSE;
2573                                 is_new_line = TRUE;
2574 #ifdef WRAP_DEBUG
2575                                 g_print("after delete l_pos=");
2576                                 dump_text(text, line_pos, tlen, 1);
2577 #endif
2578                                 /* move beginning of line if we are on LF */
2579                                 GET_CHAR(line_pos, cb, clen);
2580                                 if (clen == 1 && *cb == '\n')
2581                                         line_pos++;
2582 #ifdef WRAP_DEBUG
2583                                 g_print("new line_pos=%d\n", line_pos);
2584 #endif
2585
2586                                 continue;
2587                         }
2588
2589                         /* mark new line beginning */
2590                         line_pos = cur_pos + 1;
2591                         line_len = cur_len = 0;
2592                         do_delete = FALSE;
2593                         is_new_line = TRUE;
2594                         continue;
2595                 }
2596
2597                 if (ch_len < 0) {
2598                         cbuf[0] = '\0';
2599                         ch_len = 1;
2600                 }
2601
2602                 /* possible line break */
2603                 if (ch_len == 1 && isspace(*cbuf)) {
2604                         line_pos = cur_pos + 1;
2605                         line_len = cur_len + ch_len;
2606                 }
2607
2608                 /* are we over wrapping length set in preferences ? */
2609                 if (cur_len + DISP_WIDTH(ch_len) > linewrap_len) {
2610                         gint clen;
2611
2612 #ifdef WRAP_DEBUG
2613                         g_print("should wrap cur_pos=%d ", cur_pos);
2614                         dump_text(text, p_pos, tlen, 1);
2615                         dump_text(text, line_pos, tlen, 1);
2616 #endif
2617                         /* force wrapping if it is one long word but not URL */
2618                         if (line_pos - p_pos <= i_len)
2619                                 if (!gtk_stext_is_uri_string
2620                                     (text, line_pos, tlen))
2621                                         line_pos = cur_pos - 1;
2622 #ifdef WRAP_DEBUG
2623                         g_print("new line_pos=%d\n", line_pos);
2624 #endif
2625
2626                         GET_CHAR(line_pos - 1, cbuf, clen);
2627
2628                         /* if next character is space delete it */
2629                         if (clen == 1 && isspace(*cbuf)) {
2630                                 if (p_pos + i_len != line_pos ||
2631                                     !gtk_stext_is_uri_string
2632                                         (text, line_pos, tlen)) {
2633                                         STEXT_FREEZE();
2634                                         /* workaround for correct cursor
2635                                            position */
2636                                         if (set_editable_pos == FALSE) {
2637                                                 editable_pos = gtk_editable_get_position(GTK_EDITABLE(text));
2638                                                 if (editable_pos == line_pos)
2639                                                         set_editable_pos = TRUE;
2640                                         }
2641                                         gtk_stext_set_point(text, line_pos);
2642                                         gtk_stext_backward_delete(text, 1);
2643                                         tlen--;
2644                                         cur_pos--;
2645                                         line_pos--;
2646                                         cur_len--;
2647                                         line_len--;
2648                                 }
2649                         }
2650
2651                         /* if it is URL at beginning of line don't wrap */
2652                         if (p_pos + i_len == line_pos &&
2653                             gtk_stext_is_uri_string(text, line_pos, tlen)) {
2654 #ifdef WRAP_DEBUG
2655                                 g_print("found URL at ");
2656                                 dump_text(text, line_pos, tlen, 1);
2657 #endif
2658                                 continue;
2659                         }
2660
2661                         /* insert CR */
2662                         STEXT_FREEZE();
2663                         gtk_stext_set_point(text, line_pos);
2664                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2665                         /* gtk_stext_compact_buffer(text); */
2666                         tlen++;
2667                         line_pos++;
2668                         /* for loop will increase it */
2669                         cur_pos = line_pos - 1;
2670                         /* start over with current line */
2671                         is_new_line = TRUE;
2672                         line_len = cur_len = 0;
2673                         if (autowrap || i_len > 0)
2674                                 do_delete = TRUE;
2675                         else
2676                                 do_delete = FALSE;
2677 #ifdef WRAP_DEBUG
2678                         g_print("after CR insert ");
2679                         dump_text(text, line_pos, tlen, 1);
2680                         dump_text(text, cur_pos, tlen, 1);
2681 #endif
2682
2683                         /* should we insert quotation ? */
2684                         if (linewrap_quote && i_len) {
2685                                 /* only if line is not already quoted  */
2686                                 if (!gtk_stext_str_compare
2687                                         (text, line_pos, tlen, qfmt)) {
2688                                         guint ins_len;
2689
2690                                         if (line_pos - p_pos > i_len) {
2691                                                 ins_len = ins_quote
2692                                                         (text, i_len, p_pos,
2693                                                          tlen, qfmt);
2694                                                 tlen += ins_len;
2695                                         }
2696 #ifdef WRAP_DEBUG
2697                                         g_print("after quote insert ");
2698                                         dump_text(text, line_pos, tlen, 1);
2699 #endif
2700                                 }
2701                         }
2702                         continue;
2703                 }
2704
2705                 if (ch_len > 1) {
2706                         line_pos = cur_pos + 1;
2707                         line_len = cur_len + DISP_WIDTH(ch_len);
2708                 }
2709                 /* advance to next character in buffer */
2710                 cur_len += DISP_WIDTH(ch_len);
2711         }
2712
2713         if (frozen)
2714                 gtk_stext_thaw(text);
2715
2716         if (set_editable_pos && editable_pos <= tlen)
2717                 gtk_editable_set_position(GTK_EDITABLE(text), editable_pos);
2718 }
2719
2720 #undef STEXT_FREEZE
2721 #undef GET_CHAR
2722
2723 static void compose_set_title(Compose *compose)
2724 {
2725         gchar *str;
2726         gchar *edited;
2727
2728         edited = compose->modified ? _(" [Edited]") : "";
2729         if (compose->account && compose->account->address)
2730                 str = g_strdup_printf(_("%s - Compose message%s"),
2731                                       compose->account->address, edited);
2732         else
2733                 str = g_strdup_printf(_("Compose message%s"), edited);
2734         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2735         g_free(str);
2736 }
2737
2738 /**
2739  * compose_current_mail_account:
2740  * 
2741  * Find a current mail account (the currently selected account, or the
2742  * default account, if a news account is currently selected).  If a
2743  * mail account cannot be found, display an error message.
2744  * 
2745  * Return value: Mail account, or NULL if not found.
2746  **/
2747 static PrefsAccount *
2748 compose_current_mail_account(void)
2749 {
2750         PrefsAccount *ac;
2751
2752         if (cur_account && cur_account->protocol != A_NNTP)
2753                 ac = cur_account;
2754         else {
2755                 ac = account_get_default();
2756                 if (!ac || ac->protocol == A_NNTP) {
2757                         alertpanel_error(_("Account for sending mail is not specified.\n"
2758                                            "Please select a mail account before sending."));
2759                         return NULL;
2760                 }
2761         }
2762         return ac;
2763 }
2764
2765 static void compose_select_account(Compose *compose, PrefsAccount *account)
2766 {
2767         GtkWidget *menuitem;
2768         GtkItemFactory *ifactory;
2769
2770         g_return_if_fail(account != NULL);
2771
2772         compose->account = account;
2773
2774         compose_set_title(compose);
2775
2776         ifactory = gtk_item_factory_from_widget(compose->menubar);
2777 #if 0
2778         if (account->protocol == A_NNTP) {
2779                 gtk_widget_show(compose->newsgroups_hbox);
2780                 gtk_widget_show(compose->newsgroups_entry);
2781                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 4);
2782                 compose->use_newsgroups = TRUE;
2783
2784                 menuitem = gtk_item_factory_get_item(ifactory, "/View/To");
2785                 gtk_check_menu_item_set_active
2786                         (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
2787                 gtk_widget_set_sensitive(menuitem, TRUE);
2788                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
2789                 gtk_check_menu_item_set_active
2790                         (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
2791                 gtk_widget_set_sensitive(menuitem, TRUE);
2792
2793                 menu_set_sensitive(ifactory, "/View/Followup to", TRUE);
2794         } else {
2795                 gtk_widget_hide(compose->newsgroups_hbox);
2796                 gtk_widget_hide(compose->newsgroups_entry);
2797                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 0);
2798                 gtk_widget_queue_resize(compose->table_vbox);
2799                 compose->use_newsgroups = FALSE;
2800
2801                 menuitem = gtk_item_factory_get_item(ifactory, "/View/To");
2802                 gtk_check_menu_item_set_active
2803                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2804                 gtk_widget_set_sensitive(menuitem, FALSE);
2805                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
2806                 gtk_check_menu_item_set_active
2807                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2808                 gtk_widget_set_sensitive(menuitem, FALSE);
2809
2810                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Followup to");
2811                 gtk_check_menu_item_set_active
2812                         (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
2813                 gtk_widget_set_sensitive(menuitem, FALSE);
2814         }
2815
2816         if (account->set_autocc) {
2817                 compose_entry_show(compose, COMPOSE_ENTRY_CC);
2818                 if (account->auto_cc && compose->mode != COMPOSE_REEDIT)
2819                         compose_entry_set(compose, account->auto_cc,
2820                                           COMPOSE_ENTRY_CC);
2821         }
2822         if (account->set_autobcc) {
2823                 compose_entry_show(compose, COMPOSE_ENTRY_BCC);
2824                 if (account->auto_bcc && compose->mode != COMPOSE_REEDIT)
2825                         compose_entry_set(compose, account->auto_bcc,
2826                                           COMPOSE_ENTRY_BCC);
2827         }
2828         if (account->set_autoreplyto) {
2829                 compose_entry_show(compose, COMPOSE_ENTRY_REPLY_TO);
2830                 if (account->auto_replyto && compose->mode != COMPOSE_REEDIT)
2831                         compose_entry_set(compose, account->auto_replyto,
2832                                           COMPOSE_ENTRY_REPLY_TO);
2833         }
2834
2835         menuitem = gtk_item_factory_get_item(ifactory, "/View/Ruler");
2836         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2837                                        prefs_common.show_ruler);
2838 #endif
2839
2840 #if USE_GPGME
2841         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
2842         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2843                                        account->default_sign);
2844         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
2845         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2846                                        account->default_encrypt);
2847                                        
2848         activate_gnupg_mode(compose, account);          
2849 #endif /* USE_GPGME */
2850 }
2851
2852 gboolean compose_check_for_valid_recipient(Compose *compose) {
2853         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2854         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2855         gboolean recipient_found = FALSE;
2856         GSList *list;
2857         gchar **strptr;
2858
2859         /* free to and newsgroup list */
2860         slist_free_strings(compose->to_list);
2861         g_slist_free(compose->to_list);
2862         compose->to_list = NULL;
2863                         
2864         slist_free_strings(compose->newsgroup_list);
2865         g_slist_free(compose->newsgroup_list);
2866         compose->newsgroup_list = NULL;
2867
2868         /* search header entries for to and newsgroup entries */
2869         for (list = compose->header_list; list; list = list->next) {
2870                 gchar *header;
2871                 gchar *entry;
2872                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
2873                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2874                 g_strstrip(entry);
2875                 if (entry[0] != '\0') {
2876                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2877                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2878                                         compose->to_list = address_list_append(compose->to_list, entry);
2879                                         recipient_found = TRUE;
2880                                 }
2881                         }
2882                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2883                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2884                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2885                                         recipient_found = TRUE;
2886                                 }
2887                         }
2888                 }
2889                 g_free(header);
2890                 g_free(entry);
2891         }
2892         return recipient_found;
2893 }
2894
2895 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
2896 {
2897         gchar *str;
2898
2899         if (compose_check_for_valid_recipient(compose) == FALSE) {
2900                 alertpanel_error(_("Recipient is not specified."));
2901                 return FALSE;
2902         }
2903
2904         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2905         if (*str == '\0' && check_subject == TRUE) {
2906                 AlertValue aval;
2907
2908                 aval = alertpanel(_("Send"),
2909                                   _("Subject is empty. Send it anyway?"),
2910                                   _("Yes"), _("No"), NULL);
2911                 if (aval != G_ALERTDEFAULT)
2912                         return FALSE;
2913         }
2914
2915         return TRUE;
2916 }
2917
2918 gint compose_send(Compose *compose)
2919 {
2920         gint msgnum;
2921         FolderItem *folder;
2922         gint val;
2923         gchar *msgpath;
2924
2925         if (compose_check_entries(compose, TRUE) == FALSE)
2926                 return -1;
2927
2928         val = compose_queue(compose, &msgnum, &folder);
2929         if (val) {
2930                 alertpanel_error(_("Could not queue message for sending"));
2931                 return -1;
2932         }
2933
2934         if (msgnum == 0) {
2935                 alertpanel_error(_("The message was queued but could not be sent.\nUse \"Send queued messages\" from the main window to retry."));
2936                 return 0;
2937         }
2938         
2939         msgpath = folder_item_fetch_msg(folder, msgnum);
2940         val = procmsg_send_message_queue(msgpath);
2941         g_free(msgpath);
2942
2943         folder_item_remove_msg(folder, msgnum);
2944
2945         return val;
2946 }
2947
2948 #if 0 /* compose restructure */
2949 gint compose_send(Compose *compose)
2950 {
2951         gchar tmp[MAXPATHLEN + 1];
2952         gint ok = 0;
2953         static gboolean lock = FALSE;
2954
2955         if (lock) return 1;
2956
2957         g_return_val_if_fail(compose->account != NULL, -1);
2958
2959         lock = TRUE;
2960
2961         if (compose_check_entries(compose, TRUE) == FALSE) {
2962                 lock = FALSE;
2963                 return 1;
2964         }
2965
2966         /* write to temporary file */
2967         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
2968                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
2969
2970         if (prefs_common.linewrap_at_send)
2971                 compose_wrap_line_all(compose);
2972
2973         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2974                 lock = FALSE;
2975                 return -1;
2976         }
2977
2978         if (!compose->to_list && !compose->newsgroup_list) {
2979                 g_warning("can't get recipient list.");
2980                 unlink(tmp);
2981                 lock = FALSE;
2982                 return -1;
2983         }
2984
2985         if (compose->to_list) {
2986                 PrefsAccount *ac;
2987
2988 #if 0 /* NEW COMPOSE GUI */
2989                 if (compose->account->protocol != A_NNTP)
2990                         ac = compose->account;
2991                 else {
2992                         ac = account_find_from_address(compose->account->address);
2993                         if (!ac) {
2994                                 if (cur_account && cur_account->protocol != A_NNTP)
2995                                         ac = cur_account;
2996                                 else
2997                                         ac = account_get_default();
2998                         }
2999                         if (!ac || ac->protocol == A_NNTP) {
3000                                 alertpanel_error(_("Account for sending mail is not specified.\n"
3001                                                    "Please select a mail account before sending."));
3002                                 unlink(tmp);
3003                                 lock = FALSE;
3004                                 return -1;
3005                         }
3006                 }
3007 #endif
3008                 ac = compose->account;
3009
3010                 ok = send_message(tmp, ac, compose->to_list);
3011         }
3012
3013         if (ok == 0 && compose->newsgroup_list) {
3014                 ok = news_post(FOLDER(compose->account->folder), tmp);
3015                 if (ok < 0) {
3016                         alertpanel_error(_("Error occurred while posting the message to %s ."),
3017                                          compose->account->nntp_server);
3018                         unlink(tmp);
3019                         lock = FALSE;
3020                         return -1;
3021                 }
3022         }
3023
3024         /* queue message if failed to send */
3025         if (ok < 0) {
3026                 if (prefs_common.queue_msg) {
3027                         AlertValue val;
3028
3029                         val = alertpanel
3030                                 (_("Queueing"),
3031                                  _("Error occurred while sending the message.\n"
3032                                    "Put this message into queue folder?"),
3033                                  _("OK"), _("Cancel"), NULL);
3034                         if (G_ALERTDEFAULT == val) {
3035                                 ok = compose_queue(compose, tmp);
3036                                 if (ok < 0)
3037                                         alertpanel_error(_("Can't queue the message."));
3038                         }
3039                 } else
3040                         alertpanel_error_log(_("Error occurred while sending the message."));
3041         } else {
3042                 if (compose->mode == COMPOSE_REEDIT) {
3043                         compose_remove_reedit_target(compose);
3044                 }
3045                 /* save message to outbox */
3046                 if (prefs_common.savemsg) {
3047                         FolderItem *outbox;
3048
3049                         outbox = account_get_special_folder
3050                                 (compose->account, F_OUTBOX);
3051                         if (procmsg_save_to_outbox(outbox, tmp, FALSE) < 0)
3052                                 alertpanel_error
3053                                         (_("Can't save the message to Sent."));
3054                 }
3055         }
3056
3057         unlink(tmp);
3058         lock = FALSE;
3059         return ok;
3060 }
3061 #endif
3062
3063 static gboolean compose_use_attach(Compose *compose) {
3064     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
3065 }
3066
3067 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3068                                                            FILE *fp)
3069 {
3070         gchar buf[BUFFSIZE];
3071         gchar *str;
3072         gboolean first_address;
3073         GSList *list;
3074         ComposeHeaderEntry *headerentry;
3075         gchar *headerentryname;
3076         gchar *cc_hdr;
3077         gchar *to_hdr;
3078
3079         debug_print("Writing redirect header\n");
3080
3081         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3082         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3083
3084         first_address = TRUE;
3085         for (list = compose->header_list; list; list = list->next) {
3086                 headerentry = ((ComposeHeaderEntry *)list->data);
3087                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3088
3089                 if (g_strcasecmp(headerentryname, cc_hdr) == 0 
3090                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
3091                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3092                         Xstrdup_a(str, str, return -1);
3093                         g_strstrip(str);
3094                         if (str[0] != '\0') {
3095                                 compose_convert_header
3096                                         (buf, sizeof(buf), str,
3097                                         strlen("Resent-To") + 2);
3098                                 if (first_address) {
3099                                         fprintf(fp, "Resent-To: ");
3100                                         first_address = FALSE;
3101                                 } else {
3102                                         fprintf(fp, ",");
3103                                 }
3104                                 fprintf(fp, "%s", buf);
3105                         }
3106                 }
3107         }
3108         /* if (!first_address) { */
3109         fprintf(fp, "\n");
3110         /* } */
3111
3112         return(0);
3113 }
3114
3115 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3116 {
3117         gchar buf[BUFFSIZE];
3118         gchar *str;
3119         /* struct utsname utsbuf; */
3120
3121         g_return_val_if_fail(fp != NULL, -1);
3122         g_return_val_if_fail(compose->account != NULL, -1);
3123         g_return_val_if_fail(compose->account->address != NULL, -1);
3124
3125         /* Resent-Date */
3126         get_rfc822_date(buf, sizeof(buf));
3127         fprintf(fp, "Resent-Date: %s\n", buf);
3128
3129         /* Resent-From */
3130         if (compose->account->name && *compose->account->name) {
3131                 compose_convert_header
3132                         (buf, sizeof(buf), compose->account->name,
3133                          strlen("From: "));
3134                 fprintf(fp, "Resent-From: %s <%s>\n",
3135                         buf, compose->account->address);
3136         } else
3137                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3138
3139         /* Subject */
3140         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3141         if (*str != '\0') {
3142                 Xstrdup_a(str, str, return -1);
3143                 g_strstrip(str);
3144                 if (*str != '\0') {
3145                         compose_convert_header(buf, sizeof(buf), str,
3146                                                strlen("Subject: "));
3147                         fprintf(fp, "Subject: %s\n", buf);
3148                 }
3149         }
3150
3151         /* Resent-Message-ID */
3152         if (compose->account->gen_msgid) {
3153                 compose_generate_msgid(compose, buf, sizeof(buf));
3154                 fprintf(fp, "Resent-Message-Id: <%s>\n", buf);
3155                 compose->msgid = g_strdup(buf);
3156         }
3157
3158         compose_redirect_write_headers_from_headerlist(compose, fp);
3159
3160         /* separator between header and body */
3161         fputs("\n", fp);
3162
3163         return 0;
3164 }
3165
3166 static gint compose_redirect_write_to_file(Compose *compose, const gchar *file)
3167 {
3168         FILE *fp;
3169         FILE *fdest;
3170         size_t len;
3171         gchar buf[BUFFSIZE];
3172
3173         if ((fp = fopen(compose->redirect_filename, "rb")) == NULL) {
3174                 FILE_OP_ERROR(file, "fopen");
3175                 return -1;
3176         }
3177
3178         if ((fdest = fopen(file, "wb")) == NULL) {
3179                 FILE_OP_ERROR(file, "fopen");
3180                 fclose(fp);
3181                 return -1;
3182         }
3183
3184         /* chmod for security */
3185         if (change_file_mode_rw(fdest, file) < 0) {
3186                 FILE_OP_ERROR(file, "chmod");
3187                 g_warning("can't change file mode\n");
3188         }
3189
3190         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
3191                 /* should filter returnpath, delivered-to */
3192                 if (g_strncasecmp(buf, "Return-Path:",
3193                                    strlen("Return-Path:")) == 0 ||
3194                     g_strncasecmp(buf, "Delivered-To:",
3195                                   strlen("Delivered-To:")) == 0 ||
3196                     g_strncasecmp(buf, "Received:",
3197                                   strlen("Received:")) == 0 ||
3198                     g_strncasecmp(buf, "Subject:",
3199                                   strlen("Subject:")) == 0 ||
3200                     g_strncasecmp(buf, "X-UIDL:",
3201                                   strlen("X-UIDL:")) == 0)
3202                         continue;
3203
3204                 if (fputs(buf, fdest) == -1)
3205                         goto error;
3206
3207                 if (!prefs_common.redirect_keep_from) {
3208                         if (g_strncasecmp(buf, "From:",
3209                                           strlen("From:")) == 0) {
3210                                 fputs(" (by way of ", fdest);
3211                                 if (compose->account->name
3212                                     && *compose->account->name) {
3213                                         compose_convert_header
3214                                                 (buf, sizeof(buf),
3215                                                  compose->account->name,
3216                                                  strlen("From: "));
3217                                         fprintf(fdest, "%s <%s>",
3218                                                 buf,
3219                                                 compose->account->address);
3220                                 } else
3221                                         fprintf(fdest, "%s",
3222                                                 compose->account->address);
3223                                 fputs(")", fdest);
3224                         }
3225                 }
3226
3227                 if (fputs("\n", fdest) == -1)
3228                         goto error;
3229         }
3230
3231         compose_redirect_write_headers(compose, fdest);
3232
3233         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3234                 if (fwrite(buf, sizeof(gchar), len, fdest) != len) {
3235                         FILE_OP_ERROR(file, "fwrite");
3236                         goto error;
3237                 }
3238         }
3239
3240         fclose(fp);
3241         if (fclose(fdest) == EOF) {
3242                 FILE_OP_ERROR(file, "fclose");
3243                 unlink(file);
3244                 return -1;
3245         }
3246
3247         return 0;
3248  error:
3249         fclose(fp);
3250         fclose(fdest);
3251         unlink(file);
3252
3253         return -1;
3254 }
3255
3256
3257 #if USE_GPGME
3258 /* interfaces to rfc2015 to keep out the prefs stuff there.
3259  * returns 0 on success and -1 on error. */
3260 static gint compose_create_signers_list(Compose *compose, GSList **pkey_list)
3261 {
3262         const gchar *key_id = NULL;
3263         GSList *key_list;
3264
3265         switch (compose->account->sign_key) {
3266         case SIGN_KEY_DEFAULT:
3267                 *pkey_list = NULL;
3268                 return 0;
3269         case SIGN_KEY_BY_FROM:
3270                 key_id = compose->account->address;
3271                 break;
3272         case SIGN_KEY_CUSTOM:
3273                 key_id = compose->account->sign_key_id;
3274                 break;
3275         default:
3276                 break;
3277         }
3278
3279         key_list = rfc2015_create_signers_list(key_id);
3280
3281         if (!key_list) {
3282                 alertpanel_error(_("Could not find any key associated with "
3283                                    "currently selected key id `%s'."), key_id);
3284                 return -1;
3285         }
3286
3287         *pkey_list = key_list;
3288         return 0;
3289 }
3290
3291 /* clearsign message body text */
3292 static gint compose_clearsign_text(Compose *compose, gchar **text)
3293 {
3294         GSList *key_list;
3295         gchar *tmp_file;
3296
3297         tmp_file = get_tmp_file();
3298         if (str_write_to_file(*text, tmp_file) < 0) {
3299                 g_free(tmp_file);
3300                 return -1;
3301         }
3302
3303         if (compose_create_signers_list(compose, &key_list) < 0 ||
3304             rfc2015_clearsign(tmp_file, key_list) < 0) {
3305                 unlink(tmp_file);
3306                 g_free(tmp_file);
3307                 return -1;
3308         }
3309
3310         g_free(*text);
3311         *text = file_read_to_str(tmp_file);
3312         unlink(tmp_file);
3313         g_free(tmp_file);
3314         if (*text == NULL)
3315                 return -1;
3316
3317         return 0;
3318 }
3319 #endif /* USE_GPGME */
3320
3321 static gint compose_write_to_file(Compose *compose, const gchar *file,
3322                                   gboolean is_draft)
3323 {
3324         FILE *fp;
3325         size_t len;
3326         gchar *chars;
3327         gchar *buf;
3328         gchar *canon_buf;
3329         const gchar *out_codeset;
3330         EncodingType encoding;
3331
3332         if ((fp = fopen(file, "wb")) == NULL) {
3333                 FILE_OP_ERROR(file, "fopen");
3334                 return -1;
3335         }
3336
3337         /* chmod for security */
3338         if (change_file_mode_rw(fp, file) < 0) {
3339                 FILE_OP_ERROR(file, "chmod");
3340                 g_warning("can't change file mode\n");
3341         }
3342
3343         /* get all composed text */
3344         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3345         len = strlen(chars);
3346         if (is_ascii_str(chars)) {
3347                 buf = chars;
3348                 chars = NULL;
3349                 out_codeset = CS_US_ASCII;
3350                 encoding = ENC_7BIT;
3351         } else {
3352                 const gchar *src_codeset;
3353
3354                 out_codeset = conv_get_outgoing_charset_str();
3355                 if (!strcasecmp(out_codeset, CS_US_ASCII))
3356                         out_codeset = CS_ISO_8859_1;
3357
3358                 if (prefs_common.encoding_method == CTE_BASE64)
3359                         encoding = ENC_BASE64;
3360                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
3361                         encoding = ENC_QUOTED_PRINTABLE;
3362                 else if (prefs_common.encoding_method == CTE_8BIT)
3363                         encoding = ENC_8BIT;
3364                 else
3365                         encoding = procmime_get_encoding_for_charset(out_codeset);
3366
3367 #if USE_GPGME
3368                 if (!is_draft &&
3369                     compose->use_signing && !compose->gnupg_mode &&
3370                     encoding == ENC_8BIT)
3371                         encoding = ENC_BASE64;
3372 #endif
3373
3374                 src_codeset = conv_get_current_charset_str();
3375                 /* if current encoding is US-ASCII, set it the same as
3376                    outgoing one to prevent code conversion failure */
3377                 if (!strcasecmp(src_codeset, CS_US_ASCII))
3378                         src_codeset = out_codeset;
3379
3380                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3381                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3382
3383                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3384                 if (!buf) {
3385                         AlertValue aval;
3386                         gchar *msg;
3387
3388                         msg = g_strdup_printf(_("Can't convert the character encoding of the message from\n"
3389                                                 "%s to %s.\n"
3390                                                 "Send it anyway?"), src_codeset, out_codeset);
3391                         aval = alertpanel
3392                                 (_("Error"), msg, _("Yes"), _("+No"), NULL);
3393                         g_free(msg);
3394
3395                         if (aval != G_ALERTDEFAULT) {
3396                                 g_free(chars);
3397                                 fclose(fp);
3398                                 unlink(file);
3399                                 return -1;
3400                         } else {
3401                                 buf = chars;
3402                                 out_codeset = src_codeset;
3403                                 chars = NULL;
3404                         }
3405                 }
3406         }
3407         g_free(chars);
3408
3409         canon_buf = canonicalize_str(buf);
3410         g_free(buf);
3411         buf = canon_buf;
3412
3413 #if USE_GPGME
3414         if (!is_draft && compose->use_signing && compose->gnupg_mode) {
3415                 if (compose_clearsign_text(compose, &buf) < 0) {
3416                         g_warning("clearsign failed\n");
3417                         fclose(fp);
3418                         unlink(file);
3419                         g_free(buf);
3420                         return -1;
3421                 }
3422         }
3423 #endif
3424
3425         /* write headers */
3426         if (compose_write_headers
3427                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
3428                 g_warning("can't write headers\n");
3429                 fclose(fp);
3430                 /* unlink(file); */
3431                 g_free(buf);
3432                 return -1;
3433         }
3434
3435         if (compose_use_attach(compose)) {
3436 #if USE_GPGME
3437             /* This prolog message is ignored by mime software and
3438              * because it would make our signing/encryption task
3439              * tougher, we don't emit it in that case */
3440             if (!compose->use_signing && !compose->use_encryption)
3441 #endif
3442                 fputs("This is a multi-part message in MIME format.\n", fp);
3443
3444                 fprintf(fp, "\n--%s\n", compose->boundary);
3445                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
3446                         out_codeset);
3447                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3448                         procmime_get_encoding_str(encoding));
3449                 fputc('\n', fp);
3450         }
3451
3452         /* write body */
3453         len = strlen(buf);
3454         if (encoding == ENC_BASE64) {
3455                 gchar outbuf[B64_BUFFSIZE];
3456                 gint i, l;
3457
3458                 for (i = 0; i < len; i += B64_LINE_SIZE) {
3459                         l = MIN(B64_LINE_SIZE, len - i);
3460                         base64_encode(outbuf, buf + i, l);
3461                         fputs(outbuf, fp);
3462                         fputc('\n', fp);
3463                 }
3464         } else if (encoding == ENC_QUOTED_PRINTABLE) {
3465                 gchar *outbuf;
3466                 size_t outlen;
3467
3468                 outbuf = g_malloc(len * 4);
3469                 qp_encode_line(outbuf, buf);
3470                 outlen = strlen(outbuf);
3471                 if (fwrite(outbuf, sizeof(gchar), outlen, fp) != outlen) {
3472                         FILE_OP_ERROR(file, "fwrite");
3473                         fclose(fp);
3474                         unlink(file);
3475                         g_free(outbuf);
3476                         g_free(buf);
3477                         return -1;
3478                 }
3479                 g_free(outbuf);
3480         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
3481                 FILE_OP_ERROR(file, "fwrite");
3482                 fclose(fp);
3483                 unlink(file);
3484                 g_free(buf);
3485                 return -1;
3486         }
3487         g_free(buf);
3488
3489         if (compose_use_attach(compose))
3490                 compose_write_attach(compose, fp);
3491
3492         if (fclose(fp) == EOF) {
3493                 FILE_OP_ERROR(file, "fclose");
3494                 unlink(file);
3495                 return -1;
3496         }
3497
3498 #if USE_GPGME
3499         if (is_draft) {
3500                 uncanonicalize_file_replace(file);
3501                 return 0;
3502         }
3503
3504         if ((compose->use_signing && !compose->gnupg_mode) ||
3505             compose->use_encryption) {
3506                 if (canonicalize_file_replace(file) < 0) {
3507                         unlink(file);
3508                         return -1;
3509                 }
3510         }
3511
3512         if (compose->use_signing && !compose->gnupg_mode) {
3513                 GSList *key_list;
3514
3515                 if (compose_create_signers_list(compose, &key_list) < 0 ||
3516                     rfc2015_sign(file, key_list) < 0) {
3517                         unlink(file);
3518                         return -1;
3519                 }
3520         }
3521         if (compose->use_encryption) {
3522                 if (rfc2015_encrypt(file, compose->to_list,
3523                                     compose->gnupg_mode) < 0) {
3524                         unlink(file);
3525                         return -1;
3526                 }
3527         }
3528 #endif /* USE_GPGME */
3529
3530         uncanonicalize_file_replace(file);
3531
3532         return 0;
3533 }
3534
3535 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3536 {
3537         FILE *fp;
3538         size_t len;
3539         gchar *chars;
3540
3541         if ((fp = fopen(file, "wb")) == NULL) {
3542                 FILE_OP_ERROR(file, "fopen");
3543                 return -1;
3544         }
3545
3546         /* chmod for security */
3547         if (change_file_mode_rw(fp, file) < 0) {
3548                 FILE_OP_ERROR(file, "chmod");
3549                 g_warning("can't change file mode\n");
3550         }
3551
3552         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3553
3554         /* write body */
3555         len = strlen(chars);
3556         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3557                 FILE_OP_ERROR(file, "fwrite");
3558                 g_free(chars);
3559                 fclose(fp);
3560                 unlink(file);
3561                 return -1;
3562         }
3563
3564         g_free(chars);
3565
3566         if (fclose(fp) == EOF) {
3567                 FILE_OP_ERROR(file, "fclose");
3568                 unlink(file);
3569                 return -1;
3570         }
3571         return 0;
3572 }
3573
3574 static gint compose_remove_reedit_target(Compose *compose)
3575 {
3576         FolderItem *item;
3577         MsgInfo *msginfo = compose->targetinfo;
3578
3579         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3580         if (!msginfo) return -1;
3581
3582         item = msginfo->folder;
3583         g_return_val_if_fail(item != NULL, -1);
3584
3585         if (procmsg_msg_exist(msginfo) &&
3586             (item->stype == F_DRAFT || item->stype == F_QUEUE 
3587              || msginfo == compose->autosaved_draft)) {
3588                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3589                         g_warning("can't remove the old message\n");
3590                         return -1;
3591                 }
3592         }
3593
3594         return 0;
3595 }
3596
3597 void compose_remove_draft(Compose *compose)
3598 {
3599         FolderItem *drafts;
3600         MsgInfo *msginfo = compose->targetinfo;
3601         drafts = account_get_special_folder(compose->account, F_DRAFT);
3602
3603         if (procmsg_msg_exist(msginfo)) {
3604                 folder_item_remove_msg(drafts, msginfo->msgnum);
3605         }
3606
3607 }
3608
3609 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3610 {
3611         return compose_queue_sub (compose, msgnum, item, FALSE);
3612 }
3613 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
3614 {
3615         FolderItem *queue;
3616         gchar *tmp, *tmp2;
3617         FILE *fp, *src_fp;
3618         GSList *cur;
3619         gchar buf[BUFFSIZE];
3620         gint num;
3621         static gboolean lock = FALSE;
3622         PrefsAccount *mailac = NULL, *newsac = NULL;
3623         
3624         debug_print("queueing message...\n");
3625         g_return_val_if_fail(compose->account != NULL, -1);
3626
3627         lock = TRUE;
3628         
3629         if (compose_check_entries(compose, check_subject) == FALSE) {
3630                 lock = FALSE;
3631                 return -1;
3632         }
3633
3634         if (!compose->to_list && !compose->newsgroup_list) {
3635                 g_warning("can't get recipient list.");
3636                 lock = FALSE;
3637                 return -1;
3638         }
3639
3640         if (compose->to_list) {
3641                 if (compose->account->protocol != A_NNTP)
3642                         mailac = compose->account;
3643                 else if (cur_account && cur_account->protocol != A_NNTP)
3644                         mailac = cur_account;
3645                 else if (!(mailac = compose_current_mail_account())) {
3646                         lock = FALSE;
3647                         alertpanel_error(_("No account for sending mails available!"));
3648                         return -1;
3649                 }
3650         }
3651
3652         if (compose->newsgroup_list) {
3653                 if (compose->account->protocol == A_NNTP)
3654                         newsac = compose->account;
3655                 else if (!newsac->protocol != A_NNTP) {
3656                         lock = FALSE;
3657                         alertpanel_error(_("No account for posting news available!"));
3658                         return -1;
3659                 }                       
3660         }
3661
3662         if (prefs_common.linewrap_at_send)
3663                 compose_wrap_line_all(compose);
3664                         
3665         /* write to temporary file */
3666         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3667                                       G_DIR_SEPARATOR, (gint)compose);
3668
3669         if (compose->redirect_filename != NULL) {
3670                 if (compose_redirect_write_to_file(compose, tmp2) < 0) {
3671                         unlink(tmp2);
3672                         lock = FALSE;
3673                         return -1;
3674                 }
3675         }
3676         else {
3677                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3678                         unlink(tmp2);
3679                         lock = FALSE;
3680                         return -1;
3681                 }
3682         }
3683
3684         /* add queue header */
3685         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3686                               G_DIR_SEPARATOR, (gint)compose);
3687         if ((fp = fopen(tmp, "wb")) == NULL) {
3688                 FILE_OP_ERROR(tmp, "fopen");
3689                 g_free(tmp);
3690                 return -1;
3691         }
3692         if ((src_fp = fopen(tmp2, "rb")) == NULL) {
3693                 FILE_OP_ERROR(tmp2, "fopen");
3694                 fclose(fp);
3695                 unlink(tmp);
3696                 g_free(tmp);
3697                 unlink(tmp2);
3698                 g_free(tmp2);
3699                 return -1;
3700         }
3701         if (change_file_mode_rw(fp, tmp) < 0) {
3702                 FILE_OP_ERROR(tmp, "chmod");
3703                 g_warning("can't change file mode\n");
3704         }
3705
3706         /* queueing variables */
3707         fprintf(fp, "AF:\n");
3708         fprintf(fp, "NF:0\n");
3709         fprintf(fp, "PS:10\n");
3710         fprintf(fp, "SRH:1\n");
3711         fprintf(fp, "SFN:\n");
3712         fprintf(fp, "DSR:\n");
3713         if (compose->msgid)
3714                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3715         else
3716                 fprintf(fp, "MID:\n");
3717         fprintf(fp, "CFG:\n");
3718         fprintf(fp, "PT:0\n");
3719         fprintf(fp, "S:%s\n", compose->account->address);
3720         fprintf(fp, "RQ:\n");
3721         if (mailac)
3722                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3723         else
3724                 fprintf(fp, "SSV:\n");
3725         if (newsac)
3726                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3727         else
3728                 fprintf(fp, "NSV:\n");
3729         fprintf(fp, "SSH:\n");
3730         /* write recepient list */
3731         if (compose->to_list) {
3732                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
3733                 for (cur = compose->to_list->next; cur != NULL;
3734                      cur = cur->next)
3735                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3736                 fprintf(fp, "\n");
3737         }
3738         /* write newsgroup list */
3739         if (compose->newsgroup_list) {
3740                 fprintf(fp, "NG:");
3741                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3742                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3743                         fprintf(fp, ",%s", (gchar *)cur->data);
3744                 fprintf(fp, "\n");
3745         }
3746         /* Sylpheed account IDs */
3747         if (mailac) {
3748                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3749         }
3750         if (newsac) {
3751                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3752         }
3753         /* Save copy folder */
3754         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3755                 gchar *savefolderid;
3756                 
3757                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3758                 fprintf(fp, "SCF:%s\n", savefolderid);
3759                 g_free(savefolderid);
3760         }
3761         /* Message-ID of message replying to */
3762         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
3763                 gchar *folderid;
3764                 
3765                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
3766                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
3767                 g_free(folderid);
3768         }
3769         /* Message-ID of message forwarding to */
3770         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
3771                 gchar *folderid;
3772                 
3773                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
3774                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
3775                 g_free(folderid);
3776         }
3777         fprintf(fp, "\n");
3778
3779         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3780                 if (fputs(buf, fp) == EOF) {
3781                         FILE_OP_ERROR(tmp, "fputs");
3782                         fclose(fp);
3783                         fclose(src_fp);
3784                         unlink(tmp);
3785                         g_free(tmp);
3786                         unlink(tmp2);
3787                         g_free(tmp2);
3788                         return -1;
3789                 }
3790         }
3791         fclose(src_fp);
3792         if (fclose(fp) == EOF) {
3793                 FILE_OP_ERROR(tmp, "fclose");
3794                 unlink(tmp);
3795                 g_free(tmp);
3796                 unlink(tmp2);
3797                 g_free(tmp2);
3798                 return -1;
3799         }
3800
3801         queue = account_get_special_folder(compose->account, F_QUEUE);
3802         if (!queue) {
3803                 g_warning("can't find queue folder\n");
3804                 unlink(tmp);
3805                 g_free(tmp);
3806                 return -1;
3807         }
3808         folder_item_scan(queue);
3809         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3810                 g_warning("can't queue the message\n");
3811                 unlink(tmp);
3812                 g_free(tmp);
3813                 return -1;
3814         }
3815         unlink(tmp);
3816         g_free(tmp);
3817         unlink(tmp2);
3818         g_free(tmp2);
3819
3820         if (compose->mode == COMPOSE_REEDIT) {
3821                 compose_remove_reedit_target(compose);
3822         }
3823
3824         if ((msgnum != NULL) && (item != NULL)) {
3825                 *msgnum = num;
3826                 *item = queue;
3827         }
3828
3829         return 0;
3830 }
3831
3832 static void compose_write_attach(Compose *compose, FILE *fp)
3833 {
3834         AttachInfo *ainfo;
3835         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3836         gint row;
3837         FILE *attach_fp;
3838         gchar filename[BUFFSIZE];
3839         gint len;
3840
3841         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3842              row++) {
3843                 if ((attach_fp = fopen(ainfo->file, "rb")) == NULL) {
3844                         g_warning("Can't open file %s\n", ainfo->file);
3845                         continue;
3846                 }
3847
3848                 fprintf(fp, "\n--%s\n", compose->boundary);
3849
3850                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3851                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3852                         fprintf(fp, "Content-Disposition: inline\n");
3853                 } else {
3854                         compose_convert_header(filename, sizeof(filename),
3855                                                ainfo->name, 12);
3856                         fprintf(fp, "Content-Type: %s;\n"
3857                                     " name=\"%s\"\n",
3858                                 ainfo->content_type, filename);
3859                         fprintf(fp, "Content-Disposition: attachment;\n"
3860                                     " filename=\"%s\"\n", filename);
3861                 }
3862
3863                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3864                         procmime_get_encoding_str(ainfo->encoding));
3865
3866                 if (ainfo->encoding == ENC_BASE64) {
3867                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3868
3869                         while ((len = fread(inbuf, sizeof(gchar),
3870                                             B64_LINE_SIZE, attach_fp))
3871                                == B64_LINE_SIZE) {
3872                                 base64_encode(outbuf, inbuf, B64_LINE_SIZE);
3873                                 fputs(outbuf, fp);
3874                                 fputc('\n', fp);
3875                         }
3876                         if (len > 0 && feof(attach_fp)) {
3877                                 base64_encode(outbuf, inbuf, len);
3878                                 fputs(outbuf, fp);
3879                                 fputc('\n', fp);
3880                         }
3881                 } else if (ainfo->encoding == ENC_QUOTED_PRINTABLE) {
3882                         gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
3883
3884                         while (fgets(inbuf, sizeof(inbuf), attach_fp) != NULL) {
3885                                 qp_encode_line(outbuf, inbuf);
3886                                 fputs(outbuf, fp);
3887                         }
3888                 } else {
3889                         gchar buf[BUFFSIZE];
3890
3891                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3892                                 strcrchomp(buf);
3893                                 fputs(buf, fp);
3894                         }
3895                 }
3896
3897                 fclose(attach_fp);
3898         }
3899
3900         fprintf(fp, "\n--%s--\n", compose->boundary);
3901 }
3902
3903 #define QUOTE_IF_REQUIRED(out, str)                     \
3904 {                                                       \
3905         if (*str != '"' && (strchr(str, ',')            \
3906                         || strchr(str, '.'))) {         \
3907                 gchar *__tmp;                           \
3908                 gint len;                               \
3909                                                         \
3910                 len = strlen(str) + 3;                  \
3911                 Xalloca(__tmp, len, return -1);         \
3912                 g_snprintf(__tmp, len, "\"%s\"", str);  \
3913                 out = __tmp;                            \
3914         } else {                                        \
3915                 Xstrdup_a(out, str, return -1);         \
3916         }                                               \
3917 }
3918
3919 #define PUT_RECIPIENT_HEADER(header, str)                                    \
3920 {                                                                            \
3921         if (*str != '\0') {                                                  \
3922                 Xstrdup_a(str, str, return -1);                              \
3923                 g_strstrip(str);                                             \
3924                 if (*str != '\0') {                                          \
3925                         compose->to_list = address_list_append               \
3926                                 (compose->to_list, str);                     \
3927                         compose_convert_header                               \
3928                                 (buf, sizeof(buf), str, strlen(header) + 2); \
3929                         fprintf(fp, "%s: %s\n", header, buf);                \
3930                 }                                                            \
3931         }                                                                    \
3932 }
3933
3934 #define IS_IN_CUSTOM_HEADER(header) \
3935         (compose->account->add_customhdr && \
3936          custom_header_find(compose->account->customhdr_list, header) != NULL)
3937
3938 static gint compose_write_headers_from_headerlist(Compose *compose, 
3939                                                   FILE *fp, 
3940                                                   gchar *header)
3941 {
3942         gchar buf[BUFFSIZE];
3943         gchar *str, *header_w_colon, *trans_hdr;
3944         gboolean first_address;
3945         GSList *list;
3946         ComposeHeaderEntry *headerentry;
3947         gchar * headerentryname;
3948
3949         if (IS_IN_CUSTOM_HEADER(header)) {
3950                 return 0;
3951         }
3952
3953         debug_print("Writing %s-header\n", header);
3954
3955         header_w_colon = g_strconcat(header, ":", NULL);
3956         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3957
3958         first_address = TRUE;
3959         for (list = compose->header_list; list; list = list->next) {
3960                 headerentry = ((ComposeHeaderEntry *)list->data);
3961                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3962
3963                 if (!g_strcasecmp(trans_hdr, headerentryname)) {
3964                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3965                         Xstrdup_a(str, str, return -1);
3966                         g_strstrip(str);
3967                         if (str[0] != '\0') {
3968                                 compose_convert_header
3969                                         (buf, sizeof(buf), str,
3970                                         strlen(header) + 2);
3971                                 if (first_address) {
3972                                         fprintf(fp, "%s: ", header);
3973                                         first_address = FALSE;
3974                                 } else {
3975                                         fprintf(fp, ",");
3976                                 }
3977                                 fprintf(fp, "%s", buf);
3978                         }
3979                 }
3980         }
3981         if (!first_address) {
3982                 fprintf(fp, "\n");
3983         }
3984
3985         g_free(header_w_colon);
3986
3987         return(0);
3988 }
3989
3990 static gint compose_write_headers(Compose *compose, FILE *fp,
3991                                   const gchar *charset, EncodingType encoding,
3992                                   gboolean is_draft)
3993 {
3994         gchar buf[BUFFSIZE];
3995         gchar *str;
3996         gchar *name;
3997         GSList *list;
3998         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3999
4000         /* struct utsname utsbuf; */
4001
4002         g_return_val_if_fail(fp != NULL, -1);
4003         g_return_val_if_fail(charset != NULL, -1);
4004         g_return_val_if_fail(compose->account != NULL, -1);
4005         g_return_val_if_fail(compose->account->address != NULL, -1);
4006
4007         /* Save draft infos */
4008         if (is_draft) {
4009                 fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
4010                 fprintf(fp, "S:%s\n", compose->account->address);
4011                 if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
4012                         gchar *savefolderid;
4013
4014                         savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
4015                         fprintf(fp, "SCF:%s\n", savefolderid);
4016                         g_free(savefolderid);
4017                 }
4018                 fprintf(fp, "\n");
4019         }
4020
4021         /* Date */
4022         if (compose->account->add_date) {
4023                 get_rfc822_date(buf, sizeof(buf));
4024                 fprintf(fp, "Date: %s\n", buf);
4025         }
4026
4027         /* From */
4028         if (!IS_IN_CUSTOM_HEADER("From")) {
4029                 if (compose->account->name && *compose->account->name) {
4030                         compose_convert_header
4031                                 (buf, sizeof(buf), compose->account->name,
4032                                  strlen("From: "));
4033                         QUOTE_IF_REQUIRED(name, buf);
4034                         fprintf(fp, "From: %s <%s>\n",
4035                                 name, compose->account->address);
4036                 } else
4037                         fprintf(fp, "From: %s\n", compose->account->address);
4038         }
4039         
4040         /* To */
4041         compose_write_headers_from_headerlist(compose, fp, "To");
4042 #if 0 /* NEW COMPOSE GUI */
4043         if (compose->use_to) {
4044                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
4045                 PUT_RECIPIENT_HEADER("To", str);
4046         }
4047 #endif
4048
4049         /* Newsgroups */
4050         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
4051 #if 0 /* NEW COMPOSE GUI */
4052         if (compose->use_newsgroups) {
4053                 str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
4054                 if (*str != '\0') {
4055                         Xstrdup_a(str, str, return -1);
4056                         g_strstrip(str);
4057                         remove_space(str);
4058                         if (*str != '\0') {
4059                                 compose->newsgroup_list =
4060                                         newsgroup_list_append
4061                                                 (compose->newsgroup_list, str);
4062                                 compose_convert_header(buf, sizeof(buf), str,
4063                                                        strlen("Newsgroups: "));
4064                                 fprintf(fp, "Newsgroups: %s\n", buf);
4065                         }
4066                 }
4067         }
4068 #endif
4069         /* Cc */
4070         compose_write_headers_from_headerlist(compose, fp, "Cc");
4071 #if 0 /* NEW COMPOSE GUI */
4072         if (compose->use_cc) {
4073                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
4074                 PUT_RECIPIENT_HEADER("Cc", str);
4075         }
4076 #endif
4077         /* Bcc */
4078         compose_write_headers_from_headerlist(compose, fp, "Bcc");
4079 #if 0 /* NEW COMPOSE GUI */
4080         if (compose->use_bcc) {
4081                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
4082                 PUT_RECIPIENT_HEADER("Bcc", str);
4083         }
4084 #endif
4085
4086         /* Subject */
4087         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
4088         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4089                 Xstrdup_a(str, str, return -1);
4090                 g_strstrip(str);
4091                 if (*str != '\0') {
4092                         compose_convert_header(buf, sizeof(buf), str,
4093                                                strlen("Subject: "));
4094                         fprintf(fp, "Subject: %s\n", buf);
4095                 }
4096         }
4097
4098         /* Message-ID */
4099         if (compose->account->gen_msgid) {
4100                 compose_generate_msgid(compose, buf, sizeof(buf));
4101                 fprintf(fp, "Message-Id: <%s>\n", buf);
4102                 compose->msgid = g_strdup(buf);
4103         }
4104
4105         /* In-Reply-To */
4106         if (compose->inreplyto && compose->to_list)
4107                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
4108
4109         /* References */
4110         if (compose->references)
4111                 fprintf(fp, "References: %s\n", compose->references);
4112
4113         /* Followup-To */
4114         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
4115 #if 0 /* NEW COMPOSE GUI */
4116         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
4117                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
4118                 if (*str != '\0') {
4119                         Xstrdup_a(str, str, return -1);
4120                         g_strstrip(str);
4121                         remove_space(str);
4122                         if (*str != '\0') {
4123                                 compose_convert_header(buf, sizeof(buf), str,
4124                                                        strlen("Followup-To: "));
4125                                 fprintf(fp, "Followup-To: %s\n", buf);
4126                         }
4127                 }
4128         }
4129 #endif
4130         /* Reply-To */
4131         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
4132 #if 0 /* NEW COMPOSE GUI */
4133         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
4134                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
4135                 if (*str != '\0') {
4136                         Xstrdup_a(str, str, return -1);
4137                         g_strstrip(str);
4138                         if (*str != '\0') {
4139                                 compose_convert_header(buf, sizeof(buf), str,
4140                                                        strlen("Reply-To: "));
4141                                 fprintf(fp, "Reply-To: %s\n", buf);
4142                         }
4143                 }
4144         }
4145 #endif
4146         /* Organization */
4147         if (compose->account->organization &&
4148             !IS_IN_CUSTOM_HEADER("Organization")) {
4149                 compose_convert_header(buf, sizeof(buf),
4150                                        compose->account->organization,
4151                                        strlen("Organization: "));
4152                 fprintf(fp, "Organization: %s\n", buf);
4153         }
4154
4155         /* Program version and system info */
4156         /* uname(&utsbuf); */
4157         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4158             !compose->newsgroup_list) {
4159                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4160                         prog_version,
4161                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4162                         TARGET_ALIAS);
4163                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4164         }
4165         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4166                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4167                         prog_version,
4168                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4169                         TARGET_ALIAS);
4170                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4171         }
4172
4173         /* custom headers */
4174         if (compose->account->add_customhdr) {
4175                 GSList *cur;
4176
4177                 for (cur = compose->account->customhdr_list; cur != NULL;
4178                      cur = cur->next) {
4179                         CustomHeader *chdr = (CustomHeader *)cur->data;
4180
4181                         if (strcasecmp(chdr->name, "Date")         != 0 &&
4182                             strcasecmp(chdr->name, "From")         != 0 &&
4183                             strcasecmp(chdr->name, "To")           != 0 &&
4184                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
4185                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
4186                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
4187                             strcasecmp(chdr->name, "References")   != 0 &&
4188                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
4189                             strcasecmp(chdr->name, "Content-Type") != 0 &&
4190                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
4191                             != 0) {
4192                                 compose_convert_header
4193                                         (buf, sizeof(buf),
4194                                          chdr->value ? chdr->value : "",
4195                                          strlen(chdr->name) + 2);
4196                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
4197                         }
4198                 }
4199         }
4200
4201         /* MIME */
4202         fprintf(fp, "Mime-Version: 1.0\n");
4203         if (compose_use_attach(compose)) {
4204                 get_rfc822_date(buf, sizeof(buf));
4205                 subst_char(buf, ' ', '_');
4206                 subst_char(buf, ',', '_');
4207                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
4208                                                     buf, (guint)compose);
4209                 fprintf(fp,
4210                         "Content-Type: multipart/mixed;\n"
4211                         " boundary=\"%s\"\n", compose->boundary);
4212         } else {
4213                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
4214                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
4215                         procmime_get_encoding_str(encoding));
4216         }
4217
4218         /* PRIORITY */
4219         switch (compose->priority) {
4220                 case PRIORITY_HIGHEST: fprintf(fp, "Importance: high\n"
4221                                                    "X-Priority: 1 (Highest)\n");
4222                         break;
4223                 case PRIORITY_HIGH: fprintf(fp, "Importance: high\n"
4224                                                 "X-Priority: 2 (High)\n");
4225                         break;
4226                 case PRIORITY_NORMAL: break;
4227                 case PRIORITY_LOW: fprintf(fp, "Importance: low\n"
4228                                                "X-Priority: 4 (Low)\n");
4229                         break;
4230                 case PRIORITY_LOWEST: fprintf(fp, "Importance: low\n"
4231                                                   "X-Priority: 5 (Lowest)\n");
4232                         break;
4233                 default: debug_print("compose: priority unknown : %d\n",
4234                                      compose->priority);
4235         }
4236
4237         /* Request Return Receipt */
4238         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4239                 if (compose->return_receipt) {
4240                         if (compose->account->name
4241                             && *compose->account->name) {
4242                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
4243                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4244                         } else
4245                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
4246                 }
4247         }
4248
4249         /* get special headers */
4250         for (list = compose->header_list; list; list = list->next) {
4251                 ComposeHeaderEntry *headerentry;
4252                 gchar *tmp;
4253                 gchar *headername;
4254                 gchar *headername_wcolon;
4255                 gchar *headername_trans;
4256                 gchar *headervalue;
4257                 gchar **string;
4258                 gboolean standard_header = FALSE;
4259
4260                 headerentry = ((ComposeHeaderEntry *)list->data);
4261                 
4262                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4263                 if (!strstr(tmp, ":")) {
4264                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4265                         headername = g_strdup(tmp);
4266                 } else {
4267                         headername_wcolon = g_strdup(tmp);
4268                         headername = g_strdup(strtok(tmp, ":"));
4269                 }
4270                 g_free(tmp);
4271                 
4272                 headervalue = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4273                 string = std_headers;
4274                 while (*string != NULL) {
4275                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4276                         if (!strcmp(headername_trans,headername_wcolon))
4277                                 standard_header = TRUE;
4278                         string++;
4279                 }
4280                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4281                         fprintf(fp, "%s %s\n", headername_wcolon, headervalue);
4282                                 
4283                 g_free(headername);
4284                 g_free(headername_wcolon);
4285                 
4286         }
4287
4288         /* separator between header and body */
4289         fputs("\n", fp);
4290
4291         return 0;
4292 }
4293
4294 #undef IS_IN_CUSTOM_HEADER
4295
4296 static void compose_convert_header(gchar *dest, gint len, gchar *src,
4297                                    gint header_len)
4298 {
4299         g_return_if_fail(src != NULL);
4300         g_return_if_fail(dest != NULL);
4301
4302         if (len < 1) return;
4303
4304         g_strchomp(src);
4305
4306         conv_encode_header(dest, len, src, header_len);
4307 }
4308
4309 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
4310 {
4311         struct tm *lt;
4312         time_t t;
4313         gchar *addr;
4314
4315         t = time(NULL);
4316         lt = localtime(&t);
4317
4318         if (compose->account && compose->account->address &&
4319             *compose->account->address) {
4320                 if (strchr(compose->account->address, '@'))
4321                         addr = g_strdup(compose->account->address);
4322                 else
4323                         addr = g_strconcat(compose->account->address, "@",
4324                                            get_domain_name(), NULL);
4325         } else
4326                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
4327                                    NULL);
4328
4329         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
4330                    lt->tm_year + 1900, lt->tm_mon + 1,
4331                    lt->tm_mday, lt->tm_hour,
4332                    lt->tm_min, lt->tm_sec,
4333                    (guint)random(), addr);
4334
4335         debug_print("generated Message-ID: %s\n", buf);
4336
4337         g_free(addr);
4338 }
4339
4340 static void compose_create_header_entry(Compose *compose) 
4341 {
4342         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4343
4344         GtkWidget *combo;
4345         GtkWidget *entry;
4346         GList *combo_list = NULL;
4347         gchar **string, *header = NULL;
4348         ComposeHeaderEntry *headerentry;
4349         gboolean standard_header = FALSE;
4350
4351         headerentry = g_new0(ComposeHeaderEntry, 1);
4352
4353         /* Combo box */
4354         combo = gtk_combo_new();
4355         string = headers; 
4356         while(*string != NULL) {
4357                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
4358                 string++;
4359         }
4360         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
4361         g_list_free(combo_list);
4362         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
4363         gtk_widget_show(combo);
4364         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
4365         if (compose->header_last) {     
4366                 gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4367                 string = headers;
4368                 while (*string != NULL) {
4369                         if (!strcmp(*string, last_header_entry))
4370                                 standard_header = TRUE;
4371                         string++;
4372                 }
4373                 if (standard_header)
4374                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4375         }
4376         if (!compose->header_last || !standard_header) {
4377                 switch(compose->account->protocol) {
4378                         case A_NNTP:
4379                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
4380                                 break;
4381                         default:
4382                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
4383                                 break;
4384                 }                                                                   
4385         }
4386         if (header)
4387                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
4388
4389         /* Entry field */
4390         entry = gtk_entry_new(); 
4391         gtk_widget_show(entry);
4392         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
4393
4394         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
4395         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
4396         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4397
4398         address_completion_register_entry(GTK_ENTRY(entry));
4399
4400         headerentry->compose = compose;
4401         headerentry->combo = combo;
4402         headerentry->entry = entry;
4403         headerentry->headernum = compose->header_nextrow;
4404
4405         compose->header_nextrow++;
4406         compose->header_last = headerentry;
4407 }
4408
4409 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
4410 {
4411         ComposeHeaderEntry *last_header;
4412         
4413         last_header = compose->header_last;
4414         
4415         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
4416         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
4417 }
4418
4419 static GtkWidget *compose_create_header(Compose *compose) 
4420 {
4421         GtkWidget *label;
4422         GtkWidget *hbox;
4423         GtkWidget *from_optmenu_hbox;
4424 #if 0 /* NEW COMPOSE GUI */
4425         GtkWidget *to_entry;
4426         GtkWidget *to_hbox;
4427         GtkWidget *newsgroups_entry;
4428         GtkWidget *newsgroups_hbox;
4429 #endif
4430         GtkWidget *header_scrolledwin;
4431         GtkWidget *header_table;
4432 #if 0 /* NEW COMPOSE GUI */
4433         GtkWidget *cc_entry;
4434         GtkWidget *cc_hbox;
4435         GtkWidget *bcc_entry;
4436         GtkWidget *bcc_hbox;
4437         GtkWidget *reply_entry;
4438         GtkWidget *reply_hbox;
4439         GtkWidget *followup_entry;
4440         GtkWidget *followup_hbox;
4441 #endif
4442
4443         gint count = 0;
4444
4445         /* header labels and entries */
4446         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4447         gtk_widget_show(header_scrolledwin);
4448         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
4449
4450         header_table = gtk_table_new(2, 2, FALSE);
4451         gtk_widget_show(header_table);
4452         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
4453         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
4454         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
4455         count = 0;
4456
4457         /* option menu for selecting accounts */
4458         hbox = gtk_hbox_new(FALSE, 0);
4459         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
4460         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
4461         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
4462                          GTK_FILL, 0, 2, 0);
4463         from_optmenu_hbox = compose_account_option_menu_create(compose);
4464         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
4465                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
4466 #if 0 /* NEW COMPOSE GUI */
4467         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4468 #endif
4469         count++;
4470
4471         compose->header_table = header_table;
4472         compose->header_list = NULL;
4473         compose->header_nextrow = count;
4474
4475         compose_create_header_entry(compose);
4476
4477 #if 0 /* NEW COMPOSE GUI */
4478         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
4479                                 "To:", TRUE); 
4480         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4481         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
4482                                 &count, "Newsgroups:", FALSE);
4483         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
4484
4485         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
4486
4487         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
4488                                 "Cc:", TRUE);
4489         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
4490         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
4491                                 "Bcc:", TRUE);
4492         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
4493         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
4494                                 "Reply-To:", TRUE);
4495         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
4496         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
4497                                 "Followup-To:", FALSE);
4498         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
4499
4500         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
4501
4502         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
4503                            GTK_SIGNAL_FUNC(to_activated), compose);
4504         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
4505                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
4506         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
4507                            GTK_SIGNAL_FUNC(subject_activated), compose);
4508         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
4509                            GTK_SIGNAL_FUNC(cc_activated), compose);
4510         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
4511                            GTK_SIGNAL_FUNC(bcc_activated), compose);
4512         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
4513                            GTK_SIGNAL_FUNC(replyto_activated), compose);
4514         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
4515                            GTK_SIGNAL_FUNC(followupto_activated), compose);
4516
4517         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
4518                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4519         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
4520                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4521         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
4522                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4523         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
4524                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4525         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
4526                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4527         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
4528                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4529         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
4530                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4531 #endif
4532
4533         compose->table            = NULL;
4534 #if 0 /* NEW COMPOSE GUI */
4535         compose->table            = table;
4536         compose->to_hbox          = to_hbox;
4537         compose->to_entry         = to_entry;
4538         compose->newsgroups_hbox  = newsgroups_hbox;
4539         compose->newsgroups_entry = newsgroups_entry;
4540 #endif
4541 #if 0 /* NEW COMPOSE GUI */
4542         compose->cc_hbox          = cc_hbox;
4543         compose->cc_entry         = cc_entry;
4544         compose->bcc_hbox         = bcc_hbox;
4545         compose->bcc_entry        = bcc_entry;
4546         compose->reply_hbox       = reply_hbox;
4547         compose->reply_entry      = reply_entry;
4548         compose->followup_hbox    = followup_hbox;
4549         compose->followup_entry   = followup_entry;
4550 #endif
4551
4552         return header_scrolledwin ;
4553 }
4554
4555 GtkWidget *compose_create_attach(Compose *compose)
4556 {
4557         gchar *titles[N_ATTACH_COLS];
4558         gint i;
4559
4560         GtkWidget *attach_scrwin;
4561         GtkWidget *attach_clist;
4562
4563         titles[COL_MIMETYPE] = _("MIME type");
4564         titles[COL_SIZE]     = _("Size");
4565         titles[COL_NAME]     = _("Name");
4566
4567         /* attachment list */
4568         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
4569         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
4570                                        GTK_POLICY_AUTOMATIC,
4571                                        GTK_POLICY_ALWAYS);
4572         gtk_widget_set_usize(attach_scrwin, -1, 80);
4573
4574         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
4575         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
4576                                            GTK_JUSTIFY_RIGHT);
4577         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
4578         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
4579         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
4580                                      GTK_SELECTION_EXTENDED);
4581         for (i = 0; i < N_ATTACH_COLS; i++)
4582                 GTK_WIDGET_UNSET_FLAGS
4583                         (GTK_CLIST(attach_clist)->column[i].button,
4584                          GTK_CAN_FOCUS);
4585         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
4586
4587         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4588                            GTK_SIGNAL_FUNC(attach_selected), compose);
4589         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4590                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4591         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4592                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4593
4594         /* drag and drop */
4595         gtk_drag_dest_set(attach_clist,
4596                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4597                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4598         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4599                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4600                            compose);
4601
4602         compose->attach_scrwin = attach_scrwin;
4603         compose->attach_clist  = attach_clist;
4604
4605         return attach_scrwin;
4606 }
4607
4608 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4609 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4610
4611 static GtkWidget *compose_create_others(Compose *compose)
4612 {
4613         GtkWidget *table;
4614         GtkWidget *savemsg_checkbtn;
4615         GtkWidget *savemsg_entry;
4616         GtkWidget *savemsg_select;
4617         
4618         guint rowcount = 0;
4619         gchar *folderidentifier;
4620
4621         /* Table for settings */
4622         table = gtk_table_new(3, 1, FALSE);
4623         gtk_widget_show(table);
4624         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4625         rowcount = 0;
4626
4627         /* Save Message to folder */
4628         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4629         gtk_widget_show(savemsg_checkbtn);
4630         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4631         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4632                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4633         }
4634         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4635                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4636
4637         savemsg_entry = gtk_entry_new();
4638         gtk_widget_show(savemsg_entry);
4639         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4640         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4641         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4642                 folderidentifier = folder_item_get_identifier(account_get_special_folder
4643                                   (compose->account, F_OUTBOX));
4644                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4645                 g_free(folderidentifier);
4646         }
4647
4648         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4649         gtk_widget_show (savemsg_select);
4650         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4651         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4652                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4653                             compose);
4654
4655         rowcount++;
4656
4657         compose->savemsg_checkbtn = savemsg_checkbtn;
4658         compose->savemsg_entry = savemsg_entry;
4659
4660         return table;   
4661 }
4662
4663 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4664 {
4665         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4666                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4667 }
4668
4669 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4670 {
4671         FolderItem *dest;
4672         gchar * path;
4673
4674         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
4675         if (!dest) return;
4676
4677         path = folder_item_get_identifier(dest);
4678
4679         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4680         g_free(path);
4681 }
4682
4683 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4684 {
4685         Compose   *compose;
4686         GtkWidget *window;
4687         GtkWidget *vbox;
4688         GtkWidget *menubar;
4689         GtkWidget *handlebox;
4690
4691         GtkWidget *notebook;
4692
4693         GtkWidget *vbox2;
4694
4695         GtkWidget *label;
4696         GtkWidget *subject_hbox;
4697         GtkWidget *subject_frame;
4698         GtkWidget *subject_entry;
4699         GtkWidget *subject;
4700         GtkWidget *paned;
4701
4702         GtkWidget *edit_vbox;
4703         GtkWidget *ruler_hbox;
4704         GtkWidget *ruler;
4705         GtkWidget *scrolledwin;
4706         GtkWidget *text;
4707
4708         UndoMain *undostruct;
4709
4710         gchar *titles[N_ATTACH_COLS];
4711         guint n_menu_entries;
4712         GtkStyle  *style, *new_style;
4713         GdkColormap *cmap;
4714         GdkColor color[1];
4715         gboolean success[1];
4716         GtkWidget *popupmenu;
4717         GtkItemFactory *popupfactory;
4718         GtkItemFactory *ifactory;
4719         GtkWidget *tmpl_menu;
4720         gint n_entries;
4721
4722 #if USE_ASPELL
4723         GtkAspell * gtkaspell = NULL;
4724 #endif
4725
4726         static GdkGeometry geometry;
4727
4728         g_return_val_if_fail(account != NULL, NULL);
4729
4730         debug_print("Creating compose window...\n");
4731         compose = g_new0(Compose, 1);
4732
4733         titles[COL_MIMETYPE] = _("MIME type");
4734         titles[COL_SIZE]     = _("Size");
4735         titles[COL_NAME]     = _("Name");
4736
4737         compose->account = account;
4738
4739         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4740         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4741         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4742         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4743
4744         if (!geometry.max_width) {
4745                 geometry.max_width = gdk_screen_width();
4746                 geometry.max_height = gdk_screen_height();
4747         }
4748         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
4749                                       &geometry, GDK_HINT_MAX_SIZE);
4750
4751         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4752                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4753         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4754                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4755         MANAGE_WINDOW_SIGNALS_CONNECT(window);
4756         gtk_widget_realize(window);
4757
4758         gtkut_widget_set_composer_icon(window);
4759
4760         vbox = gtk_vbox_new(FALSE, 0);
4761         gtk_container_add(GTK_CONTAINER(window), vbox);
4762
4763         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4764         menubar = menubar_create(window, compose_entries,
4765                                  n_menu_entries, "<Compose>", compose);
4766         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4767
4768         handlebox = gtk_handle_box_new();
4769         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4770
4771         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
4772                                           (gpointer)compose);
4773
4774         vbox2 = gtk_vbox_new(FALSE, 2);
4775         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4776         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4777         
4778         /* Notebook */
4779         notebook = gtk_notebook_new();
4780         gtk_widget_set_usize(notebook, -1, 130);
4781         gtk_widget_show(notebook);
4782
4783         /* header labels and entries */
4784         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4785         /* attachment list */
4786         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4787         /* Others Tab */
4788         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4789
4790         /* Subject */
4791         subject_hbox = gtk_hbox_new(FALSE, 0);
4792         gtk_widget_show(subject_hbox);
4793
4794         subject_frame = gtk_frame_new(NULL);
4795         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4796         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4797         gtk_widget_show(subject_frame);
4798
4799         subject = gtk_hbox_new(FALSE, 0);
4800         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4801         gtk_widget_show(subject);
4802
4803         label = gtk_label_new(_("Subject:"));
4804         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4805         gtk_widget_show(label);
4806
4807         subject_entry = gtk_entry_new();
4808         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4809         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4810         gtk_widget_show(subject_entry);
4811         compose->subject_entry = subject_entry;
4812         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4813         
4814         edit_vbox = gtk_vbox_new(FALSE, 0);
4815 #if 0 /* NEW COMPOSE GUI */
4816         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
4817 #endif
4818
4819         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4820
4821         /* ruler */
4822         ruler_hbox = gtk_hbox_new(FALSE, 0);
4823         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4824
4825         ruler = gtk_shruler_new();
4826         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4827         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4828                            BORDER_WIDTH + 1);
4829         gtk_widget_set_usize(ruler_hbox, 1, -1);
4830
4831         /* text widget */
4832         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4833         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4834                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4835         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4836         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4837
4838         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4839                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4840                             gtk_scrolled_window_get_vadjustment
4841                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4842         GTK_STEXT(text)->default_tab_width = 8;
4843         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4844
4845         if (prefs_common.block_cursor) {
4846                 GTK_STEXT(text)->cursor_type = GTK_STEXT_CURSOR_BLOCK;
4847         }
4848         
4849         if (prefs_common.smart_wrapping) {      
4850                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
4851                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
4852         }               
4853
4854         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4855
4856         gtk_signal_connect(GTK_OBJECT(text), "changed",
4857                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4858         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4859                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4860         gtk_signal_connect(GTK_OBJECT(text), "activate",
4861                            GTK_SIGNAL_FUNC(text_activated), compose);
4862         gtk_signal_connect(GTK_OBJECT(text), "insert_text",
4863                            GTK_SIGNAL_FUNC(text_inserted), compose);
4864         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4865                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4866                                  edit_vbox);
4867 #if 0
4868         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4869                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4870                                  compose);
4871 #endif
4872         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4873                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4874                                  ruler);
4875
4876         /* drag and drop */
4877         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4878                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4879         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4880                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4881                            compose);
4882         gtk_widget_show_all(vbox);
4883
4884         /* pane between attach clist and text */
4885         paned = gtk_vpaned_new();
4886         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4887         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4888         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4889         gtk_paned_add1(GTK_PANED(paned), notebook);
4890         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4891         gtk_widget_show_all(paned);
4892
4893         style = gtk_widget_get_style(text);
4894
4895         /* workaround for the slow down of GtkSText when using Pixmap theme */
4896         if (style->engine) {
4897                 GtkThemeEngine *engine;
4898
4899                 engine = style->engine;
4900                 style->engine = NULL;
4901                 new_style = gtk_style_copy(style);
4902                 style->engine = engine;
4903         } else
4904                 new_style = gtk_style_copy(style);
4905
4906         if (prefs_common.textfont) {
4907                 GdkFont *font;
4908
4909                 if ((font = gtkut_font_load(prefs_common.textfont)) != NULL) {
4910                         gdk_font_unref(new_style->font);
4911                         new_style->font = font;
4912                 }
4913         }
4914
4915         gtk_widget_set_style(text, new_style);
4916
4917         color[0] = quote_color;
4918         cmap = gdk_window_get_colormap(window->window);
4919         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4920         if (success[0] == FALSE) {
4921                 g_warning("Compose: color allocation failed.\n");
4922                 style = gtk_widget_get_style(text);
4923                 quote_color = style->black;
4924         }
4925
4926         n_entries = sizeof(compose_popup_entries) /
4927                 sizeof(compose_popup_entries[0]);
4928         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4929                                       "<Compose>", &popupfactory,
4930                                       compose);
4931
4932         ifactory = gtk_item_factory_from_widget(menubar);
4933         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4934         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4935
4936         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
4937 #if 0 /* NEW COMPOSE GUI */
4938         gtk_widget_hide(bcc_hbox);
4939         gtk_widget_hide(bcc_entry);
4940         gtk_widget_hide(reply_hbox);
4941         gtk_widget_hide(reply_entry);
4942         gtk_widget_hide(followup_hbox);
4943         gtk_widget_hide(followup_entry);
4944         gtk_widget_hide(ruler_hbox);
4945         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4946         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4947         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4948
4949         if (account->protocol == A_NNTP) {
4950                 gtk_widget_hide(to_hbox);
4951                 gtk_widget_hide(to_entry);
4952                 gtk_widget_hide(cc_hbox);
4953                 gtk_widget_hide(cc_entry);
4954                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
4955                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
4956         } else {
4957                 gtk_widget_hide(newsgroups_hbox);
4958                 gtk_widget_hide(newsgroups_entry);
4959                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
4960         }
4961 #endif
4962
4963         update_compose_actions_menu(ifactory, "/Tools/Actions", compose);
4964
4965
4966         undostruct = undo_init(text);
4967         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
4968                                    menubar);
4969
4970         address_completion_start(window);
4971
4972         compose->window        = window;
4973         compose->vbox          = vbox;
4974         compose->menubar       = menubar;
4975         compose->handlebox     = handlebox;
4976
4977         compose->vbox2         = vbox2;
4978
4979         compose->paned = paned;
4980
4981         compose->edit_vbox     = edit_vbox;
4982         compose->ruler_hbox    = ruler_hbox;
4983         compose->ruler         = ruler;
4984         compose->scrolledwin   = scrolledwin;
4985         compose->text          = text;
4986
4987         compose->focused_editable = NULL;
4988
4989         compose->popupmenu    = popupmenu;
4990         compose->popupfactory = popupfactory;
4991
4992         compose->tmpl_menu = tmpl_menu;
4993
4994         compose->mode = mode;
4995
4996         compose->targetinfo = NULL;
4997         compose->replyinfo  = NULL;
4998         compose->fwdinfo    = NULL;
4999
5000         compose->replyto     = NULL;
5001         compose->cc          = NULL;
5002         compose->bcc         = NULL;
5003         compose->followup_to = NULL;
5004
5005         compose->ml_post     = NULL;
5006
5007         compose->inreplyto   = NULL;
5008         compose->references  = NULL;
5009         compose->msgid       = NULL;
5010         compose->boundary    = NULL;
5011
5012 #if USE_GPGME
5013         compose->use_signing    = FALSE;
5014         compose->use_encryption = FALSE;
5015 #endif /* USE_GPGME */
5016
5017         compose->modified = FALSE;
5018
5019         compose->return_receipt = FALSE;
5020         compose->paste_as_quotation = FALSE;
5021
5022         compose->to_list        = NULL;
5023         compose->newsgroup_list = NULL;
5024
5025         compose->exteditor_file    = NULL;
5026         compose->exteditor_pid     = -1;
5027         compose->exteditor_readdes = -1;
5028         compose->exteditor_tag     = -1;
5029
5030         compose->redirect_filename = NULL;
5031         compose->undostruct = undostruct;
5032 #if USE_ASPELL
5033         menu_set_sensitive(ifactory, "/Spelling", FALSE);
5034         if (mode != COMPOSE_REDIRECT) {
5035                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
5036                     strcmp(prefs_common.dictionary, _("None"))) {
5037                         gtkaspell = gtkaspell_new((const gchar*)prefs_common.dictionary,
5038                                                   conv_get_current_charset_str(),
5039                                                   prefs_common.misspelled_col,
5040                                                   prefs_common.check_while_typing,
5041                                                   prefs_common.use_alternate,
5042                                                   GTK_STEXT(text));
5043                         if (!gtkaspell) {
5044                                 alertpanel_error(_("Spell checker could not be started.\n%s"), gtkaspellcheckers->error_message);
5045                                 gtkaspell_checkers_reset_error();
5046                         } else {
5047
5048                                 GtkWidget *menuitem;
5049
5050                                 if (!gtkaspell_set_sug_mode(gtkaspell, prefs_common.aspell_sugmode)) {
5051                                         debug_print("Aspell: could not set suggestion mode %s\n",
5052                                         gtkaspellcheckers->error_message);
5053                                         gtkaspell_checkers_reset_error();
5054                                 }
5055
5056                                 menuitem = gtk_item_factory_get_item(ifactory, "/Spelling/Spelling Configuration");
5057                                 gtkaspell_populate_submenu(gtkaspell, menuitem);
5058                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
5059                                 }
5060                 }
5061         }
5062 #endif
5063
5064         compose_select_account(compose, account);
5065
5066 #if USE_ASPELL
5067         compose->gtkaspell      = gtkaspell;
5068 #endif
5069
5070         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
5071                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
5072
5073         if (account->set_autobcc) 
5074                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
5075         
5076         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
5077                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
5078
5079
5080         if (account->protocol != A_NNTP)
5081                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
5082         else
5083                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
5084
5085         addressbook_set_target_compose(compose);
5086         update_compose_actions_menu(ifactory, "/Tools/Actions", compose);
5087         
5088         if (mode != COMPOSE_REDIRECT)
5089                 compose_set_template_menu(compose);
5090         else {
5091                 GtkWidget *menuitem;
5092                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5093                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
5094         }
5095
5096         compose_list = g_list_append(compose_list, compose);
5097
5098         if (!prefs_common.show_ruler)
5099                 gtk_widget_hide(ruler_hbox);
5100
5101         /* Priority */
5102         compose->priority = PRIORITY_NORMAL;
5103         compose_update_priority_menu_item(compose);
5104         
5105 #if USE_GPGME
5106         activate_gnupg_mode(compose, account);
5107 #endif  
5108         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
5109         gtk_widget_show(window);
5110         
5111         return compose;
5112 }
5113
5114 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5115 {
5116         GList *accounts;
5117         GtkWidget *hbox;
5118         GtkWidget *optmenu;
5119         GtkWidget *menu;
5120         gint num = 0, def_menu = 0;
5121
5122         accounts = account_get_list();
5123         g_return_val_if_fail(accounts != NULL, NULL);
5124
5125         hbox = gtk_hbox_new(FALSE, 0);
5126         optmenu = gtk_option_menu_new();
5127         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5128         menu = gtk_menu_new();
5129
5130         for (; accounts != NULL; accounts = accounts->next, num++) {
5131                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5132                 GtkWidget *menuitem;
5133                 gchar *name;
5134
5135                 if (ac == compose->account) def_menu = num;
5136
5137                 if (ac->name)
5138                         name = g_strdup_printf("%s: %s <%s>",
5139                                                ac->account_name,
5140                                                ac->name, ac->address);
5141                 else
5142                         name = g_strdup_printf("%s: %s",
5143                                                ac->account_name, ac->address);
5144                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
5145                 g_free(name);
5146                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
5147                                    GTK_SIGNAL_FUNC(account_activated),
5148                                    compose);
5149         }
5150
5151         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5152         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5153
5154         return hbox;
5155 }
5156
5157 static void compose_set_priority_cb(gpointer data,
5158                                     guint action,
5159                                     GtkWidget *widget)
5160 {
5161         Compose *compose = (Compose *) data;
5162         compose->priority = action;
5163 }
5164
5165 static void compose_update_priority_menu_item(Compose * compose)
5166 {
5167         GtkItemFactory *ifactory;
5168         GtkWidget *menuitem = NULL;
5169
5170         ifactory = gtk_item_factory_from_widget(compose->menubar);
5171         
5172         switch (compose->priority) {
5173                 case PRIORITY_HIGHEST:
5174                         menuitem = gtk_item_factory_get_item
5175                                 (ifactory, "/Message/Priority/Highest");
5176                         break;
5177                 case PRIORITY_HIGH:
5178                         menuitem = gtk_item_factory_get_item
5179                                 (ifactory, "/Message/Priority/High");
5180                         break;
5181                 case PRIORITY_NORMAL:
5182                         menuitem = gtk_item_factory_get_item
5183                                 (ifactory, "/Message/Priority/Normal");
5184                         break;
5185                 case PRIORITY_LOW:
5186                         menuitem = gtk_item_factory_get_item
5187                                 (ifactory, "/Message/Priority/Low");
5188                         break;
5189                 case PRIORITY_LOWEST:
5190                         menuitem = gtk_item_factory_get_item
5191                                 (ifactory, "/Message/Priority/Lowest");
5192                         break;
5193         }
5194         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5195 }       
5196
5197 #if USE_GPGME 
5198 static void compose_set_gnupg_mode_cb(gpointer data,
5199                                     guint action,
5200                                     GtkWidget *widget)
5201 {
5202         Compose *compose = (Compose *) data;
5203         compose->gnupg_mode = action;
5204 }
5205
5206 static void compose_update_gnupg_mode_menu_item(Compose * compose)
5207 {
5208         GtkItemFactory *ifactory;
5209         GtkWidget *menuitem = NULL;
5210
5211         ifactory = gtk_item_factory_from_widget(compose->menubar);
5212         
5213         switch (compose->gnupg_mode) {
5214                 case GNUPG_MODE_DETACH:
5215                         menuitem = gtk_item_factory_get_item
5216                                 (ifactory, "/Message/Mode/MIME");
5217                         break;
5218                 case GNUPG_MODE_INLINE:
5219                         menuitem = gtk_item_factory_get_item
5220                                 (ifactory, "/Message/Mode/Inline");
5221                         break;
5222         }
5223         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5224         
5225         if (compose->use_encryption == TRUE || compose->use_signing == TRUE)
5226                 menu_set_sensitive(ifactory, "/Message/Mode", TRUE);
5227         else 
5228                 menu_set_sensitive(ifactory, "/Message/Mode", FALSE);
5229 }       
5230 #endif
5231  
5232 static void compose_set_template_menu(Compose *compose)
5233 {
5234         GSList *tmpl_list, *cur;
5235         GtkWidget *menu;
5236         GtkWidget *item;
5237
5238         tmpl_list = template_get_config();
5239
5240         menu = gtk_menu_new();
5241
5242         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5243                 Template *tmpl = (Template *)cur->data;
5244
5245                 item = gtk_menu_item_new_with_label(tmpl->name);
5246                 gtk_menu_append(GTK_MENU(menu), item);
5247                 gtk_signal_connect(GTK_OBJECT(item), "activate",
5248                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
5249                                    compose);
5250                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
5251                 gtk_widget_show(item);
5252         }
5253
5254         gtk_widget_show(menu);
5255         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5256 }
5257
5258 void compose_reflect_prefs_all(void)
5259 {
5260         GList *cur;
5261         Compose *compose;
5262
5263         for (cur = compose_list; cur != NULL; cur = cur->next) {
5264                 compose = (Compose *)cur->data;
5265                 compose_set_template_menu(compose);
5266         }
5267 }
5268
5269 void compose_reflect_prefs_pixmap_theme(void)
5270 {
5271         GList *cur;
5272         Compose *compose;
5273
5274         for (cur = compose_list; cur != NULL; cur = cur->next) {
5275                 compose = (Compose *)cur->data;
5276                 toolbar_update(TOOLBAR_COMPOSE, compose);
5277         }
5278 }
5279
5280 static void compose_template_apply(Compose *compose, Template *tmpl,
5281                                    gboolean replace)
5282 {
5283         gchar *qmark;
5284         gchar *parsed_str;
5285
5286         if (!tmpl || !tmpl->value) return;
5287
5288         gtk_stext_freeze(GTK_STEXT(compose->text));
5289
5290         if (tmpl->subject && *tmpl->subject != '\0')
5291                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
5292                                    tmpl->subject);
5293         if (tmpl->to && *tmpl->to != '\0')
5294                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
5295         if (tmpl->cc && *tmpl->cc != '\0')
5296                 compose_entry_append(compose, tmpl->cc, COMPOSE_CC);
5297
5298         if (tmpl->bcc && *tmpl->bcc != '\0')
5299                 compose_entry_append(compose, tmpl->bcc, COMPOSE_BCC);
5300
5301         if (replace)
5302                 gtk_stext_clear(GTK_STEXT(compose->text));
5303
5304         if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
5305                 parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
5306                                                NULL, NULL);
5307         } else {
5308                 if (prefs_common.quotemark && *prefs_common.quotemark)
5309                         qmark = prefs_common.quotemark;
5310                 else
5311                         qmark = "> ";
5312
5313                 if (compose->replyinfo != NULL)
5314                         parsed_str = compose_quote_fmt(compose, compose->replyinfo,
5315                                                        tmpl->value, qmark, NULL);
5316                 else if (compose->fwdinfo != NULL)
5317                         parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
5318                                                        tmpl->value, qmark, NULL);
5319                 else
5320                         parsed_str = NULL;
5321         }
5322
5323         if (replace && parsed_str && compose->account->auto_sig)
5324                 compose_insert_sig(compose);
5325
5326         if (replace && parsed_str) {
5327                 gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
5328                 gtk_stext_set_point(GTK_STEXT(compose->text), 0);
5329         }
5330
5331         if (parsed_str)
5332                 compose_changed_cb(NULL, compose);
5333
5334         gtk_stext_thaw(GTK_STEXT(compose->text));
5335 }
5336
5337 static void compose_destroy(Compose *compose)
5338 {
5339         gint row;
5340         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5341         AttachInfo *ainfo;
5342
5343         /* NOTE: address_completion_end() does nothing with the window
5344          * however this may change. */
5345         address_completion_end(compose->window);
5346
5347         slist_free_strings(compose->to_list);
5348         g_slist_free(compose->to_list);
5349         slist_free_strings(compose->newsgroup_list);
5350         g_slist_free(compose->newsgroup_list);
5351         slist_free_strings(compose->header_list);
5352         g_slist_free(compose->header_list);
5353
5354         procmsg_msginfo_free(compose->targetinfo);
5355         procmsg_msginfo_free(compose->replyinfo);
5356         procmsg_msginfo_free(compose->fwdinfo);
5357
5358         g_free(compose->replyto);
5359         g_free(compose->cc);
5360         g_free(compose->bcc);
5361         g_free(compose->newsgroups);
5362         g_free(compose->followup_to);
5363
5364         g_free(compose->ml_post);
5365
5366         g_free(compose->inreplyto);
5367         g_free(compose->references);
5368         g_free(compose->msgid);
5369         g_free(compose->boundary);
5370
5371         if (compose->redirect_filename)
5372                 g_free(compose->redirect_filename);
5373
5374         g_free(compose->exteditor_file);
5375
5376         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
5377              row++)
5378                 compose_attach_info_free(ainfo);
5379
5380         if (addressbook_get_target_compose() == compose)
5381                 addressbook_set_target_compose(NULL);
5382
5383 #if USE_ASPELL
5384         if (compose->gtkaspell) {
5385                 gtkaspell_delete(compose->gtkaspell);
5386         }
5387 #endif
5388
5389         prefs_common.compose_width = compose->scrolledwin->allocation.width;
5390         prefs_common.compose_height = compose->window->allocation.height;
5391
5392         gtk_widget_destroy(compose->paned);
5393
5394         toolbar_destroy(compose->toolbar);
5395         g_free(compose->toolbar);
5396         g_free(compose);
5397
5398         compose_list = g_list_remove(compose_list, compose);
5399 }
5400
5401 static void compose_attach_info_free(AttachInfo *ainfo)
5402 {
5403         g_free(ainfo->file);
5404         g_free(ainfo->content_type);
5405         g_free(ainfo->name);
5406         g_free(ainfo);
5407 }
5408
5409 static void compose_attach_remove_selected(Compose *compose)
5410 {
5411         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5412         AttachInfo *ainfo;
5413         gint row;
5414
5415         while (clist->selection != NULL) {
5416                 row = GPOINTER_TO_INT(clist->selection->data);
5417                 ainfo = gtk_clist_get_row_data(clist, row);
5418                 compose_attach_info_free(ainfo);
5419                 gtk_clist_remove(clist, row);
5420         }
5421 }
5422
5423 static struct _AttachProperty
5424 {
5425         GtkWidget *window;
5426         GtkWidget *mimetype_entry;
5427         GtkWidget *encoding_optmenu;
5428         GtkWidget *path_entry;
5429         GtkWidget *filename_entry;
5430         GtkWidget *ok_btn;
5431         GtkWidget *cancel_btn;
5432 } attach_prop;
5433
5434 static void compose_attach_property(Compose *compose)
5435 {
5436         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5437         AttachInfo *ainfo;
5438         gint row;
5439         GtkOptionMenu *optmenu;
5440         static gboolean cancelled;
5441
5442         if (!clist->selection) return;
5443         row = GPOINTER_TO_INT(clist->selection->data);
5444
5445         ainfo = gtk_clist_get_row_data(clist, row);
5446         if (!ainfo) return;
5447
5448         if (!attach_prop.window)
5449                 compose_attach_property_create(&cancelled);
5450         gtk_widget_grab_focus(attach_prop.ok_btn);
5451         gtk_widget_show(attach_prop.window);
5452         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
5453
5454         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
5455         if (ainfo->encoding == ENC_UNKNOWN)
5456                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5457                                     GINT_TO_POINTER(ENC_BASE64));
5458         else
5459                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5460                                     GINT_TO_POINTER(ainfo->encoding));
5461
5462         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
5463                            ainfo->content_type ? ainfo->content_type : "");
5464         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
5465                            ainfo->file ? ainfo->file : "");
5466         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
5467                            ainfo->name ? ainfo->name : "");
5468
5469         for (;;) {
5470                 gchar *text;
5471                 gchar *cnttype = NULL;
5472                 gchar *file = NULL;
5473                 off_t size = 0;
5474                 GtkWidget *menu;
5475                 GtkWidget *menuitem;
5476
5477                 cancelled = FALSE;
5478                 gtk_main();
5479
5480                 if (cancelled == TRUE) {
5481                         gtk_widget_hide(attach_prop.window);
5482                         break;
5483                 }
5484
5485                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
5486                 if (*text != '\0') {
5487                         gchar *p;
5488
5489                         text = g_strstrip(g_strdup(text));
5490                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
5491                                 cnttype = g_strdup(text);
5492                                 g_free(text);
5493                         } else {
5494                                 alertpanel_error(_("Invalid MIME type."));
5495                                 g_free(text);
5496                                 continue;
5497                         }
5498                 }
5499
5500                 menu = gtk_option_menu_get_menu(optmenu);
5501                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
5502                 ainfo->encoding = GPOINTER_TO_INT
5503                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
5504
5505                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
5506                 if (*text != '\0') {
5507                         if (is_file_exist(text) &&
5508                             (size = get_file_size(text)) > 0)
5509                                 file = g_strdup(text);
5510                         else {
5511                                 alertpanel_error
5512                                         (_("File doesn't exist or is empty."));
5513                                 g_free(cnttype);
5514                                 continue;
5515                         }
5516                 }
5517
5518                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
5519                 if (*text != '\0') {
5520                         g_free(ainfo->name);
5521                         ainfo->name = g_strdup(text);
5522                 }
5523
5524                 if (cnttype) {
5525                         g_free(ainfo->content_type);
5526                         ainfo->content_type = cnttype;
5527                 }
5528                 if (file) {
5529                         g_free(ainfo->file);
5530                         ainfo->file = file;
5531                 }
5532                 if (size)
5533                         ainfo->size = size;
5534
5535                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5536                                    ainfo->content_type);
5537                 gtk_clist_set_text(clist, row, COL_SIZE,
5538                                    to_human_readable(ainfo->size));
5539                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5540
5541                 gtk_widget_hide(attach_prop.window);
5542                 break;
5543         }
5544 }
5545
5546 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5547 { \
5548         label = gtk_label_new(str); \
5549         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5550                          GTK_FILL, 0, 0, 0); \
5551         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5552  \
5553         entry = gtk_entry_new(); \
5554         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5555                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5556 }
5557
5558 static void compose_attach_property_create(gboolean *cancelled)
5559 {
5560         GtkWidget *window;
5561         GtkWidget *vbox;
5562         GtkWidget *table;
5563         GtkWidget *label;
5564         GtkWidget *mimetype_entry;
5565         GtkWidget *hbox;
5566         GtkWidget *optmenu;
5567         GtkWidget *optmenu_menu;
5568         GtkWidget *menuitem;
5569         GtkWidget *path_entry;
5570         GtkWidget *filename_entry;
5571         GtkWidget *hbbox;
5572         GtkWidget *ok_btn;
5573         GtkWidget *cancel_btn;
5574         GList     *mime_type_list, *strlist;
5575
5576         debug_print("Creating attach_property window...\n");
5577
5578         window = gtk_window_new(GTK_WINDOW_DIALOG);
5579         gtk_widget_set_usize(window, 480, -1);
5580         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5581         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
5582         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5583         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5584         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5585                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5586                            cancelled);
5587         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5588                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5589                            cancelled);
5590
5591         vbox = gtk_vbox_new(FALSE, 8);
5592         gtk_container_add(GTK_CONTAINER(window), vbox);
5593
5594         table = gtk_table_new(4, 2, FALSE);
5595         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5596         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5597         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5598
5599         label = gtk_label_new(_("MIME type")); 
5600         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5601                          GTK_FILL, 0, 0, 0); 
5602         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5603         mimetype_entry = gtk_combo_new(); 
5604         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5605                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5606                          
5607         /* stuff with list */
5608         mime_type_list = procmime_get_mime_type_list();
5609         strlist = NULL;
5610         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5611                 MimeType *type = (MimeType *) mime_type_list->data;
5612                 strlist = g_list_append(strlist, 
5613                                 g_strdup_printf("%s/%s",
5614                                         type->type, type->sub_type));
5615         }
5616         
5617         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5618
5619         for (mime_type_list = strlist; mime_type_list != NULL; 
5620                 mime_type_list = mime_type_list->next)
5621                 g_free(mime_type_list->data);
5622         g_list_free(strlist);
5623                          
5624         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5625
5626         label = gtk_label_new(_("Encoding"));
5627         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5628                          GTK_FILL, 0, 0, 0);
5629         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5630
5631         hbox = gtk_hbox_new(FALSE, 0);
5632         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5633                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5634
5635         optmenu = gtk_option_menu_new();
5636         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
5637
5638         optmenu_menu = gtk_menu_new();
5639         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5640         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5641 #if 0
5642         gtk_widget_set_sensitive(menuitem, FALSE);
5643 #endif
5644         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
5645         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5646 #if 0
5647         gtk_widget_set_sensitive(menuitem, FALSE);
5648 #endif
5649         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable",
5650                      ENC_QUOTED_PRINTABLE);
5651         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5652
5653         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5654
5655         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5656
5657         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5658         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5659
5660         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5661                                 &cancel_btn, _("Cancel"), NULL, NULL);
5662         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5663         gtk_widget_grab_default(ok_btn);
5664
5665         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5666                            GTK_SIGNAL_FUNC(attach_property_ok),
5667                            cancelled);
5668         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5669                            GTK_SIGNAL_FUNC(attach_property_cancel),
5670                            cancelled);
5671
5672         gtk_widget_show_all(vbox);
5673
5674         attach_prop.window           = window;
5675         attach_prop.mimetype_entry   = mimetype_entry;
5676         attach_prop.encoding_optmenu = optmenu;
5677         attach_prop.path_entry       = path_entry;
5678         attach_prop.filename_entry   = filename_entry;
5679         attach_prop.ok_btn           = ok_btn;
5680         attach_prop.cancel_btn       = cancel_btn;
5681 }
5682
5683 #undef SET_LABEL_AND_ENTRY
5684
5685 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5686 {
5687         *cancelled = FALSE;
5688         gtk_main_quit();
5689 }
5690
5691 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5692 {
5693         *cancelled = TRUE;
5694         gtk_main_quit();
5695 }
5696
5697 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5698                                          gboolean *cancelled)
5699 {
5700         *cancelled = TRUE;
5701         gtk_main_quit();
5702
5703         return TRUE;
5704 }
5705
5706 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5707                                         gboolean *cancelled)
5708 {
5709         if (event && event->keyval == GDK_Escape) {
5710                 *cancelled = TRUE;
5711                 gtk_main_quit();
5712         }
5713 }
5714
5715 static void compose_exec_ext_editor(Compose *compose)
5716 {
5717         gchar *tmp;
5718         pid_t pid;
5719         gint pipe_fds[2];
5720
5721         tmp = g_strdup_printf("%s%ctmpmsg.%08x", get_tmp_dir(),
5722                               G_DIR_SEPARATOR, (gint)compose);
5723
5724         if (pipe(pipe_fds) < 0) {
5725                 perror("pipe");
5726                 g_free(tmp);
5727                 return;
5728         }
5729
5730         if ((pid = fork()) < 0) {
5731                 perror("fork");
5732                 g_free(tmp);
5733                 return;
5734         }
5735
5736         if (pid != 0) {
5737                 /* close the write side of the pipe */
5738                 close(pipe_fds[1]);
5739
5740                 compose->exteditor_file    = g_strdup(tmp);
5741                 compose->exteditor_pid     = pid;
5742                 compose->exteditor_readdes = pipe_fds[0];
5743
5744                 compose_set_ext_editor_sensitive(compose, FALSE);
5745
5746                 compose->exteditor_tag =
5747                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5748                                       compose_input_cb, compose);
5749         } else {        /* process-monitoring process */
5750                 pid_t pid_ed;
5751
5752                 if (setpgid(0, 0))
5753                         perror("setpgid");
5754
5755                 /* close the read side of the pipe */
5756                 close(pipe_fds[0]);
5757
5758                 if (compose_write_body_to_file(compose, tmp) < 0) {
5759                         fd_write(pipe_fds[1], "2\n", 2);
5760                         _exit(1);
5761                 }
5762
5763                 pid_ed = compose_exec_ext_editor_real(tmp);
5764                 if (pid_ed < 0) {
5765                         fd_write(pipe_fds[1], "1\n", 2);
5766                         _exit(1);
5767                 }
5768
5769                 /* wait until editor is terminated */
5770                 waitpid(pid_ed, NULL, 0);
5771
5772                 fd_write(pipe_fds[1], "0\n", 2);
5773
5774                 close(pipe_fds[1]);
5775                 _exit(0);
5776         }
5777
5778         g_free(tmp);
5779 }
5780
5781 static gint compose_exec_ext_editor_real(const gchar *file)
5782 {
5783         static gchar *def_cmd = "emacs %s";
5784         gchar buf[1024];
5785         gchar *p;
5786         gchar **cmdline;
5787         pid_t pid;
5788
5789         g_return_val_if_fail(file != NULL, -1);
5790
5791         if ((pid = fork()) < 0) {
5792                 perror("fork");
5793                 return -1;
5794         }
5795
5796         if (pid != 0) return pid;
5797
5798         /* grandchild process */
5799
5800         if (setpgid(0, getppid()))
5801                 perror("setpgid");
5802
5803         if (prefs_common.ext_editor_cmd &&
5804             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5805             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5806                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5807         } else {
5808                 if (prefs_common.ext_editor_cmd)
5809                         g_warning("External editor command line is invalid: `%s'\n",
5810                                   prefs_common.ext_editor_cmd);
5811                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5812         }
5813
5814         cmdline = strsplit_with_quote(buf, " ", 1024);
5815         execvp(cmdline[0], cmdline);
5816
5817         perror("execvp");
5818         g_strfreev(cmdline);
5819
5820         _exit(1);
5821 }
5822
5823 static gboolean compose_ext_editor_kill(Compose *compose)
5824 {
5825         pid_t pgid = compose->exteditor_pid * -1;
5826         gint ret;
5827
5828         ret = kill(pgid, 0);
5829
5830         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5831                 AlertValue val;
5832                 gchar *msg;
5833
5834                 msg = g_strdup_printf
5835                         (_("The external editor is still working.\n"
5836                            "Force terminating the process?\n"
5837                            "process group id: %d"), -pgid);
5838                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5839                 g_free(msg);
5840
5841                 if (val == G_ALERTDEFAULT) {
5842                         gdk_input_remove(compose->exteditor_tag);
5843                         close(compose->exteditor_readdes);
5844
5845                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5846                         waitpid(compose->exteditor_pid, NULL, 0);
5847
5848                         g_warning("Terminated process group id: %d", -pgid);
5849                         g_warning("Temporary file: %s",
5850                                   compose->exteditor_file);
5851
5852                         compose_set_ext_editor_sensitive(compose, TRUE);
5853
5854                         g_free(compose->exteditor_file);
5855                         compose->exteditor_file    = NULL;
5856                         compose->exteditor_pid     = -1;
5857                         compose->exteditor_readdes = -1;
5858                         compose->exteditor_tag     = -1;
5859                 } else
5860                         return FALSE;
5861         }
5862
5863         return TRUE;
5864 }
5865
5866 static void compose_input_cb(gpointer data, gint source,
5867                              GdkInputCondition condition)
5868 {
5869         gchar buf[3];
5870         Compose *compose = (Compose *)data;
5871         gint i = 0;
5872
5873         debug_print("Compose: input from monitoring process\n");
5874
5875         gdk_input_remove(compose->exteditor_tag);
5876
5877         for (;;) {
5878                 if (read(source, &buf[i], 1) < 1) {
5879                         buf[0] = '3';
5880                         break;
5881                 }
5882                 if (buf[i] == '\n') {
5883                         buf[i] = '\0';
5884                         break;
5885                 }
5886                 i++;
5887                 if (i == sizeof(buf) - 1)
5888                         break;
5889         }
5890
5891         waitpid(compose->exteditor_pid, NULL, 0);
5892
5893         if (buf[0] == '0') {            /* success */
5894                 GtkSText *text = GTK_STEXT(compose->text);
5895
5896                 gtk_stext_freeze(text);
5897                 gtk_stext_set_point(text, 0);
5898                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5899                 compose_insert_file(compose, compose->exteditor_file);
5900                 compose_changed_cb(NULL, compose);
5901                 gtk_stext_thaw(text);
5902
5903                 if (unlink(compose->exteditor_file) < 0)
5904                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5905         } else if (buf[0] == '1') {     /* failed */
5906                 g_warning("Couldn't exec external editor\n");
5907                 if (unlink(compose->exteditor_file) < 0)
5908                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5909         } else if (buf[0] == '2') {
5910                 g_warning("Couldn't write to file\n");
5911         } else if (buf[0] == '3') {
5912                 g_warning("Pipe read failed\n");
5913         }
5914
5915         close(source);
5916
5917         compose_set_ext_editor_sensitive(compose, TRUE);
5918
5919         g_free(compose->exteditor_file);
5920         compose->exteditor_file    = NULL;
5921         compose->exteditor_pid     = -1;
5922         compose->exteditor_readdes = -1;
5923         compose->exteditor_tag     = -1;
5924 }
5925
5926 static void compose_set_ext_editor_sensitive(Compose *compose,
5927                                              gboolean sensitive)
5928 {
5929         GtkItemFactory *ifactory;
5930
5931         ifactory = gtk_item_factory_from_widget(compose->menubar);
5932
5933         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5934         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5935         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
5936                            sensitive);
5937         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
5938         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
5939         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
5940         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
5941         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
5942                            sensitive);
5943
5944         gtk_widget_set_sensitive(compose->text,                   sensitive);
5945         gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
5946         gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
5947         gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
5948         gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
5949         gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
5950         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
5951         gtk_widget_set_sensitive(compose->toolbar->linewrap_btn,  sensitive);
5952 }
5953
5954 /**
5955  * compose_undo_state_changed:
5956  *
5957  * Change the sensivity of the menuentries undo and redo
5958  **/
5959 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
5960                                        gint redo_state, gpointer data)
5961 {
5962         GtkWidget *widget = GTK_WIDGET(data);
5963         GtkItemFactory *ifactory;
5964
5965         g_return_if_fail(widget != NULL);
5966
5967         debug_print("Set_undo.  UNDO:%i  REDO:%i\n", undo_state, redo_state);
5968
5969         ifactory = gtk_item_factory_from_widget(widget);
5970
5971         switch (undo_state) {
5972         case UNDO_STATE_TRUE:
5973                 if (!undostruct->undo_state) {
5974                         debug_print ("Set_undo - Testpoint\n");
5975                         undostruct->undo_state = TRUE;
5976                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
5977                 }
5978                 break;
5979         case UNDO_STATE_FALSE:
5980                 if (undostruct->undo_state) {
5981                         undostruct->undo_state = FALSE;
5982                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5983                 }
5984                 break;
5985         case UNDO_STATE_UNCHANGED:
5986                 break;
5987         case UNDO_STATE_REFRESH:
5988                 menu_set_sensitive(ifactory, "/Edit/Undo",
5989                                    undostruct->undo_state);
5990                 break;
5991         default:
5992                 g_warning("Undo state not recognized");
5993                 break;
5994         }
5995
5996         switch (redo_state) {
5997         case UNDO_STATE_TRUE:
5998                 if (!undostruct->redo_state) {
5999                         undostruct->redo_state = TRUE;
6000                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
6001                 }
6002                 break;
6003         case UNDO_STATE_FALSE:
6004                 if (undostruct->redo_state) {
6005                         undostruct->redo_state = FALSE;
6006                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
6007                 }
6008                 break;
6009         case UNDO_STATE_UNCHANGED:
6010                 break;
6011         case UNDO_STATE_REFRESH:
6012                 menu_set_sensitive(ifactory, "/Edit/Redo",
6013                                    undostruct->redo_state);
6014                 break;
6015         default:
6016                 g_warning("Redo state not recognized");
6017                 break;
6018         }
6019 }
6020
6021 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
6022 {
6023         gint cursor_pos;
6024
6025         cursor_pos = (text->cursor_pos_x - extra) / char_width;
6026         cursor_pos = MAX(cursor_pos, 0);
6027
6028         return cursor_pos;
6029 }
6030
6031 /* callback functions */
6032
6033 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
6034  * includes "non-client" (windows-izm) in calculation, so this calculation
6035  * may not be accurate.
6036  */
6037 static gboolean compose_edit_size_alloc(GtkEditable *widget,
6038                                         GtkAllocation *allocation,
6039                                         GtkSHRuler *shruler)
6040 {
6041         if (prefs_common.show_ruler) {
6042                 gint char_width;
6043                 gint line_width_in_chars;
6044
6045                 char_width = gtkut_get_font_width
6046                         (GTK_WIDGET(widget)->style->font);
6047                 line_width_in_chars =
6048                         (allocation->width - allocation->x) / char_width;
6049
6050                 /* got the maximum */
6051                 gtk_ruler_set_range(GTK_RULER(shruler),
6052                                     0.0, line_width_in_chars,
6053                                     calc_cursor_xpos(GTK_STEXT(widget),
6054                                                      allocation->x,
6055                                                      char_width),
6056                                     /*line_width_in_chars*/ char_width);
6057         }
6058
6059         return TRUE;
6060 }
6061
6062 static void account_activated(GtkMenuItem *menuitem, gpointer data)
6063 {
6064         Compose *compose = (Compose *)data;
6065
6066         PrefsAccount *ac;
6067
6068         ac = account_find_from_id(
6069                 GPOINTER_TO_INT(gtk_object_get_user_data(GTK_OBJECT(menuitem))));
6070         g_return_if_fail(ac != NULL);
6071
6072         if (ac != compose->account)
6073                 compose_select_account(compose, ac);
6074 }
6075
6076 static void attach_selected(GtkCList *clist, gint row, gint column,
6077                             GdkEvent *event, gpointer data)
6078 {
6079         Compose *compose = (Compose *)data;
6080
6081         if (event && event->type == GDK_2BUTTON_PRESS)
6082                 compose_attach_property(compose);
6083 }
6084
6085 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
6086                                   gpointer data)
6087 {
6088         Compose *compose = (Compose *)data;
6089         GtkCList *clist = GTK_CLIST(compose->attach_clist);
6090         gint row, column;
6091
6092         if (!event) return;
6093
6094         if (event->button == 3) {
6095                 if ((clist->selection && !clist->selection->next) ||
6096                     !clist->selection) {
6097                         gtk_clist_unselect_all(clist);
6098                         if (gtk_clist_get_selection_info(clist,
6099                                                          event->x, event->y,
6100                                                          &row, &column)) {
6101                                 gtk_clist_select_row(clist, row, column);
6102                                 gtkut_clist_set_focus_row(clist, row);
6103                         }
6104                 }
6105                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6106                                NULL, NULL, event->button, event->time);
6107         }
6108 }
6109
6110 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6111                                gpointer data)
6112 {
6113         Compose *compose = (Compose *)data;
6114
6115         if (!event) return;
6116
6117         switch (event->keyval) {
6118         case GDK_Delete:
6119                 compose_attach_remove_selected(compose);
6120                 break;
6121         }
6122 }
6123
6124 static void compose_allow_user_actions (Compose *compose, gboolean allow)
6125 {
6126         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
6127         toolbar_comp_set_sensitive(compose, allow);
6128         menu_set_sensitive(ifactory, "/File", allow);
6129         menu_set_sensitive(ifactory, "/Edit", allow);
6130         menu_set_sensitive(ifactory, "/Spelling", allow);
6131         menu_set_sensitive(ifactory, "/Message", allow);
6132         menu_set_sensitive(ifactory, "/Tools", allow);
6133         menu_set_sensitive(ifactory, "/Help", allow);
6134 }
6135
6136 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
6137 {
6138         Compose *compose = (Compose *)data;
6139         gint val;
6140         
6141         if (prefs_common.work_offline)
6142                 if (alertpanel(_("Offline warning"), 
6143                                _("You're working offline. Override?"),
6144                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
6145                         return;
6146         
6147         compose_allow_user_actions (compose, FALSE);
6148         compose->sending = TRUE;
6149         val = compose_send(compose);
6150         compose_allow_user_actions (compose, TRUE);
6151         compose->sending = FALSE;
6152
6153         if (val == 0) gtk_widget_destroy(compose->window);
6154 }
6155
6156 static void compose_send_later_cb(gpointer data, guint action,
6157                                   GtkWidget *widget)
6158 {
6159         Compose *compose = (Compose *)data;
6160         gint val;
6161
6162         val = compose_queue_sub(compose, NULL, NULL, TRUE);
6163         if (!val) gtk_widget_destroy(compose->window);
6164 }
6165
6166 void compose_draft (gpointer data) 
6167 {
6168         compose_draft_cb(data, 0, NULL);        
6169 }
6170
6171 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
6172 {
6173         Compose *compose = (Compose *)data;
6174         FolderItem *draft;
6175         gchar *tmp;
6176         gint msgnum;
6177         static gboolean lock = FALSE;
6178         MsgInfo *newmsginfo;
6179         
6180         if (lock) return;
6181
6182         draft = account_get_special_folder(compose->account, F_DRAFT);
6183         g_return_if_fail(draft != NULL);
6184
6185         lock = TRUE;
6186
6187         tmp = g_strdup_printf("%s%cdraft.%08x", get_tmp_dir(),
6188                               G_DIR_SEPARATOR, (gint)compose);
6189
6190         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
6191                 g_free(tmp);
6192                 lock = FALSE;
6193                 return;
6194         }
6195
6196         if ((msgnum = folder_item_add_msg(draft, tmp, TRUE)) < 0) {
6197                 unlink(tmp);
6198                 g_free(tmp);
6199                 lock = FALSE;
6200                 return;
6201         }
6202         g_free(tmp);
6203         draft->mtime = 0;       /* force updating */
6204
6205         if (compose->mode == COMPOSE_REEDIT) {
6206                 compose_remove_reedit_target(compose);
6207         }
6208
6209         newmsginfo = folder_item_get_msginfo(draft, msgnum);
6210         if (newmsginfo) {
6211                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
6212                 procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
6213                 procmsg_msginfo_free(newmsginfo);
6214         }
6215         
6216         lock = FALSE;
6217
6218         /* 0: quit editing  1: keep editing  2: keep editing (autosave) */
6219         if (action == 0)
6220                 gtk_widget_destroy(compose->window);
6221         else {
6222                 struct stat s;
6223                 gchar *path;
6224
6225                 path = folder_item_fetch_msg(draft, msgnum);
6226                 g_return_if_fail(path != NULL);
6227                 if (stat(path, &s) < 0) {
6228                         FILE_OP_ERROR(path, "stat");
6229                         g_free(path);
6230                         lock = FALSE;
6231                         return;
6232                 }
6233                 g_free(path);
6234
6235                 procmsg_msginfo_free(compose->targetinfo);
6236                 compose->targetinfo = procmsg_msginfo_new();
6237                 compose->targetinfo->msgnum = msgnum;
6238                 compose->targetinfo->size = s.st_size;
6239                 compose->targetinfo->mtime = s.st_mtime;
6240                 compose->targetinfo->folder = draft;
6241                 compose->mode = COMPOSE_REEDIT;
6242                 
6243                 if (action == 2) {
6244                         compose->autosaved_draft = compose->targetinfo;
6245                 }
6246         }
6247 }
6248
6249 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
6250 {
6251         Compose *compose = (Compose *)data;
6252         GList *file_list;
6253
6254         if (compose->redirect_filename != NULL)
6255                 return;
6256
6257         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6258
6259         if (file_list) {
6260                 GList *tmp;
6261
6262                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6263                         gchar *file = (gchar *) tmp->data;
6264                         compose_attach_append(compose, file, file, NULL);
6265                         compose_changed_cb(NULL, compose);
6266                         g_free(file);
6267                 }
6268                 g_list_free(file_list);
6269         }               
6270 }
6271
6272 static void compose_insert_file_cb(gpointer data, guint action,
6273                                    GtkWidget *widget)
6274 {
6275         Compose *compose = (Compose *)data;
6276         GList *file_list;
6277
6278         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6279
6280         if (file_list) {
6281                 GList *tmp;
6282
6283                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6284                         gchar *file = (gchar *) tmp->data;
6285                         compose_insert_file(compose, file);
6286                         g_free(file);
6287                 }
6288                 g_list_free(file_list);
6289         }
6290 }
6291
6292 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
6293                               gpointer data)
6294 {
6295         Compose *compose = (Compose *)data;
6296         if (compose->sending)
6297                 return TRUE;
6298         compose_close_cb(compose, 0, NULL);
6299         return TRUE;
6300 }
6301
6302 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
6303 {
6304         Compose *compose = (Compose *)data;
6305         AlertValue val;
6306         
6307         if (compose->exteditor_tag != -1) {
6308                 if (!compose_ext_editor_kill(compose))
6309                         return;
6310         }
6311
6312         if (compose->modified) {
6313                 val = alertpanel(_("Discard message"),
6314                                  _("This message has been modified. discard it?"),
6315                                  _("Discard"), _("to Draft"), _("Cancel"));
6316
6317                 switch (val) {
6318                 case G_ALERTDEFAULT:
6319                         if (prefs_common.autosave)
6320                                 compose_remove_draft(compose);                  
6321                         break;
6322                 case G_ALERTALTERNATE:
6323                         compose_draft_cb(data, 0, NULL);
6324                         return;
6325                 default:
6326                         return;
6327                 }
6328         }
6329
6330         gtk_widget_destroy(compose->window);
6331 }
6332
6333 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
6334 {
6335         Compose *compose = (Compose *)data;
6336
6337         addressbook_open(compose);
6338 }
6339
6340 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
6341 {
6342         Compose *compose = (Compose *)data;
6343         Template *tmpl;
6344         gchar *msg;
6345         AlertValue val;
6346
6347         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
6348         g_return_if_fail(tmpl != NULL);
6349
6350         msg = g_strdup_printf(_("Do you want to apply the template `%s' ?"),
6351                               tmpl->name);
6352         val = alertpanel(_("Apply template"), msg,
6353                          _("Replace"), _("Insert"), _("Cancel"));
6354         g_free(msg);
6355
6356         if (val == G_ALERTDEFAULT)
6357                 compose_template_apply(compose, tmpl, TRUE);
6358         else if (val == G_ALERTALTERNATE)
6359                 compose_template_apply(compose, tmpl, FALSE);
6360 }
6361
6362 static void compose_ext_editor_cb(gpointer data, guint action,
6363                                   GtkWidget *widget)
6364 {
6365         Compose *compose = (Compose *)data;
6366
6367         compose_exec_ext_editor(compose);
6368 }
6369
6370 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
6371 {
6372         if (compose->sending)
6373                 return;
6374         compose_destroy(compose);
6375 }
6376
6377 static void compose_undo_cb(Compose *compose)
6378 {
6379         undo_undo(compose->undostruct);
6380 }
6381
6382 static void compose_redo_cb(Compose *compose)
6383 {
6384         undo_redo(compose->undostruct);
6385 }
6386
6387 static void compose_cut_cb(Compose *compose)
6388 {
6389         if (compose->focused_editable &&
6390             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6391                 gtk_editable_cut_clipboard
6392                         (GTK_EDITABLE(compose->focused_editable));
6393 }
6394
6395 static void compose_copy_cb(Compose *compose)
6396 {
6397         if (compose->focused_editable &&
6398             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6399                 gtk_editable_copy_clipboard
6400                         (GTK_EDITABLE(compose->focused_editable));
6401 }
6402
6403 static void compose_paste_cb(Compose *compose)
6404 {
6405         if (compose->focused_editable &&
6406             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6407                 gtk_editable_paste_clipboard
6408                         (GTK_EDITABLE(compose->focused_editable));
6409 }
6410
6411 static void compose_paste_as_quote_cb(Compose *compose)
6412 {
6413         if (compose->focused_editable &&
6414             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
6415                 compose->paste_as_quotation = TRUE;
6416                 gtk_editable_paste_clipboard
6417                         (GTK_EDITABLE(compose->focused_editable));
6418                 compose->paste_as_quotation = FALSE;
6419         }
6420 }
6421
6422 static void compose_allsel_cb(Compose *compose)
6423 {
6424         if (compose->focused_editable &&
6425             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6426                 gtk_editable_select_region
6427                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
6428 }
6429
6430 static void compose_gtk_stext_action_cb(Compose *compose,
6431                                         ComposeCallGtkSTextAction action)
6432 {
6433         GtkSText *text = GTK_STEXT(compose->text);
6434         static struct {
6435                 void (*do_action) (GtkSText *text);
6436         } action_table[] = {
6437                 {gtk_stext_move_beginning_of_line},
6438                 {gtk_stext_move_forward_character},
6439                 {gtk_stext_move_backward_character},
6440                 {gtk_stext_move_forward_word},
6441                 {gtk_stext_move_backward_word},
6442                 {gtk_stext_move_end_of_line},
6443                 {gtk_stext_move_next_line},
6444                 {gtk_stext_move_previous_line},
6445                 {gtk_stext_delete_forward_character},
6446                 {gtk_stext_delete_backward_character},
6447                 {gtk_stext_delete_forward_word},
6448                 {gtk_stext_delete_backward_word},
6449                 {gtk_stext_delete_line},
6450                 {gtk_stext_delete_line}, /* gtk_stext_delete_line_n */
6451                 {gtk_stext_delete_to_line_end}
6452         };
6453
6454         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
6455
6456         if (action >= COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE &&
6457             action <= COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END)
6458                 action_table[action].do_action(text);
6459 }
6460
6461 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
6462 {
6463         if (GTK_IS_EDITABLE(widget))
6464                 compose->focused_editable = widget;
6465 }
6466
6467 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
6468 {
6469         if (compose->modified == FALSE) {
6470                 compose->modified = TRUE;
6471                 compose_set_title(compose);
6472         }
6473 }
6474
6475 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
6476                                     Compose *compose)
6477 {
6478         gtk_stext_set_point(GTK_STEXT(widget),
6479                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6480 }
6481
6482 #if 0
6483 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
6484                                  Compose *compose)
6485 {
6486         gtk_stext_set_point(GTK_STEXT(widget),
6487                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6488 }
6489 #endif
6490
6491 #if 0 /* NEW COMPOSE GUI */
6492 static void compose_toggle_to_cb(gpointer data, guint action,
6493                                  GtkWidget *widget)
6494 {
6495         Compose *compose = (Compose *)data;
6496
6497         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6498                 gtk_widget_show(compose->to_hbox);
6499                 gtk_widget_show(compose->to_entry);
6500                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
6501                 compose->use_to = TRUE;
6502         } else {
6503                 gtk_widget_hide(compose->to_hbox);
6504                 gtk_widget_hide(compose->to_entry);
6505                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
6506                 gtk_widget_queue_resize(compose->table_vbox);
6507                 compose->use_to = FALSE;
6508         }
6509
6510         if (addressbook_get_target_compose() == compose)
6511                 addressbook_set_target_compose(compose);
6512 }
6513
6514 static void compose_toggle_cc_cb(gpointer data, guint action,
6515                                  GtkWidget *widget)
6516 {
6517         Compose *compose = (Compose *)data;
6518
6519         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6520                 gtk_widget_show(compose->cc_hbox);
6521                 gtk_widget_show(compose->cc_entry);
6522                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
6523                 compose->use_cc = TRUE;
6524         } else {
6525                 gtk_widget_hide(compose->cc_hbox);
6526                 gtk_widget_hide(compose->cc_entry);
6527                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
6528                 gtk_widget_queue_resize(compose->table_vbox);
6529                 compose->use_cc = FALSE;
6530         }
6531
6532         if (addressbook_get_target_compose() == compose)
6533                 addressbook_set_target_compose(compose);
6534 }
6535
6536 static void compose_toggle_bcc_cb(gpointer data, guint action,
6537                                   GtkWidget *widget)
6538 {
6539         Compose *compose = (Compose *)data;
6540
6541         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6542                 gtk_widget_show(compose->bcc_hbox);
6543                 gtk_widget_show(compose->bcc_entry);
6544                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
6545                 compose->use_bcc = TRUE;
6546         } else {
6547                 gtk_widget_hide(compose->bcc_hbox);
6548                 gtk_widget_hide(compose->bcc_entry);
6549                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
6550                 gtk_widget_queue_resize(compose->table_vbox);
6551                 compose->use_bcc = FALSE;
6552         }
6553
6554         if (addressbook_get_target_compose() == compose)
6555                 addressbook_set_target_compose(compose);
6556 }
6557
6558 static void compose_toggle_replyto_cb(gpointer data, guint action,
6559                                       GtkWidget *widget)
6560 {
6561         Compose *compose = (Compose *)data;
6562
6563         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6564                 gtk_widget_show(compose->reply_hbox);
6565                 gtk_widget_show(compose->reply_entry);
6566                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
6567                 compose->use_replyto = TRUE;
6568         } else {
6569                 gtk_widget_hide(compose->reply_hbox);
6570                 gtk_widget_hide(compose->reply_entry);
6571                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
6572                 gtk_widget_queue_resize(compose->table_vbox);
6573                 compose->use_replyto = FALSE;
6574         }
6575 }
6576
6577 static void compose_toggle_followupto_cb(gpointer data, guint action,
6578                                          GtkWidget *widget)
6579 {
6580         Compose *compose = (Compose *)data;
6581
6582         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6583                 gtk_widget_show(compose->followup_hbox);
6584                 gtk_widget_show(compose->followup_entry);
6585                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
6586                 compose->use_followupto = TRUE;
6587         } else {
6588                 gtk_widget_hide(compose->followup_hbox);
6589                 gtk_widget_hide(compose->followup_entry);
6590                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
6591                 gtk_widget_queue_resize(compose->table_vbox);
6592                 compose->use_followupto = FALSE;
6593         }
6594 }
6595
6596 static void compose_toggle_attach_cb(gpointer data, guint action,
6597                                      GtkWidget *widget)
6598 {
6599         Compose *compose = (Compose *)data;
6600
6601         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6602                 gtk_widget_ref(compose->edit_vbox);
6603
6604                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6605                                        compose->edit_vbox);
6606                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
6607                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
6608                                    TRUE, TRUE, 0);
6609                 gtk_widget_show(compose->paned);
6610
6611                 gtk_widget_unref(compose->edit_vbox);
6612                 gtk_widget_unref(compose->paned);
6613
6614                 compose->use_attach = TRUE;
6615         } else {
6616                 gtk_widget_ref(compose->paned);
6617                 gtk_widget_ref(compose->edit_vbox);
6618
6619                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6620                                        compose->paned);
6621                 gtkut_container_remove(GTK_CONTAINER(compose->paned),
6622                                        compose->edit_vbox);
6623                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
6624                                    compose->edit_vbox, TRUE, TRUE, 0);
6625
6626                 gtk_widget_unref(compose->edit_vbox);
6627
6628                 compose->use_attach = FALSE;
6629         }
6630 }
6631 #endif
6632
6633 #if USE_GPGME
6634 static void compose_toggle_sign_cb(gpointer data, guint action,
6635                                    GtkWidget *widget)
6636 {
6637         Compose *compose = (Compose *)data;
6638
6639         if (GTK_CHECK_MENU_ITEM(widget)->active)
6640                 compose->use_signing = TRUE;
6641         else
6642                 compose->use_signing = FALSE;
6643
6644         compose_update_gnupg_mode_menu_item(compose);
6645 }
6646
6647 static void compose_toggle_encrypt_cb(gpointer data, guint action,
6648                                       GtkWidget *widget)
6649 {
6650         Compose *compose = (Compose *)data;
6651
6652         if (GTK_CHECK_MENU_ITEM(widget)->active)
6653                 compose->use_encryption = TRUE;
6654         else
6655                 compose->use_encryption = FALSE;
6656                 
6657         compose_update_gnupg_mode_menu_item(compose);
6658 }
6659
6660 static void activate_gnupg_mode (Compose *compose, PrefsAccount *account) 
6661 {
6662         if (account->default_gnupg_mode)
6663                 compose->gnupg_mode = GNUPG_MODE_INLINE;
6664         else
6665                 compose->gnupg_mode = GNUPG_MODE_DETACH;
6666                 
6667         compose_update_gnupg_mode_menu_item(compose);
6668 }
6669 #endif /* USE_GPGME */
6670
6671 static void compose_toggle_ruler_cb(gpointer data, guint action,
6672                                     GtkWidget *widget)
6673 {
6674         Compose *compose = (Compose *)data;
6675
6676         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6677                 gtk_widget_show(compose->ruler_hbox);
6678                 prefs_common.show_ruler = TRUE;
6679         } else {
6680                 gtk_widget_hide(compose->ruler_hbox);
6681                 gtk_widget_queue_resize(compose->edit_vbox);
6682                 prefs_common.show_ruler = FALSE;
6683         }
6684 }
6685
6686 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6687                                              GdkDragContext     *drag_context,
6688                                              gint                x,
6689                                              gint                y,
6690                                              GtkSelectionData   *data,
6691                                              guint               info,
6692                                              guint               time,
6693                                              gpointer            user_data)
6694 {
6695         Compose *compose = (Compose *)user_data;
6696         GList *list, *tmp;
6697
6698         list = uri_list_extract_filenames((const gchar *)data->data);
6699         for (tmp = list; tmp != NULL; tmp = tmp->next)
6700                 compose_attach_append
6701                         (compose, (const gchar *)tmp->data,
6702                          (const gchar *)tmp->data, NULL);
6703         if (list) compose_changed_cb(NULL, compose);
6704         list_free_strings(list);
6705         g_list_free(list);
6706 }
6707
6708 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6709                                              GdkDragContext     *drag_context,
6710                                              gint                x,
6711                                              gint                y,
6712                                              GtkSelectionData   *data,
6713                                              guint               info,
6714                                              guint               time,
6715                                              gpointer            user_data)
6716 {
6717         Compose *compose = (Compose *)user_data;
6718         GList *list, *tmp;
6719
6720         list = uri_list_extract_filenames((const gchar *)data->data);
6721         for (tmp = list; tmp != NULL; tmp = tmp->next)
6722                 compose_insert_file(compose, (const gchar *)tmp->data);
6723         list_free_strings(list);
6724         g_list_free(list);
6725 }
6726
6727 #if 0 /* NEW COMPOSE GUI */
6728 static void to_activated(GtkWidget *widget, Compose *compose)
6729 {
6730         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6731                 gtk_widget_grab_focus(compose->newsgroups_entry);
6732         else
6733                 gtk_widget_grab_focus(compose->subject_entry);
6734 }
6735
6736 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6737 {
6738         gtk_widget_grab_focus(compose->subject_entry);
6739 }
6740
6741 static void subject_activated(GtkWidget *widget, Compose *compose)
6742 {
6743         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6744                 gtk_widget_grab_focus(compose->cc_entry);
6745         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6746                 gtk_widget_grab_focus(compose->bcc_entry);
6747         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6748                 gtk_widget_grab_focus(compose->reply_entry);
6749         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6750                 gtk_widget_grab_focus(compose->followup_entry);
6751         else
6752                 gtk_widget_grab_focus(compose->text);
6753 }
6754
6755 static void cc_activated(GtkWidget *widget, Compose *compose)
6756 {
6757         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6758                 gtk_widget_grab_focus(compose->bcc_entry);
6759         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6760                 gtk_widget_grab_focus(compose->reply_entry);
6761         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6762                 gtk_widget_grab_focus(compose->followup_entry);
6763         else
6764                 gtk_widget_grab_focus(compose->text);
6765 }
6766
6767 static void bcc_activated(GtkWidget *widget, Compose *compose)
6768 {
6769         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6770                 gtk_widget_grab_focus(compose->reply_entry);
6771         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6772                 gtk_widget_grab_focus(compose->followup_entry);
6773         else
6774                 gtk_widget_grab_focus(compose->text);
6775 }
6776
6777 static void replyto_activated(GtkWidget *widget, Compose *compose)
6778 {
6779         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6780                 gtk_widget_grab_focus(compose->followup_entry);
6781         else
6782                 gtk_widget_grab_focus(compose->text);
6783 }
6784
6785 static void followupto_activated(GtkWidget *widget, Compose *compose)
6786 {
6787         gtk_widget_grab_focus(compose->text);
6788 }
6789 #endif
6790
6791 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6792                                              GtkWidget *widget)
6793 {
6794         Compose *compose = (Compose *)data;
6795
6796         if (GTK_CHECK_MENU_ITEM(widget)->active)
6797                 compose->return_receipt = TRUE;
6798         else
6799                 compose->return_receipt = FALSE;
6800 }
6801
6802 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6803                                             GdkEventKey *event,
6804                                             ComposeHeaderEntry *headerentry)
6805 {
6806         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6807             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6808             !(event->state & GDK_MODIFIER_MASK) &&
6809             (event->keyval == GDK_BackSpace) &&
6810             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6811                 gtk_container_remove
6812                         (GTK_CONTAINER(headerentry->compose->header_table),
6813                          headerentry->combo);
6814                 gtk_container_remove
6815                         (GTK_CONTAINER(headerentry->compose->header_table),
6816                          headerentry->entry);
6817                 headerentry->compose->header_list =
6818                         g_slist_remove(headerentry->compose->header_list,
6819                                        headerentry);
6820                 g_free(headerentry);
6821         } else  if (event->keyval == GDK_Tab) {
6822                 if (headerentry->compose->header_last == headerentry) {
6823                         /* Override default next focus, and give it to subject_entry
6824                          * instead of notebook tabs
6825                          */
6826                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6827                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6828                 }
6829         }
6830
6831 }
6832
6833 void compose_headerentry_changed_cb(GtkWidget *entry,
6834                                     ComposeHeaderEntry *headerentry)
6835 {
6836         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6837                 headerentry->compose->header_list =
6838                         g_slist_append(headerentry->compose->header_list,
6839                                        headerentry);
6840                 compose_create_header_entry(headerentry->compose);
6841                 gtk_signal_disconnect_by_func
6842                         (GTK_OBJECT(entry),
6843                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6844                          headerentry);
6845                 /* Automatically scroll down */
6846                 compose_show_first_last_header(headerentry->compose, FALSE);
6847                 
6848         }
6849 }
6850
6851 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6852 {
6853         GtkAdjustment *vadj;
6854
6855         g_return_if_fail(compose);
6856         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6857         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6858
6859         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6860         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6861 }
6862
6863 static void text_activated(GtkWidget *widget, Compose *compose)
6864 {
6865         compose_send_control_enter(compose);
6866 }
6867
6868 static void text_inserted(GtkWidget *widget, const gchar *text,
6869                           gint length, gint *position, Compose *compose)
6870 {
6871         GtkEditable *editable = GTK_EDITABLE(widget);
6872
6873         gtk_signal_handler_block_by_func(GTK_OBJECT(widget),
6874                                          GTK_SIGNAL_FUNC(text_inserted),
6875                                          compose);
6876         if (compose->paste_as_quotation) {
6877                 gchar *new_text;
6878                 gchar *qmark;
6879                 gint pos;
6880
6881                 new_text = g_strndup(text, length);
6882                 if (prefs_common.quotemark && *prefs_common.quotemark)
6883                         qmark = prefs_common.quotemark;
6884                 else
6885                         qmark = "> ";
6886                 gtk_stext_set_point(GTK_STEXT(widget), *position);
6887                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text);
6888                 pos = gtk_stext_get_point(GTK_STEXT(widget));
6889                 gtk_editable_set_position(editable, pos);
6890                 *position = pos;
6891                 g_free(new_text);
6892         } else
6893                 gtk_editable_insert_text(editable, text, length, position);
6894
6895         if (prefs_common.autowrap)
6896                 compose_wrap_line_all_full(compose, TRUE);
6897
6898         gtk_signal_handler_unblock_by_func(GTK_OBJECT(widget),
6899                                            GTK_SIGNAL_FUNC(text_inserted),
6900                                            compose);
6901         gtk_signal_emit_stop_by_name(GTK_OBJECT(editable), "insert_text");
6902
6903         
6904         if (prefs_common.autosave && 
6905             gtk_stext_get_length(GTK_STEXT(widget)) % prefs_common.autosave_length == 0)
6906                 compose_draft_cb((gpointer)compose, 2, NULL);
6907 }
6908
6909 static gboolean compose_send_control_enter(Compose *compose)
6910 {
6911         GdkEvent *ev;
6912         GdkEventKey *kev;
6913         GtkItemFactory *ifactory;
6914         GtkAccelEntry *accel;
6915         GtkWidget *send_menu;
6916         GSList *list;
6917         GdkModifierType ignored_mods =
6918                 (GDK_LOCK_MASK | GDK_MOD2_MASK | GDK_MOD3_MASK |
6919                  GDK_MOD4_MASK | GDK_MOD5_MASK);
6920
6921         ev = gtk_get_current_event();
6922         if (ev->type != GDK_KEY_PRESS) return FALSE;
6923
6924         kev = (GdkEventKey *)ev;
6925         if (!(kev->keyval == GDK_Return && (kev->state & GDK_CONTROL_MASK)))
6926                 return FALSE;
6927
6928         ifactory = gtk_item_factory_from_widget(compose->menubar);
6929         send_menu = gtk_item_factory_get_widget(ifactory, "/Message/Send");
6930         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_menu));
6931         if (!list)
6932                 return FALSE;
6933
6934         accel = (GtkAccelEntry *)list->data;
6935         if (accel && accel->accelerator_key == kev->keyval &&
6936             (accel->accelerator_mods & ~ignored_mods) ==
6937             (kev->state & ~ignored_mods)) {
6938                 compose_send_cb(compose, 0, NULL);
6939                 return TRUE;
6940         }
6941
6942         return FALSE;
6943 }
6944
6945 #if USE_ASPELL
6946 static void compose_check_all(Compose *compose)
6947 {
6948         if (compose->gtkaspell)
6949                 gtkaspell_check_all(compose->gtkaspell);
6950 }
6951
6952 static void compose_highlight_all(Compose *compose)
6953 {
6954         if (compose->gtkaspell)
6955                 gtkaspell_highlight_all(compose->gtkaspell);
6956 }
6957
6958 static void compose_check_backwards(Compose *compose)
6959 {
6960         if (compose->gtkaspell) 
6961                 gtkaspell_check_backwards(compose->gtkaspell);
6962         else {
6963                 GtkItemFactory *ifactory;
6964                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6965                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6966                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6967         }
6968 }
6969
6970 static void compose_check_forwards_go(Compose *compose)
6971 {
6972         if (compose->gtkaspell) 
6973                 gtkaspell_check_forwards_go(compose->gtkaspell);
6974         else {
6975                 GtkItemFactory *ifactory;
6976                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6977                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6978                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6979         }
6980 }
6981 #endif
6982