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