revert commit 0.8.10claws92
[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 INDENT_CHARS    ">|#"
2144 #define SPACE_CHARS     " \t"
2145
2146 static void compose_wrap_line(Compose *compose)
2147 {
2148         GtkSText *text = GTK_STEXT(compose->text);
2149         gint ch_len, last_ch_len;
2150         gchar cbuf[MB_LEN_MAX], last_ch;
2151         guint text_len;
2152         guint line_end;
2153         guint quoted;
2154         gint p_start, p_end;
2155         gint line_pos, cur_pos;
2156         gint line_len, cur_len;
2157
2158         gtk_stext_freeze(text);
2159
2160         text_len = gtk_stext_get_length(text);
2161
2162         /* check to see if the point is on the paragraph mark (empty line). */
2163         cur_pos = gtk_stext_get_point(text);
2164         GET_CHAR(cur_pos, cbuf, ch_len);
2165         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2166                 if (cur_pos == 0)
2167                         goto compose_end; /* on the paragraph mark */
2168                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
2169                 if (ch_len == 1 && *cbuf == '\n')
2170                         goto compose_end; /* on the paragraph mark */
2171         }
2172
2173         /* find paragraph start. */
2174         line_end = quoted = 0;
2175         for (p_start = cur_pos; p_start >= 0; --p_start) {
2176                 GET_CHAR(p_start, cbuf, ch_len);
2177                 if (ch_len == 1 && *cbuf == '\n') {
2178                         if (quoted)
2179                                 goto compose_end; /* quoted part */
2180                         if (line_end) {
2181                                 p_start += 2;
2182                                 break;
2183                         }
2184                         line_end = 1;
2185                 } else {
2186                         if (ch_len == 1 
2187                             && strchr(prefs_common.quote_chars, *cbuf))
2188                                 quoted = 1;
2189                         else if (ch_len != 1 || !isspace(*cbuf))
2190                                 quoted = 0;
2191
2192                         line_end = 0;
2193                 }
2194         }
2195         if (p_start < 0)
2196                 p_start = 0;
2197
2198         /* find paragraph end. */
2199         line_end = 0;
2200         for (p_end = cur_pos; p_end < text_len; p_end++) {
2201                 GET_CHAR(p_end, cbuf, ch_len);
2202                 if (ch_len == 1 && *cbuf == '\n') {
2203                         if (line_end) {
2204                                 p_end -= 1;
2205                                 break;
2206                         }
2207                         line_end = 1;
2208                 } else {
2209                         if (line_end && ch_len == 1 &&
2210                             strchr(prefs_common.quote_chars, *cbuf))
2211                                 goto compose_end; /* quoted part */
2212
2213                         line_end = 0;
2214                 }
2215         }
2216         if (p_end >= text_len)
2217                 p_end = text_len;
2218
2219         if (p_start >= p_end)
2220                 goto compose_end;
2221
2222         line_len = cur_len = 0;
2223         last_ch_len = 0;
2224         last_ch = '\0';
2225         line_pos = p_start;
2226         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2227                 guint space = 0;
2228
2229                 GET_CHAR(cur_pos, cbuf, ch_len);
2230
2231                 if (ch_len < 0) {
2232                         cbuf[0] = '\0';
2233                         ch_len = 1;
2234                 }
2235
2236                 if (ch_len == 1 && isspace(*cbuf))
2237                         space = 1;
2238
2239                 if (ch_len == 1 && *cbuf == '\n') {
2240                         guint replace = 0;
2241                         if (last_ch_len == 1 && !isspace(last_ch)) {
2242                                 if (cur_pos + 1 < p_end) {
2243                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2244                                         if (ch_len == 1 && !isspace(*cbuf))
2245                                                 replace = 1;
2246                                 }
2247                         }
2248                         gtk_stext_set_point(text, cur_pos + 1);
2249                         gtk_stext_backward_delete(text, 1);
2250                         if (replace) {
2251                                 gtk_stext_set_point(text, cur_pos);
2252                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2253                                 space = 1;
2254                         }
2255                         else {
2256                                 p_end--;
2257                                 cur_pos--;
2258                                 continue;
2259                         }
2260                 }
2261
2262                 last_ch_len = ch_len;
2263                 last_ch = *cbuf;
2264
2265                 if (space) {
2266                         line_pos = cur_pos + 1;
2267                         line_len = cur_len + ch_len;
2268                 }
2269
2270                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2271                     line_len > 0) {
2272                         gint tlen = ch_len;
2273
2274                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2275                         if (ch_len == 1 && isspace(*cbuf)) {
2276                                 gtk_stext_set_point(text, line_pos);
2277                                 gtk_stext_backward_delete(text, 1);
2278                                 p_end--;
2279                                 cur_pos--;
2280                                 line_pos--;
2281                                 cur_len--;
2282                                 line_len--;
2283                         }
2284                         ch_len = tlen;
2285
2286                         gtk_stext_set_point(text, line_pos);
2287                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2288                         p_end++;
2289                         cur_pos++;
2290                         line_pos++;
2291                         cur_len = cur_len - line_len + ch_len;
2292                         line_len = 0;
2293                         continue;
2294                 }
2295
2296                 if (ch_len > 1) {
2297                         line_pos = cur_pos + 1;
2298                         line_len = cur_len + ch_len;
2299                 }
2300                 cur_len += ch_len;
2301         }
2302
2303 compose_end:
2304         gtk_stext_thaw(text);
2305 }
2306
2307 #undef WRAP_DEBUG
2308 #ifdef WRAP_DEBUG
2309 /* Darko: used when I debug wrapping */
2310 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2311 {
2312         gint i, clen;
2313         gchar cbuf[MB_LEN_MAX];
2314
2315         printf("%d [", pos);
2316         for (i = pos; i < tlen; i++) {
2317                 GET_CHAR(i, cbuf, clen);
2318                 if (clen < 0) break;
2319                 if (breakoncr && clen == 1 && cbuf[0] == '\n')
2320                         break;
2321                 fwrite(cbuf, clen, 1, stdout);
2322         }
2323         printf("]\n");
2324 }
2325 #endif
2326
2327 typedef enum {
2328         WAIT_FOR_SPACE,
2329         WAIT_FOR_INDENT_CHAR,
2330         WAIT_FOR_INDENT_CHAR_OR_SPACE
2331 } IndentState;
2332
2333 /* return indent length, we allow:
2334    > followed by spaces/tabs
2335    | followed by spaces/tabs
2336    uppercase characters immediately followed by >,
2337    and the repeating sequences of the above */
2338 /* return indent length */
2339 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2340 {
2341         guint i_len = 0;
2342         guint i, ch_len, alnum_cnt = 0;
2343         IndentState state = WAIT_FOR_INDENT_CHAR;
2344         gchar cbuf[MB_LEN_MAX];
2345         gboolean is_space;
2346         gboolean is_indent;
2347
2348         for (i = start_pos; i < text_len; i++) {
2349                 GET_CHAR(i, cbuf, ch_len);
2350                 if (ch_len > 1)
2351                         break;
2352
2353                 if (cbuf[0] == '\n')
2354                         break;
2355
2356                 is_indent = strchr(prefs_common.quote_chars, cbuf[0]) ? TRUE : FALSE;
2357                 is_space = strchr(SPACE_CHARS, cbuf[0]) ? TRUE : FALSE;
2358
2359                 switch (state) {
2360                 case WAIT_FOR_SPACE:
2361                         if (is_space == FALSE)
2362                                 goto out;
2363                         state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2364                         break;
2365                 case WAIT_FOR_INDENT_CHAR_OR_SPACE:
2366                         if (is_indent == FALSE && is_space == FALSE &&
2367                             !isupper(cbuf[0]))
2368                                 goto out;
2369                         if (is_space == TRUE) {
2370                                 alnum_cnt = 0;
2371                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2372                         } else if (is_indent == TRUE) {
2373                                 alnum_cnt = 0;
2374                                 state = WAIT_FOR_SPACE;
2375                         } else {
2376                                 alnum_cnt++;
2377                                 state = WAIT_FOR_INDENT_CHAR;
2378                         }
2379                         break;
2380                 case WAIT_FOR_INDENT_CHAR:
2381                         if (is_indent == FALSE && !isupper(cbuf[0]))
2382                                 goto out;
2383                         if (is_indent == TRUE) {
2384                                 if (alnum_cnt > 0 
2385                                     && !strchr(prefs_common.quote_chars, cbuf[0]))
2386                                         goto out;
2387                                 alnum_cnt = 0;
2388                                 state = WAIT_FOR_SPACE;
2389                         } else {
2390                                 alnum_cnt++;
2391                         }
2392                         break;
2393                 }
2394
2395                 i_len++;
2396         }
2397
2398 out:
2399         if ((i_len > 0) && (state == WAIT_FOR_INDENT_CHAR))
2400                 i_len -= alnum_cnt;
2401
2402         return i_len;
2403 }
2404
2405 /* insert quotation string when line was wrapped */
2406 static guint ins_quote(GtkSText *text, guint indent_len,
2407                        guint prev_line_pos, guint text_len,
2408                        gchar *quote_fmt)
2409 {
2410         guint i, ins_len = 0;
2411         gchar ch;
2412
2413         if (indent_len) {
2414                 for (i = 0; i < indent_len; i++) {
2415                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2416                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2417                 }
2418                 ins_len = indent_len;
2419         }
2420
2421         return ins_len;
2422 }
2423
2424 /* check if we should join the next line */
2425 static gboolean join_next_line(GtkSText *text, guint start_pos, guint tlen,
2426                                guint prev_ilen, gboolean autowrap)
2427 {
2428         guint indent_len, ch_len;
2429         gboolean do_join = FALSE;
2430         gchar cbuf[MB_LEN_MAX];
2431
2432         indent_len = get_indent_length(text, start_pos, tlen);
2433
2434         if ((autowrap || indent_len > 0) && indent_len == prev_ilen) {
2435                 GET_CHAR(start_pos + indent_len, cbuf, ch_len);
2436                 if (ch_len > 0 && (cbuf[0] != '\n'))
2437                         do_join = TRUE;
2438         }
2439
2440         return do_join;
2441 }
2442
2443 static void compose_wrap_line_all(Compose *compose)
2444 {
2445         compose_wrap_line_all_full(compose, FALSE);
2446 }
2447
2448 #define STEXT_FREEZE() \
2449         if (!frozen) { gtk_stext_freeze(text); frozen = TRUE; }
2450
2451 static void compose_wrap_line_all_full(Compose *compose, gboolean autowrap)
2452 {
2453         GtkSText *text = GTK_STEXT(compose->text);
2454         guint tlen;
2455         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2456         gint line_len = 0, cur_len = 0;
2457         gint ch_len;
2458         gboolean is_new_line = TRUE, do_delete = FALSE;
2459         guint i_len = 0;
2460         gboolean linewrap_quote = TRUE;
2461         gboolean set_editable_pos = FALSE;
2462         gint editable_pos = 0;
2463         gboolean frozen = FALSE;
2464         guint linewrap_len = prefs_common.linewrap_len;
2465         gchar *qfmt = prefs_common.quotemark;
2466         gchar cbuf[MB_LEN_MAX];
2467
2468         tlen = gtk_stext_get_length(text);
2469
2470         for (; cur_pos < tlen; cur_pos++) {
2471                 /* mark position of new line - needed for quotation wrap */
2472                 if (is_new_line) {
2473                         if (linewrap_quote)
2474                                 i_len = get_indent_length(text, cur_pos, tlen);
2475
2476                         is_new_line = FALSE;
2477                         p_pos = cur_pos;
2478 #ifdef WRAP_DEBUG
2479                         g_print("new line i_len=%d p_pos=", i_len);
2480                         dump_text(text, p_pos, tlen, 1);
2481 #endif
2482                 }
2483
2484                 GET_CHAR(cur_pos, cbuf, ch_len);
2485
2486                 /* fix line length for tabs */
2487                 if (ch_len == 1 && *cbuf == '\t') {
2488                         guint tab_width = text->default_tab_width;
2489                         guint tab_offset = line_len % tab_width;
2490
2491 #ifdef WRAP_DEBUG
2492                         g_print("found tab at pos=%d line_len=%d ", cur_pos,
2493                                 line_len);
2494 #endif
2495                         if (tab_offset) {
2496                                 line_len += tab_width - tab_offset - 1;
2497                                 cur_len = line_len;
2498                         }
2499 #ifdef WRAP_DEBUG
2500                         printf("new_len=%d\n", line_len);
2501 #endif
2502                 }
2503
2504                 /* we have encountered line break */
2505                 if (ch_len == 1 && *cbuf == '\n') {
2506                         gint clen;
2507                         gchar cb[MB_LEN_MAX];
2508
2509                         /* should we join the next line */
2510                         if ((autowrap || i_len != cur_len) && do_delete &&
2511                             join_next_line
2512                                 (text, cur_pos + 1, tlen, i_len, autowrap))
2513                                 do_delete = TRUE;
2514                         else
2515                                 do_delete = FALSE;
2516
2517 #ifdef WRAP_DEBUG
2518                         g_print("found CR at %d do_del is %d next line is ",
2519                                cur_pos, do_delete);
2520                         dump_text(text, cur_pos + 1, tlen, 1);
2521 #endif
2522
2523                         /* skip delete if it is continuous URL */
2524                         if (do_delete && (line_pos - p_pos <= i_len) &&
2525                             gtk_stext_is_uri_string(text, line_pos, tlen))
2526                                 do_delete = FALSE;
2527
2528 #ifdef WRAP_DEBUG
2529                         g_print("l_len=%d wrap_len=%d do_del=%d\n",
2530                                 line_len, linewrap_len, do_delete);
2531 #endif
2532                         /* should we delete to perform smart wrapping */
2533                         if (line_len < linewrap_len && do_delete) {
2534                                 STEXT_FREEZE();
2535                                 /* get rid of newline */
2536                                 gtk_stext_set_point(text, cur_pos);
2537                                 gtk_stext_forward_delete(text, 1);
2538                                 tlen--;
2539
2540                                 /* if text starts with quote fmt or with
2541                                    indent string, delete them */
2542                                 if (i_len) {
2543                                         guint ilen;
2544                                         ilen =  gtk_stext_str_compare_n
2545                                                 (text, cur_pos, p_pos, i_len,
2546                                                  tlen);
2547                                         if (ilen) {
2548                                                 gtk_stext_forward_delete
2549                                                         (text, ilen);
2550                                                 tlen -= ilen;
2551                                         }
2552                                 }
2553
2554                                 GET_CHAR(cur_pos, cb, clen);
2555
2556                                 /* insert space if it's alphanumeric */
2557                                 if ((cur_pos != line_pos) &&
2558                                     ((clen > 1) || isalnum(cb[0]))) {
2559                                         gtk_stext_insert(text, NULL, NULL,
2560                                                         NULL, " ", 1);
2561                                         tlen++;
2562                                 }
2563
2564                                 /* and start over with current line */
2565                                 cur_pos = p_pos - 1;
2566                                 line_pos = cur_pos;
2567                                 line_len = cur_len = 0;
2568                                 do_delete = FALSE;
2569                                 is_new_line = TRUE;
2570 #ifdef WRAP_DEBUG
2571                                 g_print("after delete l_pos=");
2572                                 dump_text(text, line_pos, tlen, 1);
2573 #endif
2574                                 continue;
2575                         }
2576
2577                         /* mark new line beginning */
2578                         line_pos = cur_pos + 1;
2579                         line_len = cur_len = 0;
2580                         do_delete = FALSE;
2581                         is_new_line = TRUE;
2582                         continue;
2583                 }
2584
2585                 if (ch_len < 0) {
2586                         cbuf[0] = '\0';
2587                         ch_len = 1;
2588                 }
2589
2590                 /* possible line break */
2591                 if (ch_len == 1 && isspace(*cbuf)) {
2592                         line_pos = cur_pos + 1;
2593                         line_len = cur_len + ch_len;
2594                 }
2595
2596                 /* are we over wrapping length set in preferences ? */
2597                 if (cur_len + ch_len > linewrap_len) {
2598                         gint clen;
2599
2600 #ifdef WRAP_DEBUG
2601                         g_print("should wrap cur_pos=%d ", cur_pos);
2602                         dump_text(text, p_pos, tlen, 1);
2603                         dump_text(text, line_pos, tlen, 1);
2604 #endif
2605                         /* force wrapping if it is one long word but not URL */
2606                         if (line_pos - p_pos <= i_len)
2607                                 if (!gtk_stext_is_uri_string
2608                                     (text, line_pos, tlen))
2609                                         line_pos = cur_pos - 1;
2610 #ifdef WRAP_DEBUG
2611                         g_print("new line_pos=%d\n", line_pos);
2612 #endif
2613
2614                         GET_CHAR(line_pos - 1, cbuf, clen);
2615
2616                         /* if next character is space delete it */
2617                         if (clen == 1 && isspace(*cbuf)) {
2618                                 if (p_pos + i_len != line_pos ||
2619                                     !gtk_stext_is_uri_string
2620                                         (text, line_pos, tlen)) {
2621                                         STEXT_FREEZE();
2622                                         /* workaround for correct cursor
2623                                            position */
2624                                         if (set_editable_pos == FALSE) {
2625                                                 editable_pos = gtk_editable_get_position(GTK_EDITABLE(text));
2626                                                 if (editable_pos == line_pos)
2627                                                         set_editable_pos = TRUE;
2628                                         }
2629                                         gtk_stext_set_point(text, line_pos);
2630                                         gtk_stext_backward_delete(text, 1);
2631                                         tlen--;
2632                                         cur_pos--;
2633                                         line_pos--;
2634                                         cur_len--;
2635                                         line_len--;
2636                                 }
2637                         }
2638
2639                         /* if it is URL at beginning of line don't wrap */
2640                         if (p_pos + i_len == line_pos &&
2641                             gtk_stext_is_uri_string(text, line_pos, tlen)) {
2642 #ifdef WRAP_DEBUG
2643                                 g_print("found URL at ");
2644                                 dump_text(text, line_pos, tlen, 1);
2645 #endif
2646                                 continue;
2647                         }
2648
2649                         /* insert CR */
2650                         STEXT_FREEZE();
2651                         gtk_stext_set_point(text, line_pos);
2652                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2653                         /* gtk_stext_compact_buffer(text); */
2654                         tlen++;
2655                         line_pos++;
2656                         /* for loop will increase it */
2657                         cur_pos = line_pos - 1;
2658                         /* start over with current line */
2659                         is_new_line = TRUE;
2660                         line_len = cur_len = 0;
2661                         if (autowrap || i_len > 0)
2662                                 do_delete = TRUE;
2663                         else
2664                                 do_delete = FALSE;
2665 #ifdef WRAP_DEBUG
2666                         g_print("after CR insert ");
2667                         dump_text(text, line_pos, tlen, 1);
2668                         dump_text(text, cur_pos, tlen, 1);
2669 #endif
2670
2671                         /* should we insert quotation ? */
2672                         if (linewrap_quote && i_len) {
2673                                 /* only if line is not already quoted  */
2674                                 if (!gtk_stext_str_compare
2675                                         (text, line_pos, tlen, qfmt)) {
2676                                         guint ins_len;
2677
2678                                         if (line_pos - p_pos > i_len) {
2679                                                 ins_len = ins_quote
2680                                                         (text, i_len, p_pos,
2681                                                          tlen, qfmt);
2682                                                 tlen += ins_len;
2683                                         }
2684 #ifdef WRAP_DEBUG
2685                                         g_print("after quote insert ");
2686                                         dump_text(text, line_pos, tlen, 1);
2687 #endif
2688                                 }
2689                         }
2690                         continue;
2691                 }
2692
2693                 if (ch_len > 1) {
2694                         line_pos = cur_pos + 1;
2695                         line_len = cur_len + ch_len;
2696                 }
2697                 /* advance to next character in buffer */
2698                 cur_len += ch_len;
2699         }
2700
2701         if (frozen)
2702                 gtk_stext_thaw(text);
2703
2704         if (set_editable_pos && editable_pos <= tlen)
2705                 gtk_editable_set_position(GTK_EDITABLE(text), editable_pos);
2706 }
2707
2708 #undef STEXT_FREEZE
2709 #undef GET_CHAR
2710
2711 static void compose_set_title(Compose *compose)
2712 {
2713         gchar *str;
2714         gchar *edited;
2715
2716         edited = compose->modified ? _(" [Edited]") : "";
2717         if (compose->account && compose->account->address)
2718                 str = g_strdup_printf(_("%s - Compose message%s"),
2719                                       compose->account->address, edited);
2720         else
2721                 str = g_strdup_printf(_("Compose message%s"), edited);
2722         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2723         g_free(str);
2724 }
2725
2726 /**
2727  * compose_current_mail_account:
2728  * 
2729  * Find a current mail account (the currently selected account, or the
2730  * default account, if a news account is currently selected).  If a
2731  * mail account cannot be found, display an error message.
2732  * 
2733  * Return value: Mail account, or NULL if not found.
2734  **/
2735 static PrefsAccount *
2736 compose_current_mail_account(void)
2737 {
2738         PrefsAccount *ac;
2739
2740         if (cur_account && cur_account->protocol != A_NNTP)
2741                 ac = cur_account;
2742         else {
2743                 ac = account_get_default();
2744                 if (!ac || ac->protocol == A_NNTP) {
2745                         alertpanel_error(_("Account for sending mail is not specified.\n"
2746                                            "Please select a mail account before sending."));
2747                         return NULL;
2748                 }
2749         }
2750         return ac;
2751 }
2752
2753 static void compose_select_account(Compose *compose, PrefsAccount *account)
2754 {
2755         GtkWidget *menuitem;
2756         GtkItemFactory *ifactory;
2757
2758         g_return_if_fail(account != NULL);
2759
2760         compose->account = account;
2761
2762         compose_set_title(compose);
2763
2764         ifactory = gtk_item_factory_from_widget(compose->menubar);
2765 #if 0
2766         if (account->protocol == A_NNTP) {
2767                 gtk_widget_show(compose->newsgroups_hbox);
2768                 gtk_widget_show(compose->newsgroups_entry);
2769                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 4);
2770                 compose->use_newsgroups = TRUE;
2771
2772                 menuitem = gtk_item_factory_get_item(ifactory, "/View/To");
2773                 gtk_check_menu_item_set_active
2774                         (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
2775                 gtk_widget_set_sensitive(menuitem, TRUE);
2776                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
2777                 gtk_check_menu_item_set_active
2778                         (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
2779                 gtk_widget_set_sensitive(menuitem, TRUE);
2780
2781                 menu_set_sensitive(ifactory, "/View/Followup to", TRUE);
2782         } else {
2783                 gtk_widget_hide(compose->newsgroups_hbox);
2784                 gtk_widget_hide(compose->newsgroups_entry);
2785                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 0);
2786                 gtk_widget_queue_resize(compose->table_vbox);
2787                 compose->use_newsgroups = FALSE;
2788
2789                 menuitem = gtk_item_factory_get_item(ifactory, "/View/To");
2790                 gtk_check_menu_item_set_active
2791                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2792                 gtk_widget_set_sensitive(menuitem, FALSE);
2793                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
2794                 gtk_check_menu_item_set_active
2795                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2796                 gtk_widget_set_sensitive(menuitem, FALSE);
2797
2798                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Followup to");
2799                 gtk_check_menu_item_set_active
2800                         (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
2801                 gtk_widget_set_sensitive(menuitem, FALSE);
2802         }
2803
2804         if (account->set_autocc) {
2805                 compose_entry_show(compose, COMPOSE_ENTRY_CC);
2806                 if (account->auto_cc && compose->mode != COMPOSE_REEDIT)
2807                         compose_entry_set(compose, account->auto_cc,
2808                                           COMPOSE_ENTRY_CC);
2809         }
2810         if (account->set_autobcc) {
2811                 compose_entry_show(compose, COMPOSE_ENTRY_BCC);
2812                 if (account->auto_bcc && compose->mode != COMPOSE_REEDIT)
2813                         compose_entry_set(compose, account->auto_bcc,
2814                                           COMPOSE_ENTRY_BCC);
2815         }
2816         if (account->set_autoreplyto) {
2817                 compose_entry_show(compose, COMPOSE_ENTRY_REPLY_TO);
2818                 if (account->auto_replyto && compose->mode != COMPOSE_REEDIT)
2819                         compose_entry_set(compose, account->auto_replyto,
2820                                           COMPOSE_ENTRY_REPLY_TO);
2821         }
2822
2823         menuitem = gtk_item_factory_get_item(ifactory, "/View/Ruler");
2824         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2825                                        prefs_common.show_ruler);
2826 #endif
2827
2828 #if USE_GPGME
2829         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
2830         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2831                                        account->default_sign);
2832         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
2833         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2834                                        account->default_encrypt);
2835                                        
2836         activate_gnupg_mode(compose, account);          
2837 #endif /* USE_GPGME */
2838 }
2839
2840 gboolean compose_check_for_valid_recipient(Compose *compose) {
2841         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2842         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2843         gboolean recipient_found = FALSE;
2844         GSList *list;
2845         gchar **strptr;
2846
2847         /* free to and newsgroup list */
2848         slist_free_strings(compose->to_list);
2849         g_slist_free(compose->to_list);
2850         compose->to_list = NULL;
2851                         
2852         slist_free_strings(compose->newsgroup_list);
2853         g_slist_free(compose->newsgroup_list);
2854         compose->newsgroup_list = NULL;
2855
2856         /* search header entries for to and newsgroup entries */
2857         for (list = compose->header_list; list; list = list->next) {
2858                 gchar *header;
2859                 gchar *entry;
2860                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
2861                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2862                 g_strstrip(entry);
2863                 if (entry[0] != '\0') {
2864                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2865                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2866                                         compose->to_list = address_list_append(compose->to_list, entry);
2867                                         recipient_found = TRUE;
2868                                 }
2869                         }
2870                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2871                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2872                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2873                                         recipient_found = TRUE;
2874                                 }
2875                         }
2876                 }
2877                 g_free(header);
2878                 g_free(entry);
2879         }
2880         return recipient_found;
2881 }
2882
2883 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
2884 {
2885         gchar *str;
2886
2887         if (compose_check_for_valid_recipient(compose) == FALSE) {
2888                 alertpanel_error(_("Recipient is not specified."));
2889                 return FALSE;
2890         }
2891
2892         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2893         if (*str == '\0' && check_subject == TRUE) {
2894                 AlertValue aval;
2895
2896                 aval = alertpanel(_("Send"),
2897                                   _("Subject is empty. Send it anyway?"),
2898                                   _("Yes"), _("No"), NULL);
2899                 if (aval != G_ALERTDEFAULT)
2900                         return FALSE;
2901         }
2902
2903         return TRUE;
2904 }
2905
2906 gint compose_send(Compose *compose)
2907 {
2908         gint msgnum;
2909         FolderItem *folder;
2910         gint val;
2911         gchar *msgpath;
2912
2913         if (compose_check_entries(compose, TRUE) == FALSE)
2914                 return -1;
2915
2916         val = compose_queue(compose, &msgnum, &folder);
2917         if (val) {
2918                 alertpanel_error(_("Could not queue message for sending"));
2919                 return -1;
2920         }
2921
2922         if (msgnum == 0) {
2923                 alertpanel_error(_("The message was queued but could not be sent.\nUse \"Send queued messages\" from the main window to retry."));
2924                 return 0;
2925         }
2926         
2927         msgpath = folder_item_fetch_msg(folder, msgnum);
2928         val = procmsg_send_message_queue(msgpath);
2929         g_free(msgpath);
2930
2931         folder_item_remove_msg(folder, msgnum);
2932
2933         return val;
2934 }
2935
2936 #if 0 /* compose restructure */
2937 gint compose_send(Compose *compose)
2938 {
2939         gchar tmp[MAXPATHLEN + 1];
2940         gint ok = 0;
2941         static gboolean lock = FALSE;
2942
2943         if (lock) return 1;
2944
2945         g_return_val_if_fail(compose->account != NULL, -1);
2946
2947         lock = TRUE;
2948
2949         if (compose_check_entries(compose, TRUE) == FALSE) {
2950                 lock = FALSE;
2951                 return 1;
2952         }
2953
2954         /* write to temporary file */
2955         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
2956                    get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
2957
2958         if (prefs_common.linewrap_at_send)
2959                 compose_wrap_line_all(compose);
2960
2961         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2962                 lock = FALSE;
2963                 return -1;
2964         }
2965
2966         if (!compose->to_list && !compose->newsgroup_list) {
2967                 g_warning("can't get recipient list.");
2968                 unlink(tmp);
2969                 lock = FALSE;
2970                 return -1;
2971         }
2972
2973         if (compose->to_list) {
2974                 PrefsAccount *ac;
2975
2976 #if 0 /* NEW COMPOSE GUI */
2977                 if (compose->account->protocol != A_NNTP)
2978                         ac = compose->account;
2979                 else {
2980                         ac = account_find_from_address(compose->account->address);
2981                         if (!ac) {
2982                                 if (cur_account && cur_account->protocol != A_NNTP)
2983                                         ac = cur_account;
2984                                 else
2985                                         ac = account_get_default();
2986                         }
2987                         if (!ac || ac->protocol == A_NNTP) {
2988                                 alertpanel_error(_("Account for sending mail is not specified.\n"
2989                                                    "Please select a mail account before sending."));
2990                                 unlink(tmp);
2991                                 lock = FALSE;
2992                                 return -1;
2993                         }
2994                 }
2995 #endif
2996                 ac = compose->account;
2997
2998                 ok = send_message(tmp, ac, compose->to_list);
2999         }
3000
3001         if (ok == 0 && compose->newsgroup_list) {
3002                 ok = news_post(FOLDER(compose->account->folder), tmp);
3003                 if (ok < 0) {
3004                         alertpanel_error(_("Error occurred while posting the message to %s ."),
3005                                          compose->account->nntp_server);
3006                         unlink(tmp);
3007                         lock = FALSE;
3008                         return -1;
3009                 }
3010         }
3011
3012         /* queue message if failed to send */
3013         if (ok < 0) {
3014                 if (prefs_common.queue_msg) {
3015                         AlertValue val;
3016
3017                         val = alertpanel
3018                                 (_("Queueing"),
3019                                  _("Error occurred while sending the message.\n"
3020                                    "Put this message into queue folder?"),
3021                                  _("OK"), _("Cancel"), NULL);
3022                         if (G_ALERTDEFAULT == val) {
3023                                 ok = compose_queue(compose, tmp);
3024                                 if (ok < 0)
3025                                         alertpanel_error(_("Can't queue the message."));
3026                         }
3027                 } else
3028                         alertpanel_error_log(_("Error occurred while sending the message."));
3029         } else {
3030                 if (compose->mode == COMPOSE_REEDIT) {
3031                         compose_remove_reedit_target(compose);
3032                 }
3033                 /* save message to outbox */
3034                 if (prefs_common.savemsg) {
3035                         FolderItem *outbox;
3036
3037                         outbox = account_get_special_folder
3038                                 (compose->account, F_OUTBOX);
3039                         if (procmsg_save_to_outbox(outbox, tmp, FALSE) < 0)
3040                                 alertpanel_error
3041                                         (_("Can't save the message to Sent."));
3042                 }
3043         }
3044
3045         unlink(tmp);
3046         lock = FALSE;
3047         return ok;
3048 }
3049 #endif
3050
3051 static gboolean compose_use_attach(Compose *compose) {
3052     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
3053 }
3054
3055 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3056                                                            FILE *fp)
3057 {
3058         gchar buf[BUFFSIZE];
3059         gchar *str;
3060         gboolean first_address;
3061         GSList *list;
3062         ComposeHeaderEntry *headerentry;
3063         gchar *headerentryname;
3064         gchar *cc_hdr;
3065         gchar *to_hdr;
3066
3067         debug_print("Writing redirect header\n");
3068
3069         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3070         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3071
3072         first_address = TRUE;
3073         for (list = compose->header_list; list; list = list->next) {
3074                 headerentry = ((ComposeHeaderEntry *)list->data);
3075                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3076
3077                 if (g_strcasecmp(headerentryname, cc_hdr) == 0 
3078                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
3079                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3080                         Xstrdup_a(str, str, return -1);
3081                         g_strstrip(str);
3082                         if (str[0] != '\0') {
3083                                 compose_convert_header
3084                                         (buf, sizeof(buf), str,
3085                                         strlen("Resent-To") + 2);
3086                                 if (first_address) {
3087                                         fprintf(fp, "Resent-To: ");
3088                                         first_address = FALSE;
3089                                 } else {
3090                                         fprintf(fp, ",");
3091                                 }
3092                                 fprintf(fp, "%s", buf);
3093                         }
3094                 }
3095         }
3096         /* if (!first_address) { */
3097         fprintf(fp, "\n");
3098         /* } */
3099
3100         return(0);
3101 }
3102
3103 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3104 {
3105         gchar buf[BUFFSIZE];
3106         gchar *str;
3107         /* struct utsname utsbuf; */
3108
3109         g_return_val_if_fail(fp != NULL, -1);
3110         g_return_val_if_fail(compose->account != NULL, -1);
3111         g_return_val_if_fail(compose->account->address != NULL, -1);
3112
3113         /* Resent-Date */
3114         get_rfc822_date(buf, sizeof(buf));
3115         fprintf(fp, "Resent-Date: %s\n", buf);
3116
3117         /* Resent-From */
3118         if (compose->account->name && *compose->account->name) {
3119                 compose_convert_header
3120                         (buf, sizeof(buf), compose->account->name,
3121                          strlen("From: "));
3122                 fprintf(fp, "Resent-From: %s <%s>\n",
3123                         buf, compose->account->address);
3124         } else
3125                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3126
3127         /* Subject */
3128         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3129         if (*str != '\0') {
3130                 Xstrdup_a(str, str, return -1);
3131                 g_strstrip(str);
3132                 if (*str != '\0') {
3133                         compose_convert_header(buf, sizeof(buf), str,
3134                                                strlen("Subject: "));
3135                         fprintf(fp, "Subject: %s\n", buf);
3136                 }
3137         }
3138
3139         /* Resent-Message-ID */
3140         if (compose->account->gen_msgid) {
3141                 compose_generate_msgid(compose, buf, sizeof(buf));
3142                 fprintf(fp, "Resent-Message-Id: <%s>\n", buf);
3143                 compose->msgid = g_strdup(buf);
3144         }
3145
3146         compose_redirect_write_headers_from_headerlist(compose, fp);
3147
3148         /* separator between header and body */
3149         fputs("\n", fp);
3150
3151         return 0;
3152 }
3153
3154 static gint compose_redirect_write_to_file(Compose *compose, const gchar *file)
3155 {
3156         FILE *fp;
3157         FILE *fdest;
3158         size_t len;
3159         gchar buf[BUFFSIZE];
3160
3161         if ((fp = fopen(compose->redirect_filename, "rb")) == NULL) {
3162                 FILE_OP_ERROR(file, "fopen");
3163                 return -1;
3164         }
3165
3166         if ((fdest = fopen(file, "wb")) == NULL) {
3167                 FILE_OP_ERROR(file, "fopen");
3168                 fclose(fp);
3169                 return -1;
3170         }
3171
3172         /* chmod for security */
3173         if (change_file_mode_rw(fdest, file) < 0) {
3174                 FILE_OP_ERROR(file, "chmod");
3175                 g_warning("can't change file mode\n");
3176         }
3177
3178         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
3179                 /* should filter returnpath, delivered-to */
3180                 if (g_strncasecmp(buf, "Return-Path:",
3181                                    strlen("Return-Path:")) == 0 ||
3182                     g_strncasecmp(buf, "Delivered-To:",
3183                                   strlen("Delivered-To:")) == 0 ||
3184                     g_strncasecmp(buf, "Received:",
3185                                   strlen("Received:")) == 0 ||
3186                     g_strncasecmp(buf, "Subject:",
3187                                   strlen("Subject:")) == 0 ||
3188                     g_strncasecmp(buf, "X-UIDL:",
3189                                   strlen("X-UIDL:")) == 0)
3190                         continue;
3191
3192                 if (fputs(buf, fdest) == -1)
3193                         goto error;
3194
3195                 if (!prefs_common.redirect_keep_from) {
3196                         if (g_strncasecmp(buf, "From:",
3197                                           strlen("From:")) == 0) {
3198                                 fputs(" (by way of ", fdest);
3199                                 if (compose->account->name
3200                                     && *compose->account->name) {
3201                                         compose_convert_header
3202                                                 (buf, sizeof(buf),
3203                                                  compose->account->name,
3204                                                  strlen("From: "));
3205                                         fprintf(fdest, "%s <%s>",
3206                                                 buf,
3207                                                 compose->account->address);
3208                                 } else
3209                                         fprintf(fdest, "%s",
3210                                                 compose->account->address);
3211                                 fputs(")", fdest);
3212                         }
3213                 }
3214
3215                 if (fputs("\n", fdest) == -1)
3216                         goto error;
3217         }
3218
3219         compose_redirect_write_headers(compose, fdest);
3220
3221         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3222                 if (fwrite(buf, sizeof(gchar), len, fdest) != len) {
3223                         FILE_OP_ERROR(file, "fwrite");
3224                         goto error;
3225                 }
3226         }
3227
3228         fclose(fp);
3229         if (fclose(fdest) == EOF) {
3230                 FILE_OP_ERROR(file, "fclose");
3231                 unlink(file);
3232                 return -1;
3233         }
3234
3235         return 0;
3236  error:
3237         fclose(fp);
3238         fclose(fdest);
3239         unlink(file);
3240
3241         return -1;
3242 }
3243
3244
3245 #if USE_GPGME
3246 /* interfaces to rfc2015 to keep out the prefs stuff there.
3247  * returns 0 on success and -1 on error. */
3248 static gint compose_create_signers_list(Compose *compose, GSList **pkey_list)
3249 {
3250         const gchar *key_id = NULL;
3251         GSList *key_list;
3252
3253         switch (compose->account->sign_key) {
3254         case SIGN_KEY_DEFAULT:
3255                 *pkey_list = NULL;
3256                 return 0;
3257         case SIGN_KEY_BY_FROM:
3258                 key_id = compose->account->address;
3259                 break;
3260         case SIGN_KEY_CUSTOM:
3261                 key_id = compose->account->sign_key_id;
3262                 break;
3263         default:
3264                 break;
3265         }
3266
3267         key_list = rfc2015_create_signers_list(key_id);
3268
3269         if (!key_list) {
3270                 alertpanel_error(_("Could not find any key associated with "
3271                                    "currently selected key id `%s'."), key_id);
3272                 return -1;
3273         }
3274
3275         *pkey_list = key_list;
3276         return 0;
3277 }
3278
3279 /* clearsign message body text */
3280 static gint compose_clearsign_text(Compose *compose, gchar **text)
3281 {
3282         GSList *key_list;
3283         gchar *tmp_file;
3284
3285         tmp_file = get_tmp_file();
3286         if (str_write_to_file(*text, tmp_file) < 0) {
3287                 g_free(tmp_file);
3288                 return -1;
3289         }
3290
3291         if (compose_create_signers_list(compose, &key_list) < 0 ||
3292             rfc2015_clearsign(tmp_file, key_list) < 0) {
3293                 unlink(tmp_file);
3294                 g_free(tmp_file);
3295                 return -1;
3296         }
3297
3298         g_free(*text);
3299         *text = file_read_to_str(tmp_file);
3300         unlink(tmp_file);
3301         g_free(tmp_file);
3302         if (*text == NULL)
3303                 return -1;
3304
3305         return 0;
3306 }
3307 #endif /* USE_GPGME */
3308
3309 static gint compose_write_to_file(Compose *compose, const gchar *file,
3310                                   gboolean is_draft)
3311 {
3312         FILE *fp;
3313         size_t len;
3314         gchar *chars;
3315         gchar *buf;
3316         gchar *canon_buf;
3317         const gchar *out_codeset;
3318         EncodingType encoding;
3319
3320         if ((fp = fopen(file, "wb")) == NULL) {
3321                 FILE_OP_ERROR(file, "fopen");
3322                 return -1;
3323         }
3324
3325         /* chmod for security */
3326         if (change_file_mode_rw(fp, file) < 0) {
3327                 FILE_OP_ERROR(file, "chmod");
3328                 g_warning("can't change file mode\n");
3329         }
3330
3331         /* get all composed text */
3332         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3333         len = strlen(chars);
3334         if (is_ascii_str(chars)) {
3335                 buf = chars;
3336                 chars = NULL;
3337                 out_codeset = CS_US_ASCII;
3338                 encoding = ENC_7BIT;
3339         } else {
3340                 const gchar *src_codeset;
3341
3342                 out_codeset = conv_get_outgoing_charset_str();
3343                 if (!strcasecmp(out_codeset, CS_US_ASCII))
3344                         out_codeset = CS_ISO_8859_1;
3345
3346                 if (prefs_common.encoding_method == CTE_BASE64)
3347                         encoding = ENC_BASE64;
3348                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
3349                         encoding = ENC_QUOTED_PRINTABLE;
3350                 else if (prefs_common.encoding_method == CTE_8BIT)
3351                         encoding = ENC_8BIT;
3352                 else
3353                         encoding = procmime_get_encoding_for_charset(out_codeset);
3354
3355 #if USE_GPGME
3356                 if (!is_draft &&
3357                     compose->use_signing && !compose->gnupg_mode &&
3358                     encoding == ENC_8BIT)
3359                         encoding = ENC_BASE64;
3360 #endif
3361
3362                 src_codeset = conv_get_current_charset_str();
3363                 /* if current encoding is US-ASCII, set it the same as
3364                    outgoing one to prevent code conversion failure */
3365                 if (!strcasecmp(src_codeset, CS_US_ASCII))
3366                         src_codeset = out_codeset;
3367
3368                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3369                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3370
3371                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3372                 if (!buf) {
3373                         AlertValue aval;
3374                         gchar *msg;
3375
3376                         msg = g_strdup_printf(_("Can't convert the character encoding of the message from\n"
3377                                                 "%s to %s.\n"
3378                                                 "Send it anyway?"), src_codeset, out_codeset);
3379                         aval = alertpanel
3380                                 (_("Error"), msg, _("Yes"), _("+No"), NULL);
3381                         g_free(msg);
3382
3383                         if (aval != G_ALERTDEFAULT) {
3384                                 g_free(chars);
3385                                 fclose(fp);
3386                                 unlink(file);
3387                                 return -1;
3388                         } else {
3389                                 buf = chars;
3390                                 chars = NULL;
3391                         }
3392                 }
3393         }
3394         g_free(chars);
3395
3396         canon_buf = canonicalize_str(buf);
3397         g_free(buf);
3398         buf = canon_buf;
3399
3400 #if USE_GPGME
3401         if (!is_draft && compose->use_signing && compose->gnupg_mode) {
3402                 if (compose_clearsign_text(compose, &buf) < 0) {
3403                         g_warning("clearsign failed\n");
3404                         fclose(fp);
3405                         unlink(file);
3406                         g_free(buf);
3407                         return -1;
3408                 }
3409         }
3410 #endif
3411
3412         /* write headers */
3413         if (compose_write_headers
3414                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
3415                 g_warning("can't write headers\n");
3416                 fclose(fp);
3417                 /* unlink(file); */
3418                 g_free(buf);
3419                 return -1;
3420         }
3421
3422         if (compose_use_attach(compose)) {
3423 #if USE_GPGME
3424             /* This prolog message is ignored by mime software and
3425              * because it would make our signing/encryption task
3426              * tougher, we don't emit it in that case */
3427             if (!compose->use_signing && !compose->use_encryption)
3428 #endif
3429                 fputs("This is a multi-part message in MIME format.\n", fp);
3430
3431                 fprintf(fp, "\n--%s\n", compose->boundary);
3432                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
3433                         out_codeset);
3434                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3435                         procmime_get_encoding_str(encoding));
3436                 fputc('\n', fp);
3437         }
3438
3439         /* write body */
3440         len = strlen(buf);
3441         if (encoding == ENC_BASE64) {
3442                 gchar outbuf[B64_BUFFSIZE];
3443                 gint i, l;
3444
3445                 for (i = 0; i < len; i += B64_LINE_SIZE) {
3446                         l = MIN(B64_LINE_SIZE, len - i);
3447                         base64_encode(outbuf, buf + i, l);
3448                         fputs(outbuf, fp);
3449                         fputc('\n', fp);
3450                 }
3451         } else if (encoding == ENC_QUOTED_PRINTABLE) {
3452                 gchar *outbuf;
3453                 size_t outlen;
3454
3455                 outbuf = g_malloc(len * 4);
3456                 qp_encode_line(outbuf, buf);
3457                 outlen = strlen(outbuf);
3458                 if (fwrite(outbuf, sizeof(gchar), outlen, fp) != outlen) {
3459                         FILE_OP_ERROR(file, "fwrite");
3460                         fclose(fp);
3461                         unlink(file);
3462                         g_free(outbuf);
3463                         g_free(buf);
3464                         return -1;
3465                 }
3466                 g_free(outbuf);
3467         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
3468                 FILE_OP_ERROR(file, "fwrite");
3469                 fclose(fp);
3470                 unlink(file);
3471                 g_free(buf);
3472                 return -1;
3473         }
3474         g_free(buf);
3475
3476         if (compose_use_attach(compose))
3477                 compose_write_attach(compose, fp);
3478
3479         if (fclose(fp) == EOF) {
3480                 FILE_OP_ERROR(file, "fclose");
3481                 unlink(file);
3482                 return -1;
3483         }
3484
3485 #if USE_GPGME
3486         if (is_draft) {
3487                 uncanonicalize_file_replace(file);
3488                 return 0;
3489         }
3490
3491         if ((compose->use_signing && !compose->gnupg_mode) ||
3492             compose->use_encryption) {
3493                 if (canonicalize_file_replace(file) < 0) {
3494                         unlink(file);
3495                         return -1;
3496                 }
3497         }
3498
3499         if (compose->use_signing && !compose->gnupg_mode) {
3500                 GSList *key_list;
3501
3502                 if (compose_create_signers_list(compose, &key_list) < 0 ||
3503                     rfc2015_sign(file, key_list) < 0) {
3504                         unlink(file);
3505                         return -1;
3506                 }
3507         }
3508         if (compose->use_encryption) {
3509                 if (rfc2015_encrypt(file, compose->to_list,
3510                                     compose->gnupg_mode) < 0) {
3511                         unlink(file);
3512                         return -1;
3513                 }
3514         }
3515 #endif /* USE_GPGME */
3516
3517         uncanonicalize_file_replace(file);
3518
3519         return 0;
3520 }
3521
3522 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3523 {
3524         FILE *fp;
3525         size_t len;
3526         gchar *chars;
3527
3528         if ((fp = fopen(file, "wb")) == NULL) {
3529                 FILE_OP_ERROR(file, "fopen");
3530                 return -1;
3531         }
3532
3533         /* chmod for security */
3534         if (change_file_mode_rw(fp, file) < 0) {
3535                 FILE_OP_ERROR(file, "chmod");
3536                 g_warning("can't change file mode\n");
3537         }
3538
3539         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3540
3541         /* write body */
3542         len = strlen(chars);
3543         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3544                 FILE_OP_ERROR(file, "fwrite");
3545                 g_free(chars);
3546                 fclose(fp);
3547                 unlink(file);
3548                 return -1;
3549         }
3550
3551         g_free(chars);
3552
3553         if (fclose(fp) == EOF) {
3554                 FILE_OP_ERROR(file, "fclose");
3555                 unlink(file);
3556                 return -1;
3557         }
3558         return 0;
3559 }
3560
3561 static gint compose_remove_reedit_target(Compose *compose)
3562 {
3563         FolderItem *item;
3564         MsgInfo *msginfo = compose->targetinfo;
3565
3566         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3567         if (!msginfo) return -1;
3568
3569         item = msginfo->folder;
3570         g_return_val_if_fail(item != NULL, -1);
3571
3572         if (procmsg_msg_exist(msginfo) &&
3573             (item->stype == F_DRAFT || item->stype == F_QUEUE 
3574              || msginfo == compose->autosaved_draft)) {
3575                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3576                         g_warning("can't remove the old message\n");
3577                         return -1;
3578                 }
3579         }
3580
3581         return 0;
3582 }
3583
3584 void compose_remove_draft(Compose *compose)
3585 {
3586         FolderItem *drafts;
3587         MsgInfo *msginfo = compose->targetinfo;
3588         drafts = account_get_special_folder(compose->account, F_DRAFT);
3589
3590         if (procmsg_msg_exist(msginfo)) {
3591                 folder_item_remove_msg(drafts, msginfo->msgnum);
3592         }
3593
3594 }
3595
3596 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3597 {
3598         return compose_queue_sub (compose, msgnum, item, FALSE);
3599 }
3600 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
3601 {
3602         FolderItem *queue;
3603         gchar *tmp, *tmp2;
3604         FILE *fp, *src_fp;
3605         GSList *cur;
3606         gchar buf[BUFFSIZE];
3607         gint num;
3608         static gboolean lock = FALSE;
3609         PrefsAccount *mailac = NULL, *newsac = NULL;
3610         
3611         debug_print("queueing message...\n");
3612         g_return_val_if_fail(compose->account != NULL, -1);
3613
3614         lock = TRUE;
3615         
3616         if (compose_check_entries(compose, check_subject) == FALSE) {
3617                 lock = FALSE;
3618                 return -1;
3619         }
3620
3621         if (!compose->to_list && !compose->newsgroup_list) {
3622                 g_warning("can't get recipient list.");
3623                 lock = FALSE;
3624                 return -1;
3625         }
3626
3627         if (compose->to_list) {
3628                 if (compose->account->protocol != A_NNTP)
3629                         mailac = compose->account;
3630                 else if (cur_account && cur_account->protocol != A_NNTP)
3631                         mailac = cur_account;
3632                 else if (!(mailac = compose_current_mail_account())) {
3633                         lock = FALSE;
3634                         alertpanel_error(_("No account for sending mails available!"));
3635                         return -1;
3636                 }
3637         }
3638
3639         if (compose->newsgroup_list) {
3640                 if (compose->account->protocol == A_NNTP)
3641                         newsac = compose->account;
3642                 else if (!newsac->protocol != A_NNTP) {
3643                         lock = FALSE;
3644                         alertpanel_error(_("No account for posting news available!"));
3645                         return -1;
3646                 }                       
3647         }
3648
3649         if (prefs_common.linewrap_at_send)
3650                 compose_wrap_line_all(compose);
3651                         
3652         /* write to temporary file */
3653         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3654                                       G_DIR_SEPARATOR, (gint)compose);
3655
3656         if (compose->redirect_filename != NULL) {
3657                 if (compose_redirect_write_to_file(compose, tmp2) < 0) {
3658                         unlink(tmp2);
3659                         lock = FALSE;
3660                         return -1;
3661                 }
3662         }
3663         else {
3664                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3665                         unlink(tmp2);
3666                         lock = FALSE;
3667                         return -1;
3668                 }
3669         }
3670
3671         /* add queue header */
3672         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3673                               G_DIR_SEPARATOR, (gint)compose);
3674         if ((fp = fopen(tmp, "wb")) == NULL) {
3675                 FILE_OP_ERROR(tmp, "fopen");
3676                 g_free(tmp);
3677                 return -1;
3678         }
3679         if ((src_fp = fopen(tmp2, "rb")) == NULL) {
3680                 FILE_OP_ERROR(tmp2, "fopen");
3681                 fclose(fp);
3682                 unlink(tmp);
3683                 g_free(tmp);
3684                 unlink(tmp2);
3685                 g_free(tmp2);
3686                 return -1;
3687         }
3688         if (change_file_mode_rw(fp, tmp) < 0) {
3689                 FILE_OP_ERROR(tmp, "chmod");
3690                 g_warning("can't change file mode\n");
3691         }
3692
3693         /* queueing variables */
3694         fprintf(fp, "AF:\n");
3695         fprintf(fp, "NF:0\n");
3696         fprintf(fp, "PS:10\n");
3697         fprintf(fp, "SRH:1\n");
3698         fprintf(fp, "SFN:\n");
3699         fprintf(fp, "DSR:\n");
3700         if (compose->msgid)
3701                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3702         else
3703                 fprintf(fp, "MID:\n");
3704         fprintf(fp, "CFG:\n");
3705         fprintf(fp, "PT:0\n");
3706         fprintf(fp, "S:%s\n", compose->account->address);
3707         fprintf(fp, "RQ:\n");
3708         if (mailac)
3709                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3710         else
3711                 fprintf(fp, "SSV:\n");
3712         if (newsac)
3713                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3714         else
3715                 fprintf(fp, "NSV:\n");
3716         fprintf(fp, "SSH:\n");
3717         /* write recepient list */
3718         if (compose->to_list) {
3719                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
3720                 for (cur = compose->to_list->next; cur != NULL;
3721                      cur = cur->next)
3722                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3723                 fprintf(fp, "\n");
3724         }
3725         /* write newsgroup list */
3726         if (compose->newsgroup_list) {
3727                 fprintf(fp, "NG:");
3728                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3729                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3730                         fprintf(fp, ",%s", (gchar *)cur->data);
3731                 fprintf(fp, "\n");
3732         }
3733         /* Sylpheed account IDs */
3734         if (mailac) {
3735                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3736         }
3737         if (newsac) {
3738                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3739         }
3740         /* Save copy folder */
3741         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3742                 gchar *savefolderid;
3743                 
3744                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3745                 fprintf(fp, "SCF:%s\n", savefolderid);
3746                 g_free(savefolderid);
3747         }
3748         /* Message-ID of message replying to */
3749         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
3750                 gchar *folderid;
3751                 
3752                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
3753                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
3754                 g_free(folderid);
3755         }
3756         /* Message-ID of message forwarding to */
3757         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
3758                 gchar *folderid;
3759                 
3760                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
3761                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
3762                 g_free(folderid);
3763         }
3764         fprintf(fp, "\n");
3765
3766         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3767                 if (fputs(buf, fp) == EOF) {
3768                         FILE_OP_ERROR(tmp, "fputs");
3769                         fclose(fp);
3770                         fclose(src_fp);
3771                         unlink(tmp);
3772                         g_free(tmp);
3773                         unlink(tmp2);
3774                         g_free(tmp2);
3775                         return -1;
3776                 }
3777         }
3778         fclose(src_fp);
3779         if (fclose(fp) == EOF) {
3780                 FILE_OP_ERROR(tmp, "fclose");
3781                 unlink(tmp);
3782                 g_free(tmp);
3783                 unlink(tmp2);
3784                 g_free(tmp2);
3785                 return -1;
3786         }
3787
3788         queue = account_get_special_folder(compose->account, F_QUEUE);
3789         if (!queue) {
3790                 g_warning("can't find queue folder\n");
3791                 unlink(tmp);
3792                 g_free(tmp);
3793                 return -1;
3794         }
3795         folder_item_scan(queue);
3796         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3797                 g_warning("can't queue the message\n");
3798                 unlink(tmp);
3799                 g_free(tmp);
3800                 return -1;
3801         }
3802         unlink(tmp);
3803         g_free(tmp);
3804         unlink(tmp2);
3805         g_free(tmp2);
3806
3807         if (compose->mode == COMPOSE_REEDIT) {
3808                 compose_remove_reedit_target(compose);
3809         }
3810
3811         if ((msgnum != NULL) && (item != NULL)) {
3812                 *msgnum = num;
3813                 *item = queue;
3814         }
3815
3816         return 0;
3817 }
3818
3819 static void compose_write_attach(Compose *compose, FILE *fp)
3820 {
3821         AttachInfo *ainfo;
3822         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3823         gint row;
3824         FILE *attach_fp;
3825         gchar filename[BUFFSIZE];
3826         gint len;
3827
3828         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3829              row++) {
3830                 if ((attach_fp = fopen(ainfo->file, "rb")) == NULL) {
3831                         g_warning("Can't open file %s\n", ainfo->file);
3832                         continue;
3833                 }
3834
3835                 fprintf(fp, "\n--%s\n", compose->boundary);
3836
3837                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3838                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3839                         fprintf(fp, "Content-Disposition: inline\n");
3840                 } else {
3841                         compose_convert_header(filename, sizeof(filename),
3842                                                ainfo->name, 12);
3843                         fprintf(fp, "Content-Type: %s;\n"
3844                                     " name=\"%s\"\n",
3845                                 ainfo->content_type, filename);
3846                         fprintf(fp, "Content-Disposition: attachment;\n"
3847                                     " filename=\"%s\"\n", filename);
3848                 }
3849
3850                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3851                         procmime_get_encoding_str(ainfo->encoding));
3852
3853                 if (ainfo->encoding == ENC_BASE64) {
3854                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3855
3856                         while ((len = fread(inbuf, sizeof(gchar),
3857                                             B64_LINE_SIZE, attach_fp))
3858                                == B64_LINE_SIZE) {
3859                                 base64_encode(outbuf, inbuf, B64_LINE_SIZE);
3860                                 fputs(outbuf, fp);
3861                                 fputc('\n', fp);
3862                         }
3863                         if (len > 0 && feof(attach_fp)) {
3864                                 base64_encode(outbuf, inbuf, len);
3865                                 fputs(outbuf, fp);
3866                                 fputc('\n', fp);
3867                         }
3868                 } else if (ainfo->encoding == ENC_QUOTED_PRINTABLE) {
3869                         gchar inbuf[BUFFSIZE], outbuf[BUFFSIZE * 4];
3870
3871                         while (fgets(inbuf, sizeof(inbuf), attach_fp) != NULL) {
3872                                 qp_encode_line(outbuf, inbuf);
3873                                 fputs(outbuf, fp);
3874                         }
3875                 } else {
3876                         gchar buf[BUFFSIZE];
3877
3878                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3879                                 strcrchomp(buf);
3880                                 fputs(buf, fp);
3881                         }
3882                 }
3883
3884                 fclose(attach_fp);
3885         }
3886
3887         fprintf(fp, "\n--%s--\n", compose->boundary);
3888 }
3889
3890 #define QUOTE_IF_REQUIRED(out, str)                     \
3891 {                                                       \
3892         if (*str != '"' && (strchr(str, ',')            \
3893                         || strchr(str, '.'))) {         \
3894                 gchar *__tmp;                           \
3895                 gint len;                               \
3896                                                         \
3897                 len = strlen(str) + 3;                  \
3898                 Xalloca(__tmp, len, return -1);         \
3899                 g_snprintf(__tmp, len, "\"%s\"", str);  \
3900                 out = __tmp;                            \
3901         } else {                                        \
3902                 Xstrdup_a(out, str, return -1);         \
3903         }                                               \
3904 }
3905
3906 #define PUT_RECIPIENT_HEADER(header, str)                                    \
3907 {                                                                            \
3908         if (*str != '\0') {                                                  \
3909                 Xstrdup_a(str, str, return -1);                              \
3910                 g_strstrip(str);                                             \
3911                 if (*str != '\0') {                                          \
3912                         compose->to_list = address_list_append               \
3913                                 (compose->to_list, str);                     \
3914                         compose_convert_header                               \
3915                                 (buf, sizeof(buf), str, strlen(header) + 2); \
3916                         fprintf(fp, "%s: %s\n", header, buf);                \
3917                 }                                                            \
3918         }                                                                    \
3919 }
3920
3921 #define IS_IN_CUSTOM_HEADER(header) \
3922         (compose->account->add_customhdr && \
3923          custom_header_find(compose->account->customhdr_list, header) != NULL)
3924
3925 static gint compose_write_headers_from_headerlist(Compose *compose, 
3926                                                   FILE *fp, 
3927                                                   gchar *header)
3928 {
3929         gchar buf[BUFFSIZE];
3930         gchar *str, *header_w_colon, *trans_hdr;
3931         gboolean first_address;
3932         GSList *list;
3933         ComposeHeaderEntry *headerentry;
3934         gchar * headerentryname;
3935
3936         if (IS_IN_CUSTOM_HEADER(header)) {
3937                 return 0;
3938         }
3939
3940         debug_print("Writing %s-header\n", header);
3941
3942         header_w_colon = g_strconcat(header, ":", NULL);
3943         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3944
3945         first_address = TRUE;
3946         for (list = compose->header_list; list; list = list->next) {
3947                 headerentry = ((ComposeHeaderEntry *)list->data);
3948                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3949
3950                 if (!g_strcasecmp(trans_hdr, headerentryname)) {
3951                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3952                         Xstrdup_a(str, str, return -1);
3953                         g_strstrip(str);
3954                         if (str[0] != '\0') {
3955                                 compose_convert_header
3956                                         (buf, sizeof(buf), str,
3957                                         strlen(header) + 2);
3958                                 if (first_address) {
3959                                         fprintf(fp, "%s: ", header);
3960                                         first_address = FALSE;
3961                                 } else {
3962                                         fprintf(fp, ",");
3963                                 }
3964                                 fprintf(fp, "%s", buf);
3965                         }
3966                 }
3967         }
3968         if (!first_address) {
3969                 fprintf(fp, "\n");
3970         }
3971
3972         g_free(header_w_colon);
3973
3974         return(0);
3975 }
3976
3977 static gint compose_write_headers(Compose *compose, FILE *fp,
3978                                   const gchar *charset, EncodingType encoding,
3979                                   gboolean is_draft)
3980 {
3981         gchar buf[BUFFSIZE];
3982         gchar *str;
3983         gchar *name;
3984         GSList *list;
3985         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3986
3987         /* struct utsname utsbuf; */
3988
3989         g_return_val_if_fail(fp != NULL, -1);
3990         g_return_val_if_fail(charset != NULL, -1);
3991         g_return_val_if_fail(compose->account != NULL, -1);
3992         g_return_val_if_fail(compose->account->address != NULL, -1);
3993
3994         /* Save draft infos */
3995         if (is_draft) {
3996                 fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
3997                 fprintf(fp, "S:%s\n", compose->account->address);
3998                 if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3999                         gchar *savefolderid;
4000
4001                         savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
4002                         fprintf(fp, "SCF:%s\n", savefolderid);
4003                         g_free(savefolderid);
4004                 }
4005                 fprintf(fp, "\n");
4006         }
4007
4008         /* Date */
4009         if (compose->account->add_date) {
4010                 get_rfc822_date(buf, sizeof(buf));
4011                 fprintf(fp, "Date: %s\n", buf);
4012         }
4013
4014         /* From */
4015         if (!IS_IN_CUSTOM_HEADER("From")) {
4016                 if (compose->account->name && *compose->account->name) {
4017                         compose_convert_header
4018                                 (buf, sizeof(buf), compose->account->name,
4019                                  strlen("From: "));
4020                         QUOTE_IF_REQUIRED(name, buf);
4021                         fprintf(fp, "From: %s <%s>\n",
4022                                 name, compose->account->address);
4023                 } else
4024                         fprintf(fp, "From: %s\n", compose->account->address);
4025         }
4026         
4027         /* To */
4028         compose_write_headers_from_headerlist(compose, fp, "To");
4029 #if 0 /* NEW COMPOSE GUI */
4030         if (compose->use_to) {
4031                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
4032                 PUT_RECIPIENT_HEADER("To", str);
4033         }
4034 #endif
4035
4036         /* Newsgroups */
4037         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
4038 #if 0 /* NEW COMPOSE GUI */
4039         if (compose->use_newsgroups) {
4040                 str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
4041                 if (*str != '\0') {
4042                         Xstrdup_a(str, str, return -1);
4043                         g_strstrip(str);
4044                         remove_space(str);
4045                         if (*str != '\0') {
4046                                 compose->newsgroup_list =
4047                                         newsgroup_list_append
4048                                                 (compose->newsgroup_list, str);
4049                                 compose_convert_header(buf, sizeof(buf), str,
4050                                                        strlen("Newsgroups: "));
4051                                 fprintf(fp, "Newsgroups: %s\n", buf);
4052                         }
4053                 }
4054         }
4055 #endif
4056         /* Cc */
4057         compose_write_headers_from_headerlist(compose, fp, "Cc");
4058 #if 0 /* NEW COMPOSE GUI */
4059         if (compose->use_cc) {
4060                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
4061                 PUT_RECIPIENT_HEADER("Cc", str);
4062         }
4063 #endif
4064         /* Bcc */
4065         compose_write_headers_from_headerlist(compose, fp, "Bcc");
4066 #if 0 /* NEW COMPOSE GUI */
4067         if (compose->use_bcc) {
4068                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
4069                 PUT_RECIPIENT_HEADER("Bcc", str);
4070         }
4071 #endif
4072
4073         /* Subject */
4074         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
4075         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4076                 Xstrdup_a(str, str, return -1);
4077                 g_strstrip(str);
4078                 if (*str != '\0') {
4079                         compose_convert_header(buf, sizeof(buf), str,
4080                                                strlen("Subject: "));
4081                         fprintf(fp, "Subject: %s\n", buf);
4082                 }
4083         }
4084
4085         /* Message-ID */
4086         if (compose->account->gen_msgid) {
4087                 compose_generate_msgid(compose, buf, sizeof(buf));
4088                 fprintf(fp, "Message-Id: <%s>\n", buf);
4089                 compose->msgid = g_strdup(buf);
4090         }
4091
4092         /* In-Reply-To */
4093         if (compose->inreplyto && compose->to_list)
4094                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
4095
4096         /* References */
4097         if (compose->references)
4098                 fprintf(fp, "References: %s\n", compose->references);
4099
4100         /* Followup-To */
4101         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
4102 #if 0 /* NEW COMPOSE GUI */
4103         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
4104                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
4105                 if (*str != '\0') {
4106                         Xstrdup_a(str, str, return -1);
4107                         g_strstrip(str);
4108                         remove_space(str);
4109                         if (*str != '\0') {
4110                                 compose_convert_header(buf, sizeof(buf), str,
4111                                                        strlen("Followup-To: "));
4112                                 fprintf(fp, "Followup-To: %s\n", buf);
4113                         }
4114                 }
4115         }
4116 #endif
4117         /* Reply-To */
4118         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
4119 #if 0 /* NEW COMPOSE GUI */
4120         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
4121                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
4122                 if (*str != '\0') {
4123                         Xstrdup_a(str, str, return -1);
4124                         g_strstrip(str);
4125                         if (*str != '\0') {
4126                                 compose_convert_header(buf, sizeof(buf), str,
4127                                                        strlen("Reply-To: "));
4128                                 fprintf(fp, "Reply-To: %s\n", buf);
4129                         }
4130                 }
4131         }
4132 #endif
4133         /* Organization */
4134         if (compose->account->organization &&
4135             !IS_IN_CUSTOM_HEADER("Organization")) {
4136                 compose_convert_header(buf, sizeof(buf),
4137                                        compose->account->organization,
4138                                        strlen("Organization: "));
4139                 fprintf(fp, "Organization: %s\n", buf);
4140         }
4141
4142         /* Program version and system info */
4143         /* uname(&utsbuf); */
4144         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4145             !compose->newsgroup_list) {
4146                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4147                         prog_version,
4148                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4149                         TARGET_ALIAS);
4150                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4151         }
4152         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4153                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4154                         prog_version,
4155                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4156                         TARGET_ALIAS);
4157                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4158         }
4159
4160         /* custom headers */
4161         if (compose->account->add_customhdr) {
4162                 GSList *cur;
4163
4164                 for (cur = compose->account->customhdr_list; cur != NULL;
4165                      cur = cur->next) {
4166                         CustomHeader *chdr = (CustomHeader *)cur->data;
4167
4168                         if (strcasecmp(chdr->name, "Date")         != 0 &&
4169                             strcasecmp(chdr->name, "From")         != 0 &&
4170                             strcasecmp(chdr->name, "To")           != 0 &&
4171                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
4172                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
4173                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
4174                             strcasecmp(chdr->name, "References")   != 0 &&
4175                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
4176                             strcasecmp(chdr->name, "Content-Type") != 0 &&
4177                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
4178                             != 0) {
4179                                 compose_convert_header
4180                                         (buf, sizeof(buf),
4181                                          chdr->value ? chdr->value : "",
4182                                          strlen(chdr->name) + 2);
4183                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
4184                         }
4185                 }
4186         }
4187
4188         /* MIME */
4189         fprintf(fp, "Mime-Version: 1.0\n");
4190         if (compose_use_attach(compose)) {
4191                 get_rfc822_date(buf, sizeof(buf));
4192                 subst_char(buf, ' ', '_');
4193                 subst_char(buf, ',', '_');
4194                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
4195                                                     buf, (guint)compose);
4196                 fprintf(fp,
4197                         "Content-Type: multipart/mixed;\n"
4198                         " boundary=\"%s\"\n", compose->boundary);
4199         } else {
4200                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
4201                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
4202                         procmime_get_encoding_str(encoding));
4203         }
4204
4205         /* PRIORITY */
4206         switch (compose->priority) {
4207                 case PRIORITY_HIGHEST: fprintf(fp, "Importance: high\n"
4208                                                    "X-Priority: 1 (Highest)\n");
4209                         break;
4210                 case PRIORITY_HIGH: fprintf(fp, "Importance: high\n"
4211                                                 "X-Priority: 2 (High)\n");
4212                         break;
4213                 case PRIORITY_NORMAL: break;
4214                 case PRIORITY_LOW: fprintf(fp, "Importance: low\n"
4215                                                "X-Priority: 4 (Low)\n");
4216                         break;
4217                 case PRIORITY_LOWEST: fprintf(fp, "Importance: low\n"
4218                                                   "X-Priority: 5 (Lowest)\n");
4219                         break;
4220                 default: debug_print("compose: priority unknown : %d\n",
4221                                      compose->priority);
4222         }
4223
4224         /* Request Return Receipt */
4225         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4226                 if (compose->return_receipt) {
4227                         if (compose->account->name
4228                             && *compose->account->name) {
4229                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
4230                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4231                         } else
4232                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
4233                 }
4234         }
4235
4236         /* get special headers */
4237         for (list = compose->header_list; list; list = list->next) {
4238                 ComposeHeaderEntry *headerentry;
4239                 gchar *tmp;
4240                 gchar *headername;
4241                 gchar *headername_wcolon;
4242                 gchar *headername_trans;
4243                 gchar *headervalue;
4244                 gchar **string;
4245                 gboolean standard_header = FALSE;
4246
4247                 headerentry = ((ComposeHeaderEntry *)list->data);
4248                 
4249                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4250                 if (!strstr(tmp, ":")) {
4251                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4252                         headername = g_strdup(tmp);
4253                 } else {
4254                         headername_wcolon = g_strdup(tmp);
4255                         headername = g_strdup(strtok(tmp, ":"));
4256                 }
4257                 g_free(tmp);
4258                 
4259                 headervalue = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4260                 string = std_headers;
4261                 while (*string != NULL) {
4262                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4263                         if (!strcmp(headername_trans,headername_wcolon))
4264                                 standard_header = TRUE;
4265                         string++;
4266                 }
4267                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4268                         fprintf(fp, "%s %s\n", headername_wcolon, headervalue);
4269                                 
4270                 g_free(headername);
4271                 g_free(headername_wcolon);
4272                 
4273         }
4274
4275         /* separator between header and body */
4276         fputs("\n", fp);
4277
4278         return 0;
4279 }
4280
4281 #undef IS_IN_CUSTOM_HEADER
4282
4283 static void compose_convert_header(gchar *dest, gint len, gchar *src,
4284                                    gint header_len)
4285 {
4286         g_return_if_fail(src != NULL);
4287         g_return_if_fail(dest != NULL);
4288
4289         if (len < 1) return;
4290
4291         g_strchomp(src);
4292
4293         conv_encode_header(dest, len, src, header_len);
4294 }
4295
4296 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
4297 {
4298         struct tm *lt;
4299         time_t t;
4300         gchar *addr;
4301
4302         t = time(NULL);
4303         lt = localtime(&t);
4304
4305         if (compose->account && compose->account->address &&
4306             *compose->account->address) {
4307                 if (strchr(compose->account->address, '@'))
4308                         addr = g_strdup(compose->account->address);
4309                 else
4310                         addr = g_strconcat(compose->account->address, "@",
4311                                            get_domain_name(), NULL);
4312         } else
4313                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
4314                                    NULL);
4315
4316         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
4317                    lt->tm_year + 1900, lt->tm_mon + 1,
4318                    lt->tm_mday, lt->tm_hour,
4319                    lt->tm_min, lt->tm_sec,
4320                    (guint)random(), addr);
4321
4322         debug_print("generated Message-ID: %s\n", buf);
4323
4324         g_free(addr);
4325 }
4326
4327 static void compose_create_header_entry(Compose *compose) 
4328 {
4329         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4330
4331         GtkWidget *combo;
4332         GtkWidget *entry;
4333         GList *combo_list = NULL;
4334         gchar **string, *header = NULL;
4335         ComposeHeaderEntry *headerentry;
4336         gboolean standard_header = FALSE;
4337
4338         headerentry = g_new0(ComposeHeaderEntry, 1);
4339
4340         /* Combo box */
4341         combo = gtk_combo_new();
4342         string = headers; 
4343         while(*string != NULL) {
4344                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
4345                 string++;
4346         }
4347         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
4348         g_list_free(combo_list);
4349         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
4350         gtk_widget_show(combo);
4351         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
4352         if (compose->header_last) {     
4353                 gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4354                 string = headers;
4355                 while (*string != NULL) {
4356                         if (!strcmp(*string, last_header_entry))
4357                                 standard_header = TRUE;
4358                         string++;
4359                 }
4360                 if (standard_header)
4361                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4362         }
4363         if (!compose->header_last || !standard_header) {
4364                 switch(compose->account->protocol) {
4365                         case A_NNTP:
4366                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
4367                                 break;
4368                         default:
4369                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
4370                                 break;
4371                 }                                                                   
4372         }
4373         if (header)
4374                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
4375
4376         /* Entry field */
4377         entry = gtk_entry_new(); 
4378         gtk_widget_show(entry);
4379         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);
4380
4381         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
4382         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
4383         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4384
4385         address_completion_register_entry(GTK_ENTRY(entry));
4386
4387         headerentry->compose = compose;
4388         headerentry->combo = combo;
4389         headerentry->entry = entry;
4390         headerentry->headernum = compose->header_nextrow;
4391
4392         compose->header_nextrow++;
4393         compose->header_last = headerentry;
4394 }
4395
4396 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
4397 {
4398         ComposeHeaderEntry *last_header;
4399         
4400         last_header = compose->header_last;
4401         
4402         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
4403         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
4404 }
4405
4406 static GtkWidget *compose_create_header(Compose *compose) 
4407 {
4408         GtkWidget *label;
4409         GtkWidget *hbox;
4410         GtkWidget *from_optmenu_hbox;
4411 #if 0 /* NEW COMPOSE GUI */
4412         GtkWidget *to_entry;
4413         GtkWidget *to_hbox;
4414         GtkWidget *newsgroups_entry;
4415         GtkWidget *newsgroups_hbox;
4416 #endif
4417         GtkWidget *header_scrolledwin;
4418         GtkWidget *header_table;
4419 #if 0 /* NEW COMPOSE GUI */
4420         GtkWidget *cc_entry;
4421         GtkWidget *cc_hbox;
4422         GtkWidget *bcc_entry;
4423         GtkWidget *bcc_hbox;
4424         GtkWidget *reply_entry;
4425         GtkWidget *reply_hbox;
4426         GtkWidget *followup_entry;
4427         GtkWidget *followup_hbox;
4428 #endif
4429
4430         gint count = 0;
4431
4432         /* header labels and entries */
4433         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4434         gtk_widget_show(header_scrolledwin);
4435         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
4436
4437         header_table = gtk_table_new(2, 2, FALSE);
4438         gtk_widget_show(header_table);
4439         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
4440         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
4441         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
4442         count = 0;
4443
4444         /* option menu for selecting accounts */
4445         hbox = gtk_hbox_new(FALSE, 0);
4446         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
4447         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
4448         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
4449                          GTK_FILL, 0, 2, 0);
4450         from_optmenu_hbox = compose_account_option_menu_create(compose);
4451         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
4452                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
4453 #if 0 /* NEW COMPOSE GUI */
4454         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4455 #endif
4456         count++;
4457
4458         compose->header_table = header_table;
4459         compose->header_list = NULL;
4460         compose->header_nextrow = count;
4461
4462         compose_create_header_entry(compose);
4463
4464 #if 0 /* NEW COMPOSE GUI */
4465         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
4466                                 "To:", TRUE); 
4467         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4468         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
4469                                 &count, "Newsgroups:", FALSE);
4470         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
4471
4472         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
4473
4474         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
4475                                 "Cc:", TRUE);
4476         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
4477         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
4478                                 "Bcc:", TRUE);
4479         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
4480         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
4481                                 "Reply-To:", TRUE);
4482         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
4483         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
4484                                 "Followup-To:", FALSE);
4485         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
4486
4487         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
4488
4489         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
4490                            GTK_SIGNAL_FUNC(to_activated), compose);
4491         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
4492                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
4493         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
4494                            GTK_SIGNAL_FUNC(subject_activated), compose);
4495         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
4496                            GTK_SIGNAL_FUNC(cc_activated), compose);
4497         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
4498                            GTK_SIGNAL_FUNC(bcc_activated), compose);
4499         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
4500                            GTK_SIGNAL_FUNC(replyto_activated), compose);
4501         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
4502                            GTK_SIGNAL_FUNC(followupto_activated), compose);
4503
4504         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
4505                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4506         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
4507                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4508         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
4509                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4510         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
4511                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4512         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
4513                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4514         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
4515                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4516         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
4517                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4518 #endif
4519
4520         compose->table            = NULL;
4521 #if 0 /* NEW COMPOSE GUI */
4522         compose->table            = table;
4523         compose->to_hbox          = to_hbox;
4524         compose->to_entry         = to_entry;
4525         compose->newsgroups_hbox  = newsgroups_hbox;
4526         compose->newsgroups_entry = newsgroups_entry;
4527 #endif
4528 #if 0 /* NEW COMPOSE GUI */
4529         compose->cc_hbox          = cc_hbox;
4530         compose->cc_entry         = cc_entry;
4531         compose->bcc_hbox         = bcc_hbox;
4532         compose->bcc_entry        = bcc_entry;
4533         compose->reply_hbox       = reply_hbox;
4534         compose->reply_entry      = reply_entry;
4535         compose->followup_hbox    = followup_hbox;
4536         compose->followup_entry   = followup_entry;
4537 #endif
4538
4539         return header_scrolledwin ;
4540 }
4541
4542 GtkWidget *compose_create_attach(Compose *compose)
4543 {
4544         gchar *titles[N_ATTACH_COLS];
4545         gint i;
4546
4547         GtkWidget *attach_scrwin;
4548         GtkWidget *attach_clist;
4549
4550         titles[COL_MIMETYPE] = _("MIME type");
4551         titles[COL_SIZE]     = _("Size");
4552         titles[COL_NAME]     = _("Name");
4553
4554         /* attachment list */
4555         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
4556         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
4557                                        GTK_POLICY_AUTOMATIC,
4558                                        GTK_POLICY_ALWAYS);
4559         gtk_widget_set_usize(attach_scrwin, -1, 80);
4560
4561         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
4562         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
4563                                            GTK_JUSTIFY_RIGHT);
4564         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
4565         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
4566         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
4567                                      GTK_SELECTION_EXTENDED);
4568         for (i = 0; i < N_ATTACH_COLS; i++)
4569                 GTK_WIDGET_UNSET_FLAGS
4570                         (GTK_CLIST(attach_clist)->column[i].button,
4571                          GTK_CAN_FOCUS);
4572         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
4573
4574         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4575                            GTK_SIGNAL_FUNC(attach_selected), compose);
4576         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4577                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4578         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4579                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4580
4581         /* drag and drop */
4582         gtk_drag_dest_set(attach_clist,
4583                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4584                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4585         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4586                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4587                            compose);
4588
4589         compose->attach_scrwin = attach_scrwin;
4590         compose->attach_clist  = attach_clist;
4591
4592         return attach_scrwin;
4593 }
4594
4595 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4596 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4597
4598 static GtkWidget *compose_create_others(Compose *compose)
4599 {
4600         GtkWidget *table;
4601         GtkWidget *savemsg_checkbtn;
4602         GtkWidget *savemsg_entry;
4603         GtkWidget *savemsg_select;
4604         
4605         guint rowcount = 0;
4606         gchar *folderidentifier;
4607
4608         /* Table for settings */
4609         table = gtk_table_new(3, 1, FALSE);
4610         gtk_widget_show(table);
4611         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4612         rowcount = 0;
4613
4614         /* Save Message to folder */
4615         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4616         gtk_widget_show(savemsg_checkbtn);
4617         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4618         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4619                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4620         }
4621         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4622                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4623
4624         savemsg_entry = gtk_entry_new();
4625         gtk_widget_show(savemsg_entry);
4626         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4627         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4628         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4629                 folderidentifier = folder_item_get_identifier(account_get_special_folder
4630                                   (compose->account, F_OUTBOX));
4631                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4632                 g_free(folderidentifier);
4633         }
4634
4635         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4636         gtk_widget_show (savemsg_select);
4637         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4638         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4639                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4640                             compose);
4641
4642         rowcount++;
4643
4644         compose->savemsg_checkbtn = savemsg_checkbtn;
4645         compose->savemsg_entry = savemsg_entry;
4646
4647         return table;   
4648 }
4649
4650 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4651 {
4652         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4653                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4654 }
4655
4656 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4657 {
4658         FolderItem *dest;
4659         gchar * path;
4660
4661         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
4662         if (!dest) return;
4663
4664         path = folder_item_get_identifier(dest);
4665
4666         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4667         g_free(path);
4668 }
4669
4670 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4671 {
4672         Compose   *compose;
4673         GtkWidget *window;
4674         GtkWidget *vbox;
4675         GtkWidget *menubar;
4676         GtkWidget *handlebox;
4677
4678         GtkWidget *notebook;
4679
4680         GtkWidget *vbox2;
4681
4682         GtkWidget *label;
4683         GtkWidget *subject_hbox;
4684         GtkWidget *subject_frame;
4685         GtkWidget *subject_entry;
4686         GtkWidget *subject;
4687         GtkWidget *paned;
4688
4689         GtkWidget *edit_vbox;
4690         GtkWidget *ruler_hbox;
4691         GtkWidget *ruler;
4692         GtkWidget *scrolledwin;
4693         GtkWidget *text;
4694
4695         UndoMain *undostruct;
4696
4697         gchar *titles[N_ATTACH_COLS];
4698         guint n_menu_entries;
4699         GtkStyle  *style, *new_style;
4700         GdkColormap *cmap;
4701         GdkColor color[1];
4702         gboolean success[1];
4703         GtkWidget *popupmenu;
4704         GtkItemFactory *popupfactory;
4705         GtkItemFactory *ifactory;
4706         GtkWidget *tmpl_menu;
4707         gint n_entries;
4708
4709 #if USE_ASPELL
4710         GtkAspell * gtkaspell = NULL;
4711 #endif
4712
4713         static GdkGeometry geometry;
4714
4715         g_return_val_if_fail(account != NULL, NULL);
4716
4717         debug_print("Creating compose window...\n");
4718         compose = g_new0(Compose, 1);
4719
4720         titles[COL_MIMETYPE] = _("MIME type");
4721         titles[COL_SIZE]     = _("Size");
4722         titles[COL_NAME]     = _("Name");
4723
4724         compose->account = account;
4725
4726         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4727         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4728         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4729         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4730
4731         if (!geometry.max_width) {
4732                 geometry.max_width = gdk_screen_width();
4733                 geometry.max_height = gdk_screen_height();
4734         }
4735         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
4736                                       &geometry, GDK_HINT_MAX_SIZE);
4737
4738         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4739                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4740         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4741                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4742         MANAGE_WINDOW_SIGNALS_CONNECT(window);
4743         gtk_widget_realize(window);
4744
4745         gtkut_widget_set_composer_icon(window);
4746
4747         vbox = gtk_vbox_new(FALSE, 0);
4748         gtk_container_add(GTK_CONTAINER(window), vbox);
4749
4750         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4751         menubar = menubar_create(window, compose_entries,
4752                                  n_menu_entries, "<Compose>", compose);
4753         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4754
4755         handlebox = gtk_handle_box_new();
4756         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4757
4758         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
4759                                           (gpointer)compose);
4760
4761         vbox2 = gtk_vbox_new(FALSE, 2);
4762         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4763         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4764         
4765         /* Notebook */
4766         notebook = gtk_notebook_new();
4767         gtk_widget_set_usize(notebook, -1, 130);
4768         gtk_widget_show(notebook);
4769
4770         /* header labels and entries */
4771         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4772         /* attachment list */
4773         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4774         /* Others Tab */
4775         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4776
4777         /* Subject */
4778         subject_hbox = gtk_hbox_new(FALSE, 0);
4779         gtk_widget_show(subject_hbox);
4780
4781         subject_frame = gtk_frame_new(NULL);
4782         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4783         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4784         gtk_widget_show(subject_frame);
4785
4786         subject = gtk_hbox_new(FALSE, 0);
4787         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4788         gtk_widget_show(subject);
4789
4790         label = gtk_label_new(_("Subject:"));
4791         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4792         gtk_widget_show(label);
4793
4794         subject_entry = gtk_entry_new();
4795         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4796         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4797         gtk_widget_show(subject_entry);
4798         compose->subject_entry = subject_entry;
4799         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4800         
4801         edit_vbox = gtk_vbox_new(FALSE, 0);
4802 #if 0 /* NEW COMPOSE GUI */
4803         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
4804 #endif
4805
4806         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4807
4808         /* ruler */
4809         ruler_hbox = gtk_hbox_new(FALSE, 0);
4810         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4811
4812         ruler = gtk_shruler_new();
4813         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4814         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4815                            BORDER_WIDTH + 1);
4816         gtk_widget_set_usize(ruler_hbox, 1, -1);
4817
4818         /* text widget */
4819         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4820         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4821                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4822         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4823         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4824
4825         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4826                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4827                             gtk_scrolled_window_get_vadjustment
4828                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4829         GTK_STEXT(text)->default_tab_width = 8;
4830         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4831
4832         if (prefs_common.block_cursor) {
4833                 GTK_STEXT(text)->cursor_type = GTK_STEXT_CURSOR_BLOCK;
4834         }
4835         
4836         if (prefs_common.smart_wrapping) {      
4837                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
4838                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
4839         }               
4840
4841         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4842
4843         gtk_signal_connect(GTK_OBJECT(text), "changed",
4844                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4845         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4846                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4847         gtk_signal_connect(GTK_OBJECT(text), "activate",
4848                            GTK_SIGNAL_FUNC(text_activated), compose);
4849         gtk_signal_connect(GTK_OBJECT(text), "insert_text",
4850                            GTK_SIGNAL_FUNC(text_inserted), compose);
4851         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4852                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4853                                  edit_vbox);
4854 #if 0
4855         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4856                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4857                                  compose);
4858 #endif
4859         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4860                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4861                                  ruler);
4862
4863         /* drag and drop */
4864         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4865                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4866         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4867                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4868                            compose);
4869         gtk_widget_show_all(vbox);
4870
4871         /* pane between attach clist and text */
4872         paned = gtk_vpaned_new();
4873         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4874         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4875         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4876         gtk_paned_add1(GTK_PANED(paned), notebook);
4877         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4878         gtk_widget_show_all(paned);
4879
4880         style = gtk_widget_get_style(text);
4881
4882         /* workaround for the slow down of GtkSText when using Pixmap theme */
4883         if (style->engine) {
4884                 GtkThemeEngine *engine;
4885
4886                 engine = style->engine;
4887                 style->engine = NULL;
4888                 new_style = gtk_style_copy(style);
4889                 style->engine = engine;
4890         } else
4891                 new_style = gtk_style_copy(style);
4892
4893         if (prefs_common.textfont) {
4894                 GdkFont *font;
4895
4896                 if ((font = gtkut_font_load(prefs_common.textfont)) != NULL) {
4897                         gdk_font_unref(new_style->font);
4898                         new_style->font = font;
4899                 }
4900         }
4901
4902         gtk_widget_set_style(text, new_style);
4903
4904         color[0] = quote_color;
4905         cmap = gdk_window_get_colormap(window->window);
4906         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4907         if (success[0] == FALSE) {
4908                 g_warning("Compose: color allocation failed.\n");
4909                 style = gtk_widget_get_style(text);
4910                 quote_color = style->black;
4911         }
4912
4913         n_entries = sizeof(compose_popup_entries) /
4914                 sizeof(compose_popup_entries[0]);
4915         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4916                                       "<Compose>", &popupfactory,
4917                                       compose);
4918
4919         ifactory = gtk_item_factory_from_widget(menubar);
4920         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4921         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4922
4923         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
4924 #if 0 /* NEW COMPOSE GUI */
4925         gtk_widget_hide(bcc_hbox);
4926         gtk_widget_hide(bcc_entry);
4927         gtk_widget_hide(reply_hbox);
4928         gtk_widget_hide(reply_entry);
4929         gtk_widget_hide(followup_hbox);
4930         gtk_widget_hide(followup_entry);
4931         gtk_widget_hide(ruler_hbox);
4932         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4933         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4934         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4935
4936         if (account->protocol == A_NNTP) {
4937                 gtk_widget_hide(to_hbox);
4938                 gtk_widget_hide(to_entry);
4939                 gtk_widget_hide(cc_hbox);
4940                 gtk_widget_hide(cc_entry);
4941                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
4942                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
4943         } else {
4944                 gtk_widget_hide(newsgroups_hbox);
4945                 gtk_widget_hide(newsgroups_entry);
4946                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
4947         }
4948 #endif
4949
4950         update_compose_actions_menu(ifactory, "/Tools/Actions", compose);
4951
4952
4953         undostruct = undo_init(text);
4954         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
4955                                    menubar);
4956
4957         address_completion_start(window);
4958
4959         compose->window        = window;
4960         compose->vbox          = vbox;
4961         compose->menubar       = menubar;
4962         compose->handlebox     = handlebox;
4963
4964         compose->vbox2         = vbox2;
4965
4966         compose->paned = paned;
4967
4968         compose->edit_vbox     = edit_vbox;
4969         compose->ruler_hbox    = ruler_hbox;
4970         compose->ruler         = ruler;
4971         compose->scrolledwin   = scrolledwin;
4972         compose->text          = text;
4973
4974         compose->focused_editable = NULL;
4975
4976         compose->popupmenu    = popupmenu;
4977         compose->popupfactory = popupfactory;
4978
4979         compose->tmpl_menu = tmpl_menu;
4980
4981         compose->mode = mode;
4982
4983         compose->targetinfo = NULL;
4984         compose->replyinfo  = NULL;
4985         compose->fwdinfo    = NULL;
4986
4987         compose->replyto     = NULL;
4988         compose->cc          = NULL;
4989         compose->bcc         = NULL;
4990         compose->followup_to = NULL;
4991
4992         compose->ml_post     = NULL;
4993
4994         compose->inreplyto   = NULL;
4995         compose->references  = NULL;
4996         compose->msgid       = NULL;
4997         compose->boundary    = NULL;
4998
4999 #if USE_GPGME
5000         compose->use_signing    = FALSE;
5001         compose->use_encryption = FALSE;
5002 #endif /* USE_GPGME */
5003
5004         compose->modified = FALSE;
5005
5006         compose->return_receipt = FALSE;
5007         compose->paste_as_quotation = FALSE;
5008
5009         compose->to_list        = NULL;
5010         compose->newsgroup_list = NULL;
5011
5012         compose->exteditor_file    = NULL;
5013         compose->exteditor_pid     = -1;
5014         compose->exteditor_readdes = -1;
5015         compose->exteditor_tag     = -1;
5016
5017         compose->redirect_filename = NULL;
5018         compose->undostruct = undostruct;
5019 #if USE_ASPELL
5020         menu_set_sensitive(ifactory, "/Spelling", FALSE);
5021         if (mode != COMPOSE_REDIRECT) {
5022                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
5023                     strcmp(prefs_common.dictionary, _("None"))) {
5024                         gtkaspell = gtkaspell_new((const gchar*)prefs_common.dictionary,
5025                                                   conv_get_current_charset_str(),
5026                                                   prefs_common.misspelled_col,
5027                                                   prefs_common.check_while_typing,
5028                                                   prefs_common.use_alternate,
5029                                                   GTK_STEXT(text));
5030                         if (!gtkaspell) {
5031                                 alertpanel_error(_("Spell checker could not be started.\n%s"), gtkaspellcheckers->error_message);
5032                                 gtkaspell_checkers_reset_error();
5033                         } else {
5034
5035                                 GtkWidget *menuitem;
5036
5037                                 if (!gtkaspell_set_sug_mode(gtkaspell, prefs_common.aspell_sugmode)) {
5038                                         debug_print("Aspell: could not set suggestion mode %s\n",
5039                                         gtkaspellcheckers->error_message);
5040                                         gtkaspell_checkers_reset_error();
5041                                 }
5042
5043                                 menuitem = gtk_item_factory_get_item(ifactory, "/Spelling/Spelling Configuration");
5044                                 gtkaspell_populate_submenu(gtkaspell, menuitem);
5045                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
5046                                 }
5047                 }
5048         }
5049 #endif
5050
5051         compose_select_account(compose, account);
5052
5053 #if USE_ASPELL
5054         compose->gtkaspell      = gtkaspell;
5055 #endif
5056
5057         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
5058                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
5059
5060         if (account->set_autobcc) 
5061                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
5062         
5063         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
5064                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
5065
5066
5067         if (account->protocol != A_NNTP)
5068                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
5069         else
5070                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
5071
5072         addressbook_set_target_compose(compose);
5073         update_compose_actions_menu(ifactory, "/Tools/Actions", compose);
5074         
5075         if (mode != COMPOSE_REDIRECT)
5076                 compose_set_template_menu(compose);
5077         else {
5078                 GtkWidget *menuitem;
5079                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5080                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
5081         }
5082
5083         compose_list = g_list_append(compose_list, compose);
5084
5085         if (!prefs_common.show_ruler)
5086                 gtk_widget_hide(ruler_hbox);
5087
5088         /* Priority */
5089         compose->priority = PRIORITY_NORMAL;
5090         compose_update_priority_menu_item(compose);
5091         
5092 #if USE_GPGME
5093         activate_gnupg_mode(compose, account);
5094 #endif  
5095         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
5096         gtk_widget_show(window);
5097         
5098         return compose;
5099 }
5100
5101 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5102 {
5103         GList *accounts;
5104         GtkWidget *hbox;
5105         GtkWidget *optmenu;
5106         GtkWidget *menu;
5107         gint num = 0, def_menu = 0;
5108
5109         accounts = account_get_list();
5110         g_return_val_if_fail(accounts != NULL, NULL);
5111
5112         hbox = gtk_hbox_new(FALSE, 0);
5113         optmenu = gtk_option_menu_new();
5114         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5115         menu = gtk_menu_new();
5116
5117         for (; accounts != NULL; accounts = accounts->next, num++) {
5118                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5119                 GtkWidget *menuitem;
5120                 gchar *name;
5121
5122                 if (ac == compose->account) def_menu = num;
5123
5124                 if (ac->name)
5125                         name = g_strdup_printf("%s: %s <%s>",
5126                                                ac->account_name,
5127                                                ac->name, ac->address);
5128                 else
5129                         name = g_strdup_printf("%s: %s",
5130                                                ac->account_name, ac->address);
5131                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
5132                 g_free(name);
5133                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
5134                                    GTK_SIGNAL_FUNC(account_activated),
5135                                    compose);
5136         }
5137
5138         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5139         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5140
5141         return hbox;
5142 }
5143
5144 static void compose_set_priority_cb(gpointer data,
5145                                     guint action,
5146                                     GtkWidget *widget)
5147 {
5148         Compose *compose = (Compose *) data;
5149         compose->priority = action;
5150 }
5151
5152 static void compose_update_priority_menu_item(Compose * compose)
5153 {
5154         GtkItemFactory *ifactory;
5155         GtkWidget *menuitem = NULL;
5156
5157         ifactory = gtk_item_factory_from_widget(compose->menubar);
5158         
5159         switch (compose->priority) {
5160                 case PRIORITY_HIGHEST:
5161                         menuitem = gtk_item_factory_get_item
5162                                 (ifactory, "/Message/Priority/Highest");
5163                         break;
5164                 case PRIORITY_HIGH:
5165                         menuitem = gtk_item_factory_get_item
5166                                 (ifactory, "/Message/Priority/High");
5167                         break;
5168                 case PRIORITY_NORMAL:
5169                         menuitem = gtk_item_factory_get_item
5170                                 (ifactory, "/Message/Priority/Normal");
5171                         break;
5172                 case PRIORITY_LOW:
5173                         menuitem = gtk_item_factory_get_item
5174                                 (ifactory, "/Message/Priority/Low");
5175                         break;
5176                 case PRIORITY_LOWEST:
5177                         menuitem = gtk_item_factory_get_item
5178                                 (ifactory, "/Message/Priority/Lowest");
5179                         break;
5180         }
5181         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5182 }       
5183
5184 #if USE_GPGME 
5185 static void compose_set_gnupg_mode_cb(gpointer data,
5186                                     guint action,
5187                                     GtkWidget *widget)
5188 {
5189         Compose *compose = (Compose *) data;
5190         compose->gnupg_mode = action;
5191 }
5192
5193 static void compose_update_gnupg_mode_menu_item(Compose * compose)
5194 {
5195         GtkItemFactory *ifactory;
5196         GtkWidget *menuitem = NULL;
5197
5198         ifactory = gtk_item_factory_from_widget(compose->menubar);
5199         
5200         switch (compose->gnupg_mode) {
5201                 case GNUPG_MODE_DETACH:
5202                         menuitem = gtk_item_factory_get_item
5203                                 (ifactory, "/Message/Mode/MIME");
5204                         break;
5205                 case GNUPG_MODE_INLINE:
5206                         menuitem = gtk_item_factory_get_item
5207                                 (ifactory, "/Message/Mode/Inline");
5208                         break;
5209         }
5210         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5211         
5212         if (compose->use_encryption == TRUE || compose->use_signing == TRUE)
5213                 menu_set_sensitive(ifactory, "/Message/Mode", TRUE);
5214         else 
5215                 menu_set_sensitive(ifactory, "/Message/Mode", FALSE);
5216 }       
5217 #endif
5218  
5219 static void compose_set_template_menu(Compose *compose)
5220 {
5221         GSList *tmpl_list, *cur;
5222         GtkWidget *menu;
5223         GtkWidget *item;
5224
5225         tmpl_list = template_get_config();
5226
5227         menu = gtk_menu_new();
5228
5229         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5230                 Template *tmpl = (Template *)cur->data;
5231
5232                 item = gtk_menu_item_new_with_label(tmpl->name);
5233                 gtk_menu_append(GTK_MENU(menu), item);
5234                 gtk_signal_connect(GTK_OBJECT(item), "activate",
5235                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
5236                                    compose);
5237                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
5238                 gtk_widget_show(item);
5239         }
5240
5241         gtk_widget_show(menu);
5242         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5243 }
5244
5245 void compose_reflect_prefs_all(void)
5246 {
5247         GList *cur;
5248         Compose *compose;
5249
5250         for (cur = compose_list; cur != NULL; cur = cur->next) {
5251                 compose = (Compose *)cur->data;
5252                 compose_set_template_menu(compose);
5253         }
5254 }
5255
5256 void compose_reflect_prefs_pixmap_theme(void)
5257 {
5258         GList *cur;
5259         Compose *compose;
5260
5261         for (cur = compose_list; cur != NULL; cur = cur->next) {
5262                 compose = (Compose *)cur->data;
5263                 toolbar_update(TOOLBAR_COMPOSE, compose);
5264         }
5265 }
5266
5267 static void compose_template_apply(Compose *compose, Template *tmpl,
5268                                    gboolean replace)
5269 {
5270         gchar *qmark;
5271         gchar *parsed_str;
5272
5273         if (!tmpl || !tmpl->value) return;
5274
5275         gtk_stext_freeze(GTK_STEXT(compose->text));
5276
5277         if (tmpl->subject && *tmpl->subject != '\0')
5278                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
5279                                    tmpl->subject);
5280         if (tmpl->to && *tmpl->to != '\0')
5281                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
5282         if (tmpl->cc && *tmpl->cc != '\0')
5283                 compose_entry_append(compose, tmpl->cc, COMPOSE_CC);
5284
5285         if (tmpl->bcc && *tmpl->bcc != '\0')
5286                 compose_entry_append(compose, tmpl->bcc, COMPOSE_BCC);
5287
5288         if (replace)
5289                 gtk_stext_clear(GTK_STEXT(compose->text));
5290
5291         if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
5292                 parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
5293                                                NULL, NULL);
5294         } else {
5295                 if (prefs_common.quotemark && *prefs_common.quotemark)
5296                         qmark = prefs_common.quotemark;
5297                 else
5298                         qmark = "> ";
5299
5300                 if (compose->replyinfo != NULL)
5301                         parsed_str = compose_quote_fmt(compose, compose->replyinfo,
5302                                                        tmpl->value, qmark, NULL);
5303                 else if (compose->fwdinfo != NULL)
5304                         parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
5305                                                        tmpl->value, qmark, NULL);
5306                 else
5307                         parsed_str = NULL;
5308         }
5309
5310         if (replace && parsed_str && compose->account->auto_sig)
5311                 compose_insert_sig(compose);
5312
5313         if (replace && parsed_str) {
5314                 gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
5315                 gtk_stext_set_point(GTK_STEXT(compose->text), 0);
5316         }
5317
5318         if (parsed_str)
5319                 compose_changed_cb(NULL, compose);
5320
5321         gtk_stext_thaw(GTK_STEXT(compose->text));
5322 }
5323
5324 static void compose_destroy(Compose *compose)
5325 {
5326         gint row;
5327         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5328         AttachInfo *ainfo;
5329
5330         /* NOTE: address_completion_end() does nothing with the window
5331          * however this may change. */
5332         address_completion_end(compose->window);
5333
5334         slist_free_strings(compose->to_list);
5335         g_slist_free(compose->to_list);
5336         slist_free_strings(compose->newsgroup_list);
5337         g_slist_free(compose->newsgroup_list);
5338         slist_free_strings(compose->header_list);
5339         g_slist_free(compose->header_list);
5340
5341         procmsg_msginfo_free(compose->targetinfo);
5342         procmsg_msginfo_free(compose->replyinfo);
5343         procmsg_msginfo_free(compose->fwdinfo);
5344
5345         g_free(compose->replyto);
5346         g_free(compose->cc);
5347         g_free(compose->bcc);
5348         g_free(compose->newsgroups);
5349         g_free(compose->followup_to);
5350
5351         g_free(compose->ml_post);
5352
5353         g_free(compose->inreplyto);
5354         g_free(compose->references);
5355         g_free(compose->msgid);
5356         g_free(compose->boundary);
5357
5358         if (compose->redirect_filename)
5359                 g_free(compose->redirect_filename);
5360
5361         g_free(compose->exteditor_file);
5362
5363         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
5364              row++)
5365                 compose_attach_info_free(ainfo);
5366
5367         if (addressbook_get_target_compose() == compose)
5368                 addressbook_set_target_compose(NULL);
5369
5370 #if USE_ASPELL
5371         if (compose->gtkaspell) {
5372                 gtkaspell_delete(compose->gtkaspell);
5373         }
5374 #endif
5375
5376         prefs_common.compose_width = compose->scrolledwin->allocation.width;
5377         prefs_common.compose_height = compose->window->allocation.height;
5378
5379         gtk_widget_destroy(compose->paned);
5380
5381         toolbar_destroy(compose->toolbar);
5382         g_free(compose->toolbar);
5383         g_free(compose);
5384
5385         compose_list = g_list_remove(compose_list, compose);
5386 }
5387
5388 static void compose_attach_info_free(AttachInfo *ainfo)
5389 {
5390         g_free(ainfo->file);
5391         g_free(ainfo->content_type);
5392         g_free(ainfo->name);
5393         g_free(ainfo);
5394 }
5395
5396 static void compose_attach_remove_selected(Compose *compose)
5397 {
5398         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5399         AttachInfo *ainfo;
5400         gint row;
5401
5402         while (clist->selection != NULL) {
5403                 row = GPOINTER_TO_INT(clist->selection->data);
5404                 ainfo = gtk_clist_get_row_data(clist, row);
5405                 compose_attach_info_free(ainfo);
5406                 gtk_clist_remove(clist, row);
5407         }
5408 }
5409
5410 static struct _AttachProperty
5411 {
5412         GtkWidget *window;
5413         GtkWidget *mimetype_entry;
5414         GtkWidget *encoding_optmenu;
5415         GtkWidget *path_entry;
5416         GtkWidget *filename_entry;
5417         GtkWidget *ok_btn;
5418         GtkWidget *cancel_btn;
5419 } attach_prop;
5420
5421 static void compose_attach_property(Compose *compose)
5422 {
5423         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5424         AttachInfo *ainfo;
5425         gint row;
5426         GtkOptionMenu *optmenu;
5427         static gboolean cancelled;
5428
5429         if (!clist->selection) return;
5430         row = GPOINTER_TO_INT(clist->selection->data);
5431
5432         ainfo = gtk_clist_get_row_data(clist, row);
5433         if (!ainfo) return;
5434
5435         if (!attach_prop.window)
5436                 compose_attach_property_create(&cancelled);
5437         gtk_widget_grab_focus(attach_prop.ok_btn);
5438         gtk_widget_show(attach_prop.window);
5439         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
5440
5441         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
5442         if (ainfo->encoding == ENC_UNKNOWN)
5443                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5444                                     GINT_TO_POINTER(ENC_BASE64));
5445         else
5446                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5447                                     GINT_TO_POINTER(ainfo->encoding));
5448
5449         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
5450                            ainfo->content_type ? ainfo->content_type : "");
5451         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
5452                            ainfo->file ? ainfo->file : "");
5453         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
5454                            ainfo->name ? ainfo->name : "");
5455
5456         for (;;) {
5457                 gchar *text;
5458                 gchar *cnttype = NULL;
5459                 gchar *file = NULL;
5460                 off_t size = 0;
5461                 GtkWidget *menu;
5462                 GtkWidget *menuitem;
5463
5464                 cancelled = FALSE;
5465                 gtk_main();
5466
5467                 if (cancelled == TRUE) {
5468                         gtk_widget_hide(attach_prop.window);
5469                         break;
5470                 }
5471
5472                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
5473                 if (*text != '\0') {
5474                         gchar *p;
5475
5476                         text = g_strstrip(g_strdup(text));
5477                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
5478                                 cnttype = g_strdup(text);
5479                                 g_free(text);
5480                         } else {
5481                                 alertpanel_error(_("Invalid MIME type."));
5482                                 g_free(text);
5483                                 continue;
5484                         }
5485                 }
5486
5487                 menu = gtk_option_menu_get_menu(optmenu);
5488                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
5489                 ainfo->encoding = GPOINTER_TO_INT
5490                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
5491
5492                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
5493                 if (*text != '\0') {
5494                         if (is_file_exist(text) &&
5495                             (size = get_file_size(text)) > 0)
5496                                 file = g_strdup(text);
5497                         else {
5498                                 alertpanel_error
5499                                         (_("File doesn't exist or is empty."));
5500                                 g_free(cnttype);
5501                                 continue;
5502                         }
5503                 }
5504
5505                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
5506                 if (*text != '\0') {
5507                         g_free(ainfo->name);
5508                         ainfo->name = g_strdup(text);
5509                 }
5510
5511                 if (cnttype) {
5512                         g_free(ainfo->content_type);
5513                         ainfo->content_type = cnttype;
5514                 }
5515                 if (file) {
5516                         g_free(ainfo->file);
5517                         ainfo->file = file;
5518                 }
5519                 if (size)
5520                         ainfo->size = size;
5521
5522                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5523                                    ainfo->content_type);
5524                 gtk_clist_set_text(clist, row, COL_SIZE,
5525                                    to_human_readable(ainfo->size));
5526                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5527
5528                 gtk_widget_hide(attach_prop.window);
5529                 break;
5530         }
5531 }
5532
5533 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5534 { \
5535         label = gtk_label_new(str); \
5536         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5537                          GTK_FILL, 0, 0, 0); \
5538         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5539  \
5540         entry = gtk_entry_new(); \
5541         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5542                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5543 }
5544
5545 static void compose_attach_property_create(gboolean *cancelled)
5546 {
5547         GtkWidget *window;
5548         GtkWidget *vbox;
5549         GtkWidget *table;
5550         GtkWidget *label;
5551         GtkWidget *mimetype_entry;
5552         GtkWidget *hbox;
5553         GtkWidget *optmenu;
5554         GtkWidget *optmenu_menu;
5555         GtkWidget *menuitem;
5556         GtkWidget *path_entry;
5557         GtkWidget *filename_entry;
5558         GtkWidget *hbbox;
5559         GtkWidget *ok_btn;
5560         GtkWidget *cancel_btn;
5561         GList     *mime_type_list, *strlist;
5562
5563         debug_print("Creating attach_property window...\n");
5564
5565         window = gtk_window_new(GTK_WINDOW_DIALOG);
5566         gtk_widget_set_usize(window, 480, -1);
5567         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5568         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
5569         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5570         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5571         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5572                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5573                            cancelled);
5574         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5575                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5576                            cancelled);
5577
5578         vbox = gtk_vbox_new(FALSE, 8);
5579         gtk_container_add(GTK_CONTAINER(window), vbox);
5580
5581         table = gtk_table_new(4, 2, FALSE);
5582         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5583         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5584         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5585
5586         label = gtk_label_new(_("MIME type")); 
5587         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5588                          GTK_FILL, 0, 0, 0); 
5589         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5590         mimetype_entry = gtk_combo_new(); 
5591         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5592                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5593                          
5594         /* stuff with list */
5595         mime_type_list = procmime_get_mime_type_list();
5596         strlist = NULL;
5597         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5598                 MimeType *type = (MimeType *) mime_type_list->data;
5599                 strlist = g_list_append(strlist, 
5600                                 g_strdup_printf("%s/%s",
5601                                         type->type, type->sub_type));
5602         }
5603         
5604         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5605
5606         for (mime_type_list = strlist; mime_type_list != NULL; 
5607                 mime_type_list = mime_type_list->next)
5608                 g_free(mime_type_list->data);
5609         g_list_free(strlist);
5610                          
5611         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5612
5613         label = gtk_label_new(_("Encoding"));
5614         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5615                          GTK_FILL, 0, 0, 0);
5616         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5617
5618         hbox = gtk_hbox_new(FALSE, 0);
5619         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5620                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5621
5622         optmenu = gtk_option_menu_new();
5623         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
5624
5625         optmenu_menu = gtk_menu_new();
5626         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5627         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5628 #if 0
5629         gtk_widget_set_sensitive(menuitem, FALSE);
5630 #endif
5631         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
5632         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5633 #if 0
5634         gtk_widget_set_sensitive(menuitem, FALSE);
5635 #endif
5636         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable",
5637                      ENC_QUOTED_PRINTABLE);
5638         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5639
5640         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5641
5642         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5643
5644         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5645         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5646
5647         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5648                                 &cancel_btn, _("Cancel"), NULL, NULL);
5649         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5650         gtk_widget_grab_default(ok_btn);
5651
5652         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5653                            GTK_SIGNAL_FUNC(attach_property_ok),
5654                            cancelled);
5655         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5656                            GTK_SIGNAL_FUNC(attach_property_cancel),
5657                            cancelled);
5658
5659         gtk_widget_show_all(vbox);
5660
5661         attach_prop.window           = window;
5662         attach_prop.mimetype_entry   = mimetype_entry;
5663         attach_prop.encoding_optmenu = optmenu;
5664         attach_prop.path_entry       = path_entry;
5665         attach_prop.filename_entry   = filename_entry;
5666         attach_prop.ok_btn           = ok_btn;
5667         attach_prop.cancel_btn       = cancel_btn;
5668 }
5669
5670 #undef SET_LABEL_AND_ENTRY
5671
5672 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5673 {
5674         *cancelled = FALSE;
5675         gtk_main_quit();
5676 }
5677
5678 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5679 {
5680         *cancelled = TRUE;
5681         gtk_main_quit();
5682 }
5683
5684 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5685                                          gboolean *cancelled)
5686 {
5687         *cancelled = TRUE;
5688         gtk_main_quit();
5689
5690         return TRUE;
5691 }
5692
5693 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5694                                         gboolean *cancelled)
5695 {
5696         if (event && event->keyval == GDK_Escape) {
5697                 *cancelled = TRUE;
5698                 gtk_main_quit();
5699         }
5700 }
5701
5702 static void compose_exec_ext_editor(Compose *compose)
5703 {
5704         gchar *tmp;
5705         pid_t pid;
5706         gint pipe_fds[2];
5707
5708         tmp = g_strdup_printf("%s%ctmpmsg.%08x", get_tmp_dir(),
5709                               G_DIR_SEPARATOR, (gint)compose);
5710
5711         if (pipe(pipe_fds) < 0) {
5712                 perror("pipe");
5713                 g_free(tmp);
5714                 return;
5715         }
5716
5717         if ((pid = fork()) < 0) {
5718                 perror("fork");
5719                 g_free(tmp);
5720                 return;
5721         }
5722
5723         if (pid != 0) {
5724                 /* close the write side of the pipe */
5725                 close(pipe_fds[1]);
5726
5727                 compose->exteditor_file    = g_strdup(tmp);
5728                 compose->exteditor_pid     = pid;
5729                 compose->exteditor_readdes = pipe_fds[0];
5730
5731                 compose_set_ext_editor_sensitive(compose, FALSE);
5732
5733                 compose->exteditor_tag =
5734                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5735                                       compose_input_cb, compose);
5736         } else {        /* process-monitoring process */
5737                 pid_t pid_ed;
5738
5739                 if (setpgid(0, 0))
5740                         perror("setpgid");
5741
5742                 /* close the read side of the pipe */
5743                 close(pipe_fds[0]);
5744
5745                 if (compose_write_body_to_file(compose, tmp) < 0) {
5746                         fd_write(pipe_fds[1], "2\n", 2);
5747                         _exit(1);
5748                 }
5749
5750                 pid_ed = compose_exec_ext_editor_real(tmp);
5751                 if (pid_ed < 0) {
5752                         fd_write(pipe_fds[1], "1\n", 2);
5753                         _exit(1);
5754                 }
5755
5756                 /* wait until editor is terminated */
5757                 waitpid(pid_ed, NULL, 0);
5758
5759                 fd_write(pipe_fds[1], "0\n", 2);
5760
5761                 close(pipe_fds[1]);
5762                 _exit(0);
5763         }
5764
5765         g_free(tmp);
5766 }
5767
5768 static gint compose_exec_ext_editor_real(const gchar *file)
5769 {
5770         static gchar *def_cmd = "emacs %s";
5771         gchar buf[1024];
5772         gchar *p;
5773         gchar **cmdline;
5774         pid_t pid;
5775
5776         g_return_val_if_fail(file != NULL, -1);
5777
5778         if ((pid = fork()) < 0) {
5779                 perror("fork");
5780                 return -1;
5781         }
5782
5783         if (pid != 0) return pid;
5784
5785         /* grandchild process */
5786
5787         if (setpgid(0, getppid()))
5788                 perror("setpgid");
5789
5790         if (prefs_common.ext_editor_cmd &&
5791             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5792             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5793                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5794         } else {
5795                 if (prefs_common.ext_editor_cmd)
5796                         g_warning("External editor command line is invalid: `%s'\n",
5797                                   prefs_common.ext_editor_cmd);
5798                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5799         }
5800
5801         cmdline = strsplit_with_quote(buf, " ", 1024);
5802         execvp(cmdline[0], cmdline);
5803
5804         perror("execvp");
5805         g_strfreev(cmdline);
5806
5807         _exit(1);
5808 }
5809
5810 static gboolean compose_ext_editor_kill(Compose *compose)
5811 {
5812         pid_t pgid = compose->exteditor_pid * -1;
5813         gint ret;
5814
5815         ret = kill(pgid, 0);
5816
5817         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5818                 AlertValue val;
5819                 gchar *msg;
5820
5821                 msg = g_strdup_printf
5822                         (_("The external editor is still working.\n"
5823                            "Force terminating the process?\n"
5824                            "process group id: %d"), -pgid);
5825                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5826                 g_free(msg);
5827
5828                 if (val == G_ALERTDEFAULT) {
5829                         gdk_input_remove(compose->exteditor_tag);
5830                         close(compose->exteditor_readdes);
5831
5832                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5833                         waitpid(compose->exteditor_pid, NULL, 0);
5834
5835                         g_warning("Terminated process group id: %d", -pgid);
5836                         g_warning("Temporary file: %s",
5837                                   compose->exteditor_file);
5838
5839                         compose_set_ext_editor_sensitive(compose, TRUE);
5840
5841                         g_free(compose->exteditor_file);
5842                         compose->exteditor_file    = NULL;
5843                         compose->exteditor_pid     = -1;
5844                         compose->exteditor_readdes = -1;
5845                         compose->exteditor_tag     = -1;
5846                 } else
5847                         return FALSE;
5848         }
5849
5850         return TRUE;
5851 }
5852
5853 static void compose_input_cb(gpointer data, gint source,
5854                              GdkInputCondition condition)
5855 {
5856         gchar buf[3];
5857         Compose *compose = (Compose *)data;
5858         gint i = 0;
5859
5860         debug_print("Compose: input from monitoring process\n");
5861
5862         gdk_input_remove(compose->exteditor_tag);
5863
5864         for (;;) {
5865                 if (read(source, &buf[i], 1) < 1) {
5866                         buf[0] = '3';
5867                         break;
5868                 }
5869                 if (buf[i] == '\n') {
5870                         buf[i] = '\0';
5871                         break;
5872                 }
5873                 i++;
5874                 if (i == sizeof(buf) - 1)
5875                         break;
5876         }
5877
5878         waitpid(compose->exteditor_pid, NULL, 0);
5879
5880         if (buf[0] == '0') {            /* success */
5881                 GtkSText *text = GTK_STEXT(compose->text);
5882
5883                 gtk_stext_freeze(text);
5884                 gtk_stext_set_point(text, 0);
5885                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5886                 compose_insert_file(compose, compose->exteditor_file);
5887                 compose_changed_cb(NULL, compose);
5888                 gtk_stext_thaw(text);
5889
5890                 if (unlink(compose->exteditor_file) < 0)
5891                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5892         } else if (buf[0] == '1') {     /* failed */
5893                 g_warning("Couldn't exec external editor\n");
5894                 if (unlink(compose->exteditor_file) < 0)
5895                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5896         } else if (buf[0] == '2') {
5897                 g_warning("Couldn't write to file\n");
5898         } else if (buf[0] == '3') {
5899                 g_warning("Pipe read failed\n");
5900         }
5901
5902         close(source);
5903
5904         compose_set_ext_editor_sensitive(compose, TRUE);
5905
5906         g_free(compose->exteditor_file);
5907         compose->exteditor_file    = NULL;
5908         compose->exteditor_pid     = -1;
5909         compose->exteditor_readdes = -1;
5910         compose->exteditor_tag     = -1;
5911 }
5912
5913 static void compose_set_ext_editor_sensitive(Compose *compose,
5914                                              gboolean sensitive)
5915 {
5916         GtkItemFactory *ifactory;
5917
5918         ifactory = gtk_item_factory_from_widget(compose->menubar);
5919
5920         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5921         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5922         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
5923                            sensitive);
5924         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
5925         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
5926         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
5927         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
5928         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
5929                            sensitive);
5930
5931         gtk_widget_set_sensitive(compose->text,                   sensitive);
5932         gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
5933         gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
5934         gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
5935         gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
5936         gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
5937         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
5938         gtk_widget_set_sensitive(compose->toolbar->linewrap_btn,  sensitive);
5939 }
5940
5941 /**
5942  * compose_undo_state_changed:
5943  *
5944  * Change the sensivity of the menuentries undo and redo
5945  **/
5946 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
5947                                        gint redo_state, gpointer data)
5948 {
5949         GtkWidget *widget = GTK_WIDGET(data);
5950         GtkItemFactory *ifactory;
5951
5952         g_return_if_fail(widget != NULL);
5953
5954         debug_print("Set_undo.  UNDO:%i  REDO:%i\n", undo_state, redo_state);
5955
5956         ifactory = gtk_item_factory_from_widget(widget);
5957
5958         switch (undo_state) {
5959         case UNDO_STATE_TRUE:
5960                 if (!undostruct->undo_state) {
5961                         debug_print ("Set_undo - Testpoint\n");
5962                         undostruct->undo_state = TRUE;
5963                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
5964                 }
5965                 break;
5966         case UNDO_STATE_FALSE:
5967                 if (undostruct->undo_state) {
5968                         undostruct->undo_state = FALSE;
5969                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5970                 }
5971                 break;
5972         case UNDO_STATE_UNCHANGED:
5973                 break;
5974         case UNDO_STATE_REFRESH:
5975                 menu_set_sensitive(ifactory, "/Edit/Undo",
5976                                    undostruct->undo_state);
5977                 break;
5978         default:
5979                 g_warning("Undo state not recognized");
5980                 break;
5981         }
5982
5983         switch (redo_state) {
5984         case UNDO_STATE_TRUE:
5985                 if (!undostruct->redo_state) {
5986                         undostruct->redo_state = TRUE;
5987                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
5988                 }
5989                 break;
5990         case UNDO_STATE_FALSE:
5991                 if (undostruct->redo_state) {
5992                         undostruct->redo_state = FALSE;
5993                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5994                 }
5995                 break;
5996         case UNDO_STATE_UNCHANGED:
5997                 break;
5998         case UNDO_STATE_REFRESH:
5999                 menu_set_sensitive(ifactory, "/Edit/Redo",
6000                                    undostruct->redo_state);
6001                 break;
6002         default:
6003                 g_warning("Redo state not recognized");
6004                 break;
6005         }
6006 }
6007
6008 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
6009 {
6010         gint cursor_pos;
6011
6012         cursor_pos = (text->cursor_pos_x - extra) / char_width;
6013         cursor_pos = MAX(cursor_pos, 0);
6014
6015         return cursor_pos;
6016 }
6017
6018 /* callback functions */
6019
6020 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
6021  * includes "non-client" (windows-izm) in calculation, so this calculation
6022  * may not be accurate.
6023  */
6024 static gboolean compose_edit_size_alloc(GtkEditable *widget,
6025                                         GtkAllocation *allocation,
6026                                         GtkSHRuler *shruler)
6027 {
6028         if (prefs_common.show_ruler) {
6029                 gint char_width;
6030                 gint line_width_in_chars;
6031
6032                 char_width = gtkut_get_font_width
6033                         (GTK_WIDGET(widget)->style->font);
6034                 line_width_in_chars =
6035                         (allocation->width - allocation->x) / char_width;
6036
6037                 /* got the maximum */
6038                 gtk_ruler_set_range(GTK_RULER(shruler),
6039                                     0.0, line_width_in_chars,
6040                                     calc_cursor_xpos(GTK_STEXT(widget),
6041                                                      allocation->x,
6042                                                      char_width),
6043                                     /*line_width_in_chars*/ char_width);
6044         }
6045
6046         return TRUE;
6047 }
6048
6049 static void account_activated(GtkMenuItem *menuitem, gpointer data)
6050 {
6051         Compose *compose = (Compose *)data;
6052
6053         PrefsAccount *ac;
6054
6055         ac = account_find_from_id(
6056                 GPOINTER_TO_INT(gtk_object_get_user_data(GTK_OBJECT(menuitem))));
6057         g_return_if_fail(ac != NULL);
6058
6059         if (ac != compose->account)
6060                 compose_select_account(compose, ac);
6061 }
6062
6063 static void attach_selected(GtkCList *clist, gint row, gint column,
6064                             GdkEvent *event, gpointer data)
6065 {
6066         Compose *compose = (Compose *)data;
6067
6068         if (event && event->type == GDK_2BUTTON_PRESS)
6069                 compose_attach_property(compose);
6070 }
6071
6072 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
6073                                   gpointer data)
6074 {
6075         Compose *compose = (Compose *)data;
6076         GtkCList *clist = GTK_CLIST(compose->attach_clist);
6077         gint row, column;
6078
6079         if (!event) return;
6080
6081         if (event->button == 3) {
6082                 if ((clist->selection && !clist->selection->next) ||
6083                     !clist->selection) {
6084                         gtk_clist_unselect_all(clist);
6085                         if (gtk_clist_get_selection_info(clist,
6086                                                          event->x, event->y,
6087                                                          &row, &column)) {
6088                                 gtk_clist_select_row(clist, row, column);
6089                                 gtkut_clist_set_focus_row(clist, row);
6090                         }
6091                 }
6092                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6093                                NULL, NULL, event->button, event->time);
6094         }
6095 }
6096
6097 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6098                                gpointer data)
6099 {
6100         Compose *compose = (Compose *)data;
6101
6102         if (!event) return;
6103
6104         switch (event->keyval) {
6105         case GDK_Delete:
6106                 compose_attach_remove_selected(compose);
6107                 break;
6108         }
6109 }
6110
6111 static void compose_allow_user_actions (Compose *compose, gboolean allow)
6112 {
6113         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
6114         toolbar_comp_set_sensitive(compose, allow);
6115         menu_set_sensitive(ifactory, "/File", allow);
6116         menu_set_sensitive(ifactory, "/Edit", allow);
6117         menu_set_sensitive(ifactory, "/Spelling", allow);
6118         menu_set_sensitive(ifactory, "/Message", allow);
6119         menu_set_sensitive(ifactory, "/Tools", allow);
6120         menu_set_sensitive(ifactory, "/Help", allow);
6121 }
6122
6123 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
6124 {
6125         Compose *compose = (Compose *)data;
6126         gint val;
6127         
6128         if (prefs_common.work_offline)
6129                 if (alertpanel(_("Offline warning"), 
6130                                _("You're working offline. Override?"),
6131                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
6132                         return;
6133         
6134         compose_allow_user_actions (compose, FALSE);
6135         compose->sending = TRUE;
6136         val = compose_send(compose);
6137         compose_allow_user_actions (compose, TRUE);
6138         compose->sending = FALSE;
6139
6140         if (val == 0) gtk_widget_destroy(compose->window);
6141 }
6142
6143 static void compose_send_later_cb(gpointer data, guint action,
6144                                   GtkWidget *widget)
6145 {
6146         Compose *compose = (Compose *)data;
6147         gint val;
6148
6149         val = compose_queue_sub(compose, NULL, NULL, TRUE);
6150         if (!val) gtk_widget_destroy(compose->window);
6151 }
6152
6153 void compose_draft (gpointer data) 
6154 {
6155         compose_draft_cb(data, 0, NULL);        
6156 }
6157
6158 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
6159 {
6160         Compose *compose = (Compose *)data;
6161         FolderItem *draft;
6162         gchar *tmp;
6163         gint msgnum;
6164         static gboolean lock = FALSE;
6165         MsgInfo *newmsginfo;
6166         
6167         if (lock) return;
6168
6169         draft = account_get_special_folder(compose->account, F_DRAFT);
6170         g_return_if_fail(draft != NULL);
6171
6172         lock = TRUE;
6173
6174         tmp = g_strdup_printf("%s%cdraft.%08x", get_tmp_dir(),
6175                               G_DIR_SEPARATOR, (gint)compose);
6176
6177         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
6178                 g_free(tmp);
6179                 lock = FALSE;
6180                 return;
6181         }
6182
6183         if ((msgnum = folder_item_add_msg(draft, tmp, TRUE)) < 0) {
6184                 unlink(tmp);
6185                 g_free(tmp);
6186                 lock = FALSE;
6187                 return;
6188         }
6189         g_free(tmp);
6190         draft->mtime = 0;       /* force updating */
6191
6192         if (compose->mode == COMPOSE_REEDIT) {
6193                 compose_remove_reedit_target(compose);
6194         }
6195
6196         newmsginfo = folder_item_get_msginfo(draft, msgnum);
6197         if (newmsginfo) {
6198                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
6199                 procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
6200                 procmsg_msginfo_free(newmsginfo);
6201         }
6202         
6203         lock = FALSE;
6204
6205         /* 0: quit editing  1: keep editing  2: keep editing (autosave) */
6206         if (action == 0)
6207                 gtk_widget_destroy(compose->window);
6208         else {
6209                 struct stat s;
6210                 gchar *path;
6211
6212                 path = folder_item_fetch_msg(draft, msgnum);
6213                 g_return_if_fail(path != NULL);
6214                 if (stat(path, &s) < 0) {
6215                         FILE_OP_ERROR(path, "stat");
6216                         g_free(path);
6217                         lock = FALSE;
6218                         return;
6219                 }
6220                 g_free(path);
6221
6222                 procmsg_msginfo_free(compose->targetinfo);
6223                 compose->targetinfo = procmsg_msginfo_new();
6224                 compose->targetinfo->msgnum = msgnum;
6225                 compose->targetinfo->size = s.st_size;
6226                 compose->targetinfo->mtime = s.st_mtime;
6227                 compose->targetinfo->folder = draft;
6228                 compose->mode = COMPOSE_REEDIT;
6229                 
6230                 if (action == 2) {
6231                         compose->autosaved_draft = compose->targetinfo;
6232                 }
6233         }
6234 }
6235
6236 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
6237 {
6238         Compose *compose = (Compose *)data;
6239         GList *file_list;
6240
6241         if (compose->redirect_filename != NULL)
6242                 return;
6243
6244         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6245
6246         if (file_list) {
6247                 GList *tmp;
6248
6249                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6250                         gchar *file = (gchar *) tmp->data;
6251                         compose_attach_append(compose, file, file, NULL);
6252                         compose_changed_cb(NULL, compose);
6253                         g_free(file);
6254                 }
6255                 g_list_free(file_list);
6256         }               
6257 }
6258
6259 static void compose_insert_file_cb(gpointer data, guint action,
6260                                    GtkWidget *widget)
6261 {
6262         Compose *compose = (Compose *)data;
6263         GList *file_list;
6264
6265         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6266
6267         if (file_list) {
6268                 GList *tmp;
6269
6270                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6271                         gchar *file = (gchar *) tmp->data;
6272                         compose_insert_file(compose, file);
6273                         g_free(file);
6274                 }
6275                 g_list_free(file_list);
6276         }
6277 }
6278
6279 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
6280                               gpointer data)
6281 {
6282         Compose *compose = (Compose *)data;
6283         if (compose->sending)
6284                 return TRUE;
6285         compose_close_cb(compose, 0, NULL);
6286         return TRUE;
6287 }
6288
6289 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
6290 {
6291         Compose *compose = (Compose *)data;
6292         AlertValue val;
6293         
6294         if (compose->exteditor_tag != -1) {
6295                 if (!compose_ext_editor_kill(compose))
6296                         return;
6297         }
6298
6299         if (compose->modified) {
6300                 val = alertpanel(_("Discard message"),
6301                                  _("This message has been modified. discard it?"),
6302                                  _("Discard"), _("to Draft"), _("Cancel"));
6303
6304                 switch (val) {
6305                 case G_ALERTDEFAULT:
6306                         if (prefs_common.autosave)
6307                                 compose_remove_draft(compose);                  
6308                         break;
6309                 case G_ALERTALTERNATE:
6310                         compose_draft_cb(data, 0, NULL);
6311                         return;
6312                 default:
6313                         return;
6314                 }
6315         }
6316
6317         gtk_widget_destroy(compose->window);
6318 }
6319
6320 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
6321 {
6322         Compose *compose = (Compose *)data;
6323
6324         addressbook_open(compose);
6325 }
6326
6327 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
6328 {
6329         Compose *compose = (Compose *)data;
6330         Template *tmpl;
6331         gchar *msg;
6332         AlertValue val;
6333
6334         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
6335         g_return_if_fail(tmpl != NULL);
6336
6337         msg = g_strdup_printf(_("Do you want to apply the template `%s' ?"),
6338                               tmpl->name);
6339         val = alertpanel(_("Apply template"), msg,
6340                          _("Replace"), _("Insert"), _("Cancel"));
6341         g_free(msg);
6342
6343         if (val == G_ALERTDEFAULT)
6344                 compose_template_apply(compose, tmpl, TRUE);
6345         else if (val == G_ALERTALTERNATE)
6346                 compose_template_apply(compose, tmpl, FALSE);
6347 }
6348
6349 static void compose_ext_editor_cb(gpointer data, guint action,
6350                                   GtkWidget *widget)
6351 {
6352         Compose *compose = (Compose *)data;
6353
6354         compose_exec_ext_editor(compose);
6355 }
6356
6357 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
6358 {
6359         if (compose->sending)
6360                 return;
6361         compose_destroy(compose);
6362 }
6363
6364 static void compose_undo_cb(Compose *compose)
6365 {
6366         undo_undo(compose->undostruct);
6367 }
6368
6369 static void compose_redo_cb(Compose *compose)
6370 {
6371         undo_redo(compose->undostruct);
6372 }
6373
6374 static void compose_cut_cb(Compose *compose)
6375 {
6376         if (compose->focused_editable &&
6377             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6378                 gtk_editable_cut_clipboard
6379                         (GTK_EDITABLE(compose->focused_editable));
6380 }
6381
6382 static void compose_copy_cb(Compose *compose)
6383 {
6384         if (compose->focused_editable &&
6385             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6386                 gtk_editable_copy_clipboard
6387                         (GTK_EDITABLE(compose->focused_editable));
6388 }
6389
6390 static void compose_paste_cb(Compose *compose)
6391 {
6392         if (compose->focused_editable &&
6393             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6394                 gtk_editable_paste_clipboard
6395                         (GTK_EDITABLE(compose->focused_editable));
6396 }
6397
6398 static void compose_paste_as_quote_cb(Compose *compose)
6399 {
6400         if (compose->focused_editable &&
6401             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
6402                 compose->paste_as_quotation = TRUE;
6403                 gtk_editable_paste_clipboard
6404                         (GTK_EDITABLE(compose->focused_editable));
6405                 compose->paste_as_quotation = FALSE;
6406         }
6407 }
6408
6409 static void compose_allsel_cb(Compose *compose)
6410 {
6411         if (compose->focused_editable &&
6412             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6413                 gtk_editable_select_region
6414                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
6415 }
6416
6417 static void compose_gtk_stext_action_cb(Compose *compose,
6418                                         ComposeCallGtkSTextAction action)
6419 {
6420         GtkSText *text = GTK_STEXT(compose->text);
6421         static struct {
6422                 void (*do_action) (GtkSText *text);
6423         } action_table[] = {
6424                 {gtk_stext_move_beginning_of_line},
6425                 {gtk_stext_move_forward_character},
6426                 {gtk_stext_move_backward_character},
6427                 {gtk_stext_move_forward_word},
6428                 {gtk_stext_move_backward_word},
6429                 {gtk_stext_move_end_of_line},
6430                 {gtk_stext_move_next_line},
6431                 {gtk_stext_move_previous_line},
6432                 {gtk_stext_delete_forward_character},
6433                 {gtk_stext_delete_backward_character},
6434                 {gtk_stext_delete_forward_word},
6435                 {gtk_stext_delete_backward_word},
6436                 {gtk_stext_delete_line},
6437                 {gtk_stext_delete_line}, /* gtk_stext_delete_line_n */
6438                 {gtk_stext_delete_to_line_end}
6439         };
6440
6441         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
6442
6443         if (action >= COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE &&
6444             action <= COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END)
6445                 action_table[action].do_action(text);
6446 }
6447
6448 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
6449 {
6450         if (GTK_IS_EDITABLE(widget))
6451                 compose->focused_editable = widget;
6452 }
6453
6454 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
6455 {
6456         if (compose->modified == FALSE) {
6457                 compose->modified = TRUE;
6458                 compose_set_title(compose);
6459         }
6460 }
6461
6462 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
6463                                     Compose *compose)
6464 {
6465         gtk_stext_set_point(GTK_STEXT(widget),
6466                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6467 }
6468
6469 #if 0
6470 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
6471                                  Compose *compose)
6472 {
6473         gtk_stext_set_point(GTK_STEXT(widget),
6474                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6475 }
6476 #endif
6477
6478 #if 0 /* NEW COMPOSE GUI */
6479 static void compose_toggle_to_cb(gpointer data, guint action,
6480                                  GtkWidget *widget)
6481 {
6482         Compose *compose = (Compose *)data;
6483
6484         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6485                 gtk_widget_show(compose->to_hbox);
6486                 gtk_widget_show(compose->to_entry);
6487                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
6488                 compose->use_to = TRUE;
6489         } else {
6490                 gtk_widget_hide(compose->to_hbox);
6491                 gtk_widget_hide(compose->to_entry);
6492                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
6493                 gtk_widget_queue_resize(compose->table_vbox);
6494                 compose->use_to = FALSE;
6495         }
6496
6497         if (addressbook_get_target_compose() == compose)
6498                 addressbook_set_target_compose(compose);
6499 }
6500
6501 static void compose_toggle_cc_cb(gpointer data, guint action,
6502                                  GtkWidget *widget)
6503 {
6504         Compose *compose = (Compose *)data;
6505
6506         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6507                 gtk_widget_show(compose->cc_hbox);
6508                 gtk_widget_show(compose->cc_entry);
6509                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
6510                 compose->use_cc = TRUE;
6511         } else {
6512                 gtk_widget_hide(compose->cc_hbox);
6513                 gtk_widget_hide(compose->cc_entry);
6514                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
6515                 gtk_widget_queue_resize(compose->table_vbox);
6516                 compose->use_cc = FALSE;
6517         }
6518
6519         if (addressbook_get_target_compose() == compose)
6520                 addressbook_set_target_compose(compose);
6521 }
6522
6523 static void compose_toggle_bcc_cb(gpointer data, guint action,
6524                                   GtkWidget *widget)
6525 {
6526         Compose *compose = (Compose *)data;
6527
6528         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6529                 gtk_widget_show(compose->bcc_hbox);
6530                 gtk_widget_show(compose->bcc_entry);
6531                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
6532                 compose->use_bcc = TRUE;
6533         } else {
6534                 gtk_widget_hide(compose->bcc_hbox);
6535                 gtk_widget_hide(compose->bcc_entry);
6536                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
6537                 gtk_widget_queue_resize(compose->table_vbox);
6538                 compose->use_bcc = FALSE;
6539         }
6540
6541         if (addressbook_get_target_compose() == compose)
6542                 addressbook_set_target_compose(compose);
6543 }
6544
6545 static void compose_toggle_replyto_cb(gpointer data, guint action,
6546                                       GtkWidget *widget)
6547 {
6548         Compose *compose = (Compose *)data;
6549
6550         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6551                 gtk_widget_show(compose->reply_hbox);
6552                 gtk_widget_show(compose->reply_entry);
6553                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
6554                 compose->use_replyto = TRUE;
6555         } else {
6556                 gtk_widget_hide(compose->reply_hbox);
6557                 gtk_widget_hide(compose->reply_entry);
6558                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
6559                 gtk_widget_queue_resize(compose->table_vbox);
6560                 compose->use_replyto = FALSE;
6561         }
6562 }
6563
6564 static void compose_toggle_followupto_cb(gpointer data, guint action,
6565                                          GtkWidget *widget)
6566 {
6567         Compose *compose = (Compose *)data;
6568
6569         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6570                 gtk_widget_show(compose->followup_hbox);
6571                 gtk_widget_show(compose->followup_entry);
6572                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
6573                 compose->use_followupto = TRUE;
6574         } else {
6575                 gtk_widget_hide(compose->followup_hbox);
6576                 gtk_widget_hide(compose->followup_entry);
6577                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
6578                 gtk_widget_queue_resize(compose->table_vbox);
6579                 compose->use_followupto = FALSE;
6580         }
6581 }
6582
6583 static void compose_toggle_attach_cb(gpointer data, guint action,
6584                                      GtkWidget *widget)
6585 {
6586         Compose *compose = (Compose *)data;
6587
6588         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6589                 gtk_widget_ref(compose->edit_vbox);
6590
6591                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6592                                        compose->edit_vbox);
6593                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
6594                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
6595                                    TRUE, TRUE, 0);
6596                 gtk_widget_show(compose->paned);
6597
6598                 gtk_widget_unref(compose->edit_vbox);
6599                 gtk_widget_unref(compose->paned);
6600
6601                 compose->use_attach = TRUE;
6602         } else {
6603                 gtk_widget_ref(compose->paned);
6604                 gtk_widget_ref(compose->edit_vbox);
6605
6606                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6607                                        compose->paned);
6608                 gtkut_container_remove(GTK_CONTAINER(compose->paned),
6609                                        compose->edit_vbox);
6610                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
6611                                    compose->edit_vbox, TRUE, TRUE, 0);
6612
6613                 gtk_widget_unref(compose->edit_vbox);
6614
6615                 compose->use_attach = FALSE;
6616         }
6617 }
6618 #endif
6619
6620 #if USE_GPGME
6621 static void compose_toggle_sign_cb(gpointer data, guint action,
6622                                    GtkWidget *widget)
6623 {
6624         Compose *compose = (Compose *)data;
6625
6626         if (GTK_CHECK_MENU_ITEM(widget)->active)
6627                 compose->use_signing = TRUE;
6628         else
6629                 compose->use_signing = FALSE;
6630
6631         compose_update_gnupg_mode_menu_item(compose);
6632 }
6633
6634 static void compose_toggle_encrypt_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_encryption = TRUE;
6641         else
6642                 compose->use_encryption = FALSE;
6643                 
6644         compose_update_gnupg_mode_menu_item(compose);
6645 }
6646
6647 static void activate_gnupg_mode (Compose *compose, PrefsAccount *account) 
6648 {
6649         if (account->default_gnupg_mode)
6650                 compose->gnupg_mode = GNUPG_MODE_INLINE;
6651         else
6652                 compose->gnupg_mode = GNUPG_MODE_DETACH;
6653                 
6654         compose_update_gnupg_mode_menu_item(compose);
6655 }
6656 #endif /* USE_GPGME */
6657
6658 static void compose_toggle_ruler_cb(gpointer data, guint action,
6659                                     GtkWidget *widget)
6660 {
6661         Compose *compose = (Compose *)data;
6662
6663         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6664                 gtk_widget_show(compose->ruler_hbox);
6665                 prefs_common.show_ruler = TRUE;
6666         } else {
6667                 gtk_widget_hide(compose->ruler_hbox);
6668                 gtk_widget_queue_resize(compose->edit_vbox);
6669                 prefs_common.show_ruler = FALSE;
6670         }
6671 }
6672
6673 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6674                                              GdkDragContext     *drag_context,
6675                                              gint                x,
6676                                              gint                y,
6677                                              GtkSelectionData   *data,
6678                                              guint               info,
6679                                              guint               time,
6680                                              gpointer            user_data)
6681 {
6682         Compose *compose = (Compose *)user_data;
6683         GList *list, *tmp;
6684
6685         list = uri_list_extract_filenames((const gchar *)data->data);
6686         for (tmp = list; tmp != NULL; tmp = tmp->next)
6687                 compose_attach_append
6688                         (compose, (const gchar *)tmp->data,
6689                          (const gchar *)tmp->data, NULL);
6690         if (list) compose_changed_cb(NULL, compose);
6691         list_free_strings(list);
6692         g_list_free(list);
6693 }
6694
6695 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6696                                              GdkDragContext     *drag_context,
6697                                              gint                x,
6698                                              gint                y,
6699                                              GtkSelectionData   *data,
6700                                              guint               info,
6701                                              guint               time,
6702                                              gpointer            user_data)
6703 {
6704         Compose *compose = (Compose *)user_data;
6705         GList *list, *tmp;
6706
6707         list = uri_list_extract_filenames((const gchar *)data->data);
6708         for (tmp = list; tmp != NULL; tmp = tmp->next)
6709                 compose_insert_file(compose, (const gchar *)tmp->data);
6710         list_free_strings(list);
6711         g_list_free(list);
6712 }
6713
6714 #if 0 /* NEW COMPOSE GUI */
6715 static void to_activated(GtkWidget *widget, Compose *compose)
6716 {
6717         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6718                 gtk_widget_grab_focus(compose->newsgroups_entry);
6719         else
6720                 gtk_widget_grab_focus(compose->subject_entry);
6721 }
6722
6723 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6724 {
6725         gtk_widget_grab_focus(compose->subject_entry);
6726 }
6727
6728 static void subject_activated(GtkWidget *widget, Compose *compose)
6729 {
6730         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6731                 gtk_widget_grab_focus(compose->cc_entry);
6732         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6733                 gtk_widget_grab_focus(compose->bcc_entry);
6734         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6735                 gtk_widget_grab_focus(compose->reply_entry);
6736         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6737                 gtk_widget_grab_focus(compose->followup_entry);
6738         else
6739                 gtk_widget_grab_focus(compose->text);
6740 }
6741
6742 static void cc_activated(GtkWidget *widget, Compose *compose)
6743 {
6744         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6745                 gtk_widget_grab_focus(compose->bcc_entry);
6746         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6747                 gtk_widget_grab_focus(compose->reply_entry);
6748         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6749                 gtk_widget_grab_focus(compose->followup_entry);
6750         else
6751                 gtk_widget_grab_focus(compose->text);
6752 }
6753
6754 static void bcc_activated(GtkWidget *widget, Compose *compose)
6755 {
6756         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6757                 gtk_widget_grab_focus(compose->reply_entry);
6758         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6759                 gtk_widget_grab_focus(compose->followup_entry);
6760         else
6761                 gtk_widget_grab_focus(compose->text);
6762 }
6763
6764 static void replyto_activated(GtkWidget *widget, Compose *compose)
6765 {
6766         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6767                 gtk_widget_grab_focus(compose->followup_entry);
6768         else
6769                 gtk_widget_grab_focus(compose->text);
6770 }
6771
6772 static void followupto_activated(GtkWidget *widget, Compose *compose)
6773 {
6774         gtk_widget_grab_focus(compose->text);
6775 }
6776 #endif
6777
6778 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6779                                              GtkWidget *widget)
6780 {
6781         Compose *compose = (Compose *)data;
6782
6783         if (GTK_CHECK_MENU_ITEM(widget)->active)
6784                 compose->return_receipt = TRUE;
6785         else
6786                 compose->return_receipt = FALSE;
6787 }
6788
6789 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6790                                             GdkEventKey *event,
6791                                             ComposeHeaderEntry *headerentry)
6792 {
6793         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6794             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6795             !(event->state & GDK_MODIFIER_MASK) &&
6796             (event->keyval == GDK_BackSpace) &&
6797             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6798                 gtk_container_remove
6799                         (GTK_CONTAINER(headerentry->compose->header_table),
6800                          headerentry->combo);
6801                 gtk_container_remove
6802                         (GTK_CONTAINER(headerentry->compose->header_table),
6803                          headerentry->entry);
6804                 headerentry->compose->header_list =
6805                         g_slist_remove(headerentry->compose->header_list,
6806                                        headerentry);
6807                 g_free(headerentry);
6808         } else  if (event->keyval == GDK_Tab) {
6809                 if (headerentry->compose->header_last == headerentry) {
6810                         /* Override default next focus, and give it to subject_entry
6811                          * instead of notebook tabs
6812                          */
6813                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6814                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6815                 }
6816         }
6817
6818 }
6819
6820 void compose_headerentry_changed_cb(GtkWidget *entry,
6821                                     ComposeHeaderEntry *headerentry)
6822 {
6823         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6824                 headerentry->compose->header_list =
6825                         g_slist_append(headerentry->compose->header_list,
6826                                        headerentry);
6827                 compose_create_header_entry(headerentry->compose);
6828                 gtk_signal_disconnect_by_func
6829                         (GTK_OBJECT(entry),
6830                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6831                          headerentry);
6832                 /* Automatically scroll down */
6833                 compose_show_first_last_header(headerentry->compose, FALSE);
6834                 
6835         }
6836 }
6837
6838 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6839 {
6840         GtkAdjustment *vadj;
6841
6842         g_return_if_fail(compose);
6843         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6844         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6845
6846         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6847         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6848 }
6849
6850 static void text_activated(GtkWidget *widget, Compose *compose)
6851 {
6852         compose_send_control_enter(compose);
6853 }
6854
6855 static void text_inserted(GtkWidget *widget, const gchar *text,
6856                           gint length, gint *position, Compose *compose)
6857 {
6858         GtkEditable *editable = GTK_EDITABLE(widget);
6859
6860         gtk_signal_handler_block_by_func(GTK_OBJECT(widget),
6861                                          GTK_SIGNAL_FUNC(text_inserted),
6862                                          compose);
6863         if (compose->paste_as_quotation) {
6864                 gchar *new_text;
6865                 gchar *qmark;
6866                 gint pos;
6867
6868                 new_text = g_strndup(text, length);
6869                 if (prefs_common.quotemark && *prefs_common.quotemark)
6870                         qmark = prefs_common.quotemark;
6871                 else
6872                         qmark = "> ";
6873                 gtk_stext_set_point(GTK_STEXT(widget), *position);
6874                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text);
6875                 pos = gtk_stext_get_point(GTK_STEXT(widget));
6876                 gtk_editable_set_position(editable, pos);
6877                 *position = pos;
6878                 g_free(new_text);
6879         } else
6880                 gtk_editable_insert_text(editable, text, length, position);
6881
6882         if (prefs_common.autowrap)
6883                 compose_wrap_line_all_full(compose, TRUE);
6884
6885         gtk_signal_handler_unblock_by_func(GTK_OBJECT(widget),
6886                                            GTK_SIGNAL_FUNC(text_inserted),
6887                                            compose);
6888         gtk_signal_emit_stop_by_name(GTK_OBJECT(editable), "insert_text");
6889
6890         
6891         if (prefs_common.autosave && 
6892             gtk_stext_get_length(GTK_STEXT(widget)) % prefs_common.autosave_length == 0)
6893                 compose_draft_cb((gpointer)compose, 2, NULL);
6894 }
6895
6896 static gboolean compose_send_control_enter(Compose *compose)
6897 {
6898         GdkEvent *ev;
6899         GdkEventKey *kev;
6900         GtkItemFactory *ifactory;
6901         GtkAccelEntry *accel;
6902         GtkWidget *send_menu;
6903         GSList *list;
6904         GdkModifierType ignored_mods =
6905                 (GDK_LOCK_MASK | GDK_MOD2_MASK | GDK_MOD3_MASK |
6906                  GDK_MOD4_MASK | GDK_MOD5_MASK);
6907
6908         ev = gtk_get_current_event();
6909         if (ev->type != GDK_KEY_PRESS) return FALSE;
6910
6911         kev = (GdkEventKey *)ev;
6912         if (!(kev->keyval == GDK_Return && (kev->state & GDK_CONTROL_MASK)))
6913                 return FALSE;
6914
6915         ifactory = gtk_item_factory_from_widget(compose->menubar);
6916         send_menu = gtk_item_factory_get_widget(ifactory, "/Message/Send");
6917         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_menu));
6918         if (!list)
6919                 return FALSE;
6920
6921         accel = (GtkAccelEntry *)list->data;
6922         if (accel && accel->accelerator_key == kev->keyval &&
6923             (accel->accelerator_mods & ~ignored_mods) ==
6924             (kev->state & ~ignored_mods)) {
6925                 compose_send_cb(compose, 0, NULL);
6926                 return TRUE;
6927         }
6928
6929         return FALSE;
6930 }
6931
6932 #if USE_ASPELL
6933 static void compose_check_all(Compose *compose)
6934 {
6935         if (compose->gtkaspell)
6936                 gtkaspell_check_all(compose->gtkaspell);
6937 }
6938
6939 static void compose_highlight_all(Compose *compose)
6940 {
6941         if (compose->gtkaspell)
6942                 gtkaspell_highlight_all(compose->gtkaspell);
6943 }
6944
6945 static void compose_check_backwards(Compose *compose)
6946 {
6947         if (compose->gtkaspell) 
6948                 gtkaspell_check_backwards(compose->gtkaspell);
6949         else {
6950                 GtkItemFactory *ifactory;
6951                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6952                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6953                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6954         }
6955 }
6956
6957 static void compose_check_forwards_go(Compose *compose)
6958 {
6959         if (compose->gtkaspell) 
6960                 gtkaspell_check_forwards_go(compose->gtkaspell);
6961         else {
6962                 GtkItemFactory *ifactory;
6963                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6964                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6965                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6966         }
6967 }
6968 #endif
6969