3bfc03cd062bb3b34a09fab8dfef53c4d9d84018
[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 #if USE_GPGME
3289                 if (!is_draft &&
3290                     compose->use_signing && !compose->account->clearsign &&
3291                     encoding == ENC_8BIT)
3292                         encoding = ENC_BASE64;
3293 #endif
3294
3295                 src_codeset = conv_get_current_charset_str();
3296                 /* if current encoding is US-ASCII, set it the same as
3297                    outgoing one to prevent code conversion failure */
3298                 if (!strcasecmp(src_codeset, CS_US_ASCII))
3299                         src_codeset = out_codeset;
3300
3301                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3302                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3303
3304                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3305                 if (!buf) {
3306                         AlertValue aval;
3307
3308                         aval = alertpanel
3309                                 (_("Error"),
3310                                  _("Can't convert the character encoding of the message.\n"
3311                                    "Send it anyway?"), _("Yes"), _("+No"), NULL);
3312                         if (aval != G_ALERTDEFAULT) {
3313                                 g_free(chars);
3314                                 fclose(fp);
3315                                 unlink(file);
3316                                 return -1;
3317                         } else {
3318                                 buf = chars;
3319                                 chars = NULL;
3320                         }
3321                 }
3322         }
3323         g_free(chars);
3324
3325 #if USE_GPGME
3326         if (!is_draft && compose->use_signing && compose->account->clearsign) {
3327                 if (compose_clearsign_text(compose, &buf) < 0) {
3328                         g_warning("clearsign failed\n");
3329                         fclose(fp);
3330                         unlink(file);
3331                         g_free(buf);
3332                         return -1;
3333                 }
3334         }
3335 #endif
3336
3337         /* write headers */
3338         if (compose_write_headers
3339                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
3340                 g_warning(_("can't write headers\n"));
3341                 fclose(fp);
3342                 /* unlink(file); */
3343                 g_free(buf);
3344                 return -1;
3345         }
3346
3347         if (compose_use_attach(compose)) {
3348 #if USE_GPGME
3349             /* This prolog message is ignored by mime software and
3350              * because it would make our signing/encryption task
3351              * tougher, we don't emit it in that case */
3352             if (!compose->use_signing && !compose->use_encryption)
3353 #endif
3354                 fputs("This is a multi-part message in MIME format.\n", fp);
3355
3356                 fprintf(fp, "\n--%s\n", compose->boundary);
3357                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
3358                         out_codeset);
3359                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3360                         procmime_get_encoding_str(encoding));
3361                 fputc('\n', fp);
3362         }
3363
3364         /* write body */
3365         len = strlen(buf);
3366         if (encoding == ENC_BASE64) {
3367                 gchar outbuf[B64_BUFFSIZE];
3368                 gint i, l;
3369
3370                 for (i = 0; i < len; i += B64_LINE_SIZE) {
3371                         l = MIN(B64_LINE_SIZE, len - i);
3372                         base64_encode(outbuf, buf + i, l);
3373                         fputs(outbuf, fp);
3374                         fputc('\n', fp);
3375                 }
3376         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
3377                 FILE_OP_ERROR(file, "fwrite");
3378                 fclose(fp);
3379                 unlink(file);
3380                 g_free(buf);
3381                 return -1;
3382         }
3383         g_free(buf);
3384
3385         if (compose_use_attach(compose))
3386                 compose_write_attach(compose, fp);
3387
3388         if (fclose(fp) == EOF) {
3389                 FILE_OP_ERROR(file, "fclose");
3390                 unlink(file);
3391                 return -1;
3392         }
3393
3394 #if USE_GPGME
3395         if (is_draft)
3396                 return 0;
3397
3398         if ((compose->use_signing && !compose->account->clearsign) ||
3399             compose->use_encryption) {
3400                 if (canonicalize_file_replace(file) < 0) {
3401                         unlink(file);
3402                         return -1;
3403                 }
3404         }
3405
3406         if (compose->use_signing && !compose->account->clearsign) {
3407                 GSList *key_list;
3408
3409                 if (compose_create_signers_list(compose, &key_list) < 0 ||
3410                     rfc2015_sign(file, key_list) < 0) {
3411                         unlink(file);
3412                         return -1;
3413                 }
3414         }
3415         if (compose->use_encryption) {
3416                 if (rfc2015_encrypt(file, compose->to_list,
3417                                     compose->account->ascii_armored) < 0) {
3418                         unlink(file);
3419                         return -1;
3420                 }
3421         }
3422 #endif /* USE_GPGME */
3423
3424         return 0;
3425 }
3426
3427 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3428 {
3429         FILE *fp;
3430         size_t len;
3431         gchar *chars;
3432
3433         if ((fp = fopen(file, "wb")) == NULL) {
3434                 FILE_OP_ERROR(file, "fopen");
3435                 return -1;
3436         }
3437
3438         /* chmod for security */
3439         if (change_file_mode_rw(fp, file) < 0) {
3440                 FILE_OP_ERROR(file, "chmod");
3441                 g_warning(_("can't change file mode\n"));
3442         }
3443
3444         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3445
3446         /* write body */
3447         len = strlen(chars);
3448         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3449                 FILE_OP_ERROR(file, "fwrite");
3450                 g_free(chars);
3451                 fclose(fp);
3452                 unlink(file);
3453                 return -1;
3454         }
3455
3456         g_free(chars);
3457
3458         if (fclose(fp) == EOF) {
3459                 FILE_OP_ERROR(file, "fclose");
3460                 unlink(file);
3461                 return -1;
3462         }
3463         return 0;
3464 }
3465
3466 static gint compose_remove_reedit_target(Compose *compose)
3467 {
3468         FolderItem *item;
3469         MsgInfo *msginfo = compose->targetinfo;
3470
3471         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3472         if (!msginfo) return -1;
3473
3474         item = msginfo->folder;
3475         g_return_val_if_fail(item != NULL, -1);
3476
3477         if (procmsg_msg_exist(msginfo) &&
3478             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
3479                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3480                         g_warning(_("can't remove the old message\n"));
3481                         return -1;
3482                 }
3483         }
3484
3485         return 0;
3486 }
3487
3488 void compose_remove_draft(Compose *compose)
3489 {
3490         FolderItem *drafts;
3491         MsgInfo *msginfo = compose->targetinfo;
3492         drafts = account_get_special_folder(compose->account, F_DRAFT);
3493
3494         if (procmsg_msg_exist(msginfo)) {
3495                 folder_item_remove_msg(drafts, msginfo->msgnum);
3496                 folderview_update_item(drafts, TRUE);
3497         }
3498
3499 }
3500
3501 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3502 {
3503         return compose_queue_sub (compose, msgnum, item, FALSE);
3504 }
3505 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
3506 {
3507         FolderItem *queue;
3508         gchar *tmp, *tmp2;
3509         FILE *fp, *src_fp;
3510         GSList *cur;
3511         gchar buf[BUFFSIZE];
3512         gint num;
3513         static gboolean lock = FALSE;
3514         PrefsAccount *mailac = NULL, *newsac = NULL;
3515         
3516         debug_print("queueing message...\n");
3517         g_return_val_if_fail(compose->account != NULL, -1);
3518         g_return_val_if_fail(compose->orig_account != NULL, -1);
3519
3520         lock = TRUE;
3521         
3522         if (compose_check_entries(compose, check_subject) == FALSE) {
3523                 lock = FALSE;
3524                 return -1;
3525         }
3526
3527         if (!compose->to_list && !compose->newsgroup_list) {
3528                 g_warning(_("can't get recipient list."));
3529                 lock = FALSE;
3530                 return -1;
3531         }
3532
3533         if (compose->to_list) {
3534                 if (compose->account->protocol != A_NNTP)
3535                         mailac = compose->account;
3536                 else if (compose->orig_account->protocol != A_NNTP)
3537                         mailac = compose->orig_account;
3538                 else if (cur_account && cur_account->protocol != A_NNTP)
3539                         mailac = cur_account;
3540                 else if (!(mailac = compose_current_mail_account())) {
3541                         lock = FALSE;
3542                         alertpanel_error(_("No account for sending mails available!"));
3543                         return -1;
3544                 }
3545         }
3546
3547         if (compose->newsgroup_list) {
3548                 if (compose->account->protocol == A_NNTP)
3549                         newsac = compose->account;
3550                 else if (!(newsac = compose->orig_account) || (newsac->protocol != A_NNTP)) {
3551                         lock = FALSE;
3552                         alertpanel_error(_("No account for posting news available!"));
3553                         return -1;
3554                 }                       
3555         }
3556
3557         if (prefs_common.linewrap_at_send)
3558                 compose_wrap_line_all(compose);
3559                         
3560         /* write to temporary file */
3561         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3562                                       G_DIR_SEPARATOR, (gint)compose);
3563
3564         if (compose->redirect_filename != NULL) {
3565                 if (compose_redirect_write_to_file(compose, tmp2) < 0) {
3566                         unlink(tmp2);
3567                         lock = FALSE;
3568                         return -1;
3569                 }
3570         }
3571         else {
3572                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3573                         unlink(tmp2);
3574                         lock = FALSE;
3575                         return -1;
3576                 }
3577         }
3578
3579         /* add queue header */
3580         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3581                               G_DIR_SEPARATOR, (gint)compose);
3582         if ((fp = fopen(tmp, "wb")) == NULL) {
3583                 FILE_OP_ERROR(tmp, "fopen");
3584                 g_free(tmp);
3585                 return -1;
3586         }
3587         if ((src_fp = fopen(tmp2, "rb")) == NULL) {
3588                 FILE_OP_ERROR(tmp2, "fopen");
3589                 fclose(fp);
3590                 unlink(tmp);
3591                 g_free(tmp);
3592                 unlink(tmp2);
3593                 g_free(tmp2);
3594                 return -1;
3595         }
3596         if (change_file_mode_rw(fp, tmp) < 0) {
3597                 FILE_OP_ERROR(tmp, "chmod");
3598                 g_warning(_("can't change file mode\n"));
3599         }
3600
3601         /* queueing variables */
3602         fprintf(fp, "AF:\n");
3603         fprintf(fp, "NF:0\n");
3604         fprintf(fp, "PS:10\n");
3605         fprintf(fp, "SRH:1\n");
3606         fprintf(fp, "SFN:\n");
3607         fprintf(fp, "DSR:\n");
3608         if (compose->msgid)
3609                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3610         else
3611                 fprintf(fp, "MID:\n");
3612         fprintf(fp, "CFG:\n");
3613         fprintf(fp, "PT:0\n");
3614         fprintf(fp, "S:%s\n", compose->account->address);
3615         fprintf(fp, "RQ:\n");
3616         if (mailac)
3617                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3618         else
3619                 fprintf(fp, "SSV:\n");
3620         if (newsac)
3621                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3622         else
3623                 fprintf(fp, "NSV:\n");
3624         fprintf(fp, "SSH:\n");
3625         /* write recepient list */
3626         fprintf(fp, "R:");
3627         if (compose->to_list) {
3628                 fprintf(fp, "<%s>", (gchar *)compose->to_list->data);
3629                 for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
3630                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3631         }
3632         fprintf(fp, "\n");
3633         /* write newsgroup list */
3634         fprintf(fp, "NG:");
3635         if (compose->newsgroup_list) {
3636                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3637                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3638                         fprintf(fp, ",%s", (gchar *)cur->data);
3639         }
3640         fprintf(fp, "\n");
3641         /* Sylpheed account IDs */
3642         if (mailac) {
3643                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3644         }
3645         if (newsac) {
3646                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3647         }
3648         /* Save copy folder */
3649         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3650                 gchar *savefolderid;
3651                 
3652                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3653                 fprintf(fp, "SCF:%s\n", savefolderid);
3654                 g_free(savefolderid);
3655         }
3656         /* Message-ID of message replying to */
3657         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
3658                 gchar *folderid;
3659                 
3660                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
3661                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
3662                 g_free(folderid);
3663         }
3664         fprintf(fp, "\n");
3665
3666         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3667                 if (fputs(buf, fp) == EOF) {
3668                         FILE_OP_ERROR(tmp, "fputs");
3669                         fclose(fp);
3670                         fclose(src_fp);
3671                         unlink(tmp);
3672                         g_free(tmp);
3673                         unlink(tmp2);
3674                         g_free(tmp2);
3675                         return -1;
3676                 }
3677         }
3678         fclose(src_fp);
3679         if (fclose(fp) == EOF) {
3680                 FILE_OP_ERROR(tmp, "fclose");
3681                 unlink(tmp);
3682                 g_free(tmp);
3683                 unlink(tmp2);
3684                 g_free(tmp2);
3685                 return -1;
3686         }
3687
3688         queue = account_get_special_folder(compose->account, F_QUEUE);
3689         if (!queue) {
3690                 g_warning(_("can't find queue folder\n"));
3691                 unlink(tmp);
3692                 g_free(tmp);
3693                 return -1;
3694         }
3695         folder_item_scan(queue);
3696         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3697                 g_warning(_("can't queue the message\n"));
3698                 unlink(tmp);
3699                 g_free(tmp);
3700                 return -1;
3701         }
3702         unlink(tmp);
3703         g_free(tmp);
3704         unlink(tmp2);
3705         g_free(tmp2);
3706
3707         if (compose->mode == COMPOSE_REEDIT) {
3708                 compose_remove_reedit_target(compose);
3709                 if (compose->targetinfo &&
3710                     compose->targetinfo->folder != queue)
3711                         folderview_update_item
3712                                 (compose->targetinfo->folder, TRUE);
3713         }
3714
3715         folderview_update_item(queue, TRUE);
3716
3717         if ((msgnum != NULL) && (item != NULL)) {
3718                 *msgnum = num;
3719                 *item = queue;
3720         }
3721
3722         return 0;
3723 }
3724
3725 static void compose_write_attach(Compose *compose, FILE *fp)
3726 {
3727         AttachInfo *ainfo;
3728         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3729         gint row;
3730         FILE *attach_fp;
3731         gchar filename[BUFFSIZE];
3732         gint len;
3733
3734         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3735              row++) {
3736                 gchar buf[BUFFSIZE];
3737                 gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3738
3739                 if ((attach_fp = fopen(ainfo->file, "rb")) == NULL) {
3740                         g_warning(_("Can't open file %s\n"), ainfo->file);
3741                         continue;
3742                 }
3743
3744                 fprintf(fp, "\n--%s\n", compose->boundary);
3745
3746                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3747                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3748                         fprintf(fp, "Content-Disposition: inline\n");
3749                 } else {
3750                         conv_encode_header(filename, sizeof(filename),
3751                                            ainfo->name, 12);
3752                         fprintf(fp, "Content-Type: %s;\n"
3753                                     " name=\"%s\"\n",
3754                                 ainfo->content_type, filename);
3755                         fprintf(fp, "Content-Disposition: attachment;\n"
3756                                     " filename=\"%s\"\n", filename);
3757                 }
3758
3759                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3760                         procmime_get_encoding_str(ainfo->encoding));
3761
3762                 switch (ainfo->encoding) {
3763
3764                 case ENC_7BIT:
3765                 case ENC_8BIT:
3766                         /* if (ainfo->encoding == ENC_7BIT) { */
3767
3768                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3769                                 strcrchomp(buf);
3770                                 fputs(buf, fp);
3771                         }
3772                         break;
3773                         /* } else { */
3774                 case ENC_BASE64:
3775
3776                         while ((len = fread(inbuf, sizeof(gchar),
3777                                             B64_LINE_SIZE, attach_fp))
3778                                == B64_LINE_SIZE) {
3779                                 base64_encode(outbuf, inbuf, B64_LINE_SIZE);
3780                                 fputs(outbuf, fp);
3781                                 fputc('\n', fp);
3782                         }
3783                         if (len > 0 && feof(attach_fp)) {
3784                                 base64_encode(outbuf, inbuf, len);
3785                                 fputs(outbuf, fp);
3786                                 fputc('\n', fp);
3787                         }
3788                         break;
3789                 }
3790
3791                 fclose(attach_fp);
3792         }
3793
3794         fprintf(fp, "\n--%s--\n", compose->boundary);
3795 }
3796
3797 #define QUOTE_IF_REQUIRED(out, str)                     \
3798 {                                                       \
3799         if (*str != '"' && (strchr(str, ',')            \
3800                         || strchr(str, '.'))) {         \
3801                 gchar *__tmp;                           \
3802                 gint len;                               \
3803                                                         \
3804                 len = strlen(str) + 3;                  \
3805                 Xalloca(__tmp, len, return -1);         \
3806                 g_snprintf(__tmp, len, "\"%s\"", str);  \
3807                 out = __tmp;                            \
3808         } else {                                        \
3809                 Xstrdup_a(out, str, return -1);         \
3810         }                                               \
3811 }
3812
3813 #define PUT_RECIPIENT_HEADER(header, str)                                    \
3814 {                                                                            \
3815         if (*str != '\0') {                                                  \
3816                 Xstrdup_a(str, str, return -1);                              \
3817                 g_strstrip(str);                                             \
3818                 if (*str != '\0') {                                          \
3819                         compose->to_list = address_list_append               \
3820                                 (compose->to_list, str);                     \
3821                         compose_convert_header                               \
3822                                 (buf, sizeof(buf), str, strlen(header) + 2); \
3823                         fprintf(fp, "%s: %s\n", header, buf);                \
3824                 }                                                            \
3825         }                                                                    \
3826 }
3827
3828 #define IS_IN_CUSTOM_HEADER(header) \
3829         (compose->account->add_customhdr && \
3830          custom_header_find(compose->account->customhdr_list, header) != NULL)
3831
3832 static gint compose_write_headers_from_headerlist(Compose *compose, 
3833                                                   FILE *fp, 
3834                                                   gchar *header)
3835 {
3836         gchar buf[BUFFSIZE];
3837         gchar *str, *header_w_colon, *trans_hdr;
3838         gboolean first_address;
3839         GSList *list;
3840         ComposeHeaderEntry *headerentry;
3841         gchar * headerentryname;
3842
3843         if (IS_IN_CUSTOM_HEADER(header)) {
3844                 return 0;
3845         }
3846
3847         debug_print("Writing %s-header\n", header);
3848
3849         header_w_colon = g_strconcat(header, ":", NULL);
3850         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3851
3852         first_address = TRUE;
3853         for (list = compose->header_list; list; list = list->next) {
3854                 headerentry = ((ComposeHeaderEntry *)list->data);
3855                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3856
3857                 if (!g_strcasecmp(trans_hdr, headerentryname)) {
3858                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3859                         Xstrdup_a(str, str, return -1);
3860                         g_strstrip(str);
3861                         if (str[0] != '\0') {
3862                                 compose_convert_header
3863                                         (buf, sizeof(buf), str,
3864                                         strlen(header) + 2);
3865                                 if (first_address) {
3866                                         fprintf(fp, "%s: ", header);
3867                                         first_address = FALSE;
3868                                 } else {
3869                                         fprintf(fp, ",");
3870                                 }
3871                                 fprintf(fp, "%s", buf);
3872                         }
3873                 }
3874         }
3875         if (!first_address) {
3876                 fprintf(fp, "\n");
3877         }
3878
3879         g_free(header_w_colon);
3880
3881         return(0);
3882 }
3883
3884 static gint compose_write_headers(Compose *compose, FILE *fp,
3885                                   const gchar *charset, EncodingType encoding,
3886                                   gboolean is_draft)
3887 {
3888         gchar buf[BUFFSIZE];
3889         gchar *str;
3890         gchar *name;
3891         GSList *list;
3892         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3893
3894         /* struct utsname utsbuf; */
3895
3896         g_return_val_if_fail(fp != NULL, -1);
3897         g_return_val_if_fail(charset != NULL, -1);
3898         g_return_val_if_fail(compose->account != NULL, -1);
3899         g_return_val_if_fail(compose->account->address != NULL, -1);
3900
3901         /* Save copy folder */
3902         if (is_draft) {
3903                 if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3904                         gchar *savefolderid;
3905
3906                         savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3907                         fprintf(fp, "SCF:%s\n\n", savefolderid);
3908                         g_free(savefolderid);
3909                 } else {
3910                         fprintf(fp, " \n\n");
3911                 }
3912         }
3913
3914         /* Date */
3915         if (compose->account->add_date) {
3916                 get_rfc822_date(buf, sizeof(buf));
3917                 fprintf(fp, "Date: %s\n", buf);
3918         }
3919
3920         /* From */
3921         if (!IS_IN_CUSTOM_HEADER("From")) {
3922                 if (compose->account->name && *compose->account->name) {
3923                         compose_convert_header
3924                                 (buf, sizeof(buf), compose->account->name,
3925                                  strlen("From: "));
3926                         QUOTE_IF_REQUIRED(name, buf);
3927                         fprintf(fp, "From: %s <%s>\n",
3928                                 name, compose->account->address);
3929                 } else
3930                         fprintf(fp, "From: %s\n", compose->account->address);
3931         }
3932         
3933         /* To */
3934         compose_write_headers_from_headerlist(compose, fp, "To");
3935 #if 0 /* NEW COMPOSE GUI */
3936         if (compose->use_to) {
3937                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3938                 PUT_RECIPIENT_HEADER("To", str);
3939         }
3940 #endif
3941
3942         /* Newsgroups */
3943         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
3944 #if 0 /* NEW COMPOSE GUI */
3945         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3946         if (*str != '\0') {
3947                 Xstrdup_a(str, str, return -1);
3948                 g_strstrip(str);
3949                 remove_space(str);
3950                 if (*str != '\0') {
3951                         compose->newsgroup_list =
3952                                 newsgroup_list_append(compose->newsgroup_list,
3953                                                       str);
3954                         compose_convert_header(buf, sizeof(buf), str,
3955                                                strlen("Newsgroups: "));
3956                         fprintf(fp, "Newsgroups: %s\n", buf);
3957                 }
3958         }
3959 #endif
3960         /* Cc */
3961         compose_write_headers_from_headerlist(compose, fp, "Cc");
3962 #if 0 /* NEW COMPOSE GUI */
3963         if (compose->use_cc) {
3964                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3965                 PUT_RECIPIENT_HEADER("Cc", str);
3966         }
3967 #endif
3968         /* Bcc */
3969         compose_write_headers_from_headerlist(compose, fp, "Bcc");
3970 #if 0 /* NEW COMPOSE GUI */
3971         if (compose->use_bcc) {
3972                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3973                 PUT_RECIPIENT_HEADER("Bcc", str);
3974         }
3975 #endif
3976
3977         /* Subject */
3978         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3979         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3980                 Xstrdup_a(str, str, return -1);
3981                 g_strstrip(str);
3982                 if (*str != '\0') {
3983                         compose_convert_header(buf, sizeof(buf), str,
3984                                                strlen("Subject: "));
3985                         fprintf(fp, "Subject: %s\n", buf);
3986                 }
3987         }
3988
3989         /* Message-ID */
3990         if (compose->account->gen_msgid) {
3991                 compose_generate_msgid(compose, buf, sizeof(buf));
3992                 fprintf(fp, "Message-Id: <%s>\n", buf);
3993                 compose->msgid = g_strdup(buf);
3994         }
3995
3996         /* In-Reply-To */
3997         if (compose->inreplyto && compose->to_list)
3998                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3999
4000         /* References */
4001         if (compose->references)
4002                 fprintf(fp, "References: %s\n", compose->references);
4003
4004         /* Followup-To */
4005         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
4006 #if 0 /* NEW COMPOSE GUI */
4007         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
4008                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
4009                 if (*str != '\0') {
4010                         Xstrdup_a(str, str, return -1);
4011                         g_strstrip(str);
4012                         remove_space(str);
4013                         if (*str != '\0') {
4014                                 compose_convert_header(buf, sizeof(buf), str,
4015                                                        strlen("Followup-To: "));
4016                                 fprintf(fp, "Followup-To: %s\n", buf);
4017                         }
4018                 }
4019         }
4020 #endif
4021         /* Reply-To */
4022         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
4023 #if 0 /* NEW COMPOSE GUI */
4024         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
4025                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
4026                 if (*str != '\0') {
4027                         Xstrdup_a(str, str, return -1);
4028                         g_strstrip(str);
4029                         if (*str != '\0') {
4030                                 compose_convert_header(buf, sizeof(buf), str,
4031                                                        strlen("Reply-To: "));
4032                                 fprintf(fp, "Reply-To: %s\n", buf);
4033                         }
4034                 }
4035         }
4036 #endif
4037         /* Organization */
4038         if (compose->account->organization &&
4039             !IS_IN_CUSTOM_HEADER("Organization")) {
4040                 compose_convert_header(buf, sizeof(buf),
4041                                        compose->account->organization,
4042                                        strlen("Organization: "));
4043                 fprintf(fp, "Organization: %s\n", buf);
4044         }
4045
4046         /* Program version and system info */
4047         /* uname(&utsbuf); */
4048         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
4049                 fprintf(fp, "X-Mailer: %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         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4056                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4057                         prog_version,
4058                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4059                         TARGET_ALIAS);
4060                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4061         }
4062
4063         /* custom headers */
4064         if (compose->account->add_customhdr) {
4065                 GSList *cur;
4066
4067                 for (cur = compose->account->customhdr_list; cur != NULL;
4068                      cur = cur->next) {
4069                         CustomHeader *chdr = (CustomHeader *)cur->data;
4070
4071                         if (strcasecmp(chdr->name, "Date")         != 0 &&
4072                             strcasecmp(chdr->name, "From")         != 0 &&
4073                             strcasecmp(chdr->name, "To")           != 0 &&
4074                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
4075                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
4076                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
4077                             strcasecmp(chdr->name, "References")   != 0 &&
4078                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
4079                             strcasecmp(chdr->name, "Content-Type") != 0 &&
4080                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
4081                             != 0) {
4082                                 compose_convert_header
4083                                         (buf, sizeof(buf),
4084                                          chdr->value ? chdr->value : "",
4085                                          strlen(chdr->name) + 2);
4086                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
4087                         }
4088                 }
4089         }
4090
4091         /* MIME */
4092         fprintf(fp, "Mime-Version: 1.0\n");
4093         if (compose_use_attach(compose)) {
4094                 get_rfc822_date(buf, sizeof(buf));
4095                 subst_char(buf, ' ', '_');
4096                 subst_char(buf, ',', '_');
4097                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
4098                                                     buf, (guint)compose);
4099                 fprintf(fp,
4100                         "Content-Type: multipart/mixed;\n"
4101                         " boundary=\"%s\"\n", compose->boundary);
4102         } else {
4103                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
4104                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
4105                         procmime_get_encoding_str(encoding));
4106         }
4107
4108         /* PRIORITY */
4109         switch (compose->priority) {
4110                 case PRIORITY_HIGHEST: fprintf(fp, "Importance: high\n"
4111                                                    "X-Priority: 1 (Highest)\n");
4112                         break;
4113                 case PRIORITY_HIGH: fprintf(fp, "Importance: high\n"
4114                                                 "X-Priority: 2 (High)\n");
4115                         break;
4116                 case PRIORITY_NORMAL: break;
4117                 case PRIORITY_LOW: fprintf(fp, "Importance: low\n"
4118                                                "X-Priority: 4 (Low)\n");
4119                         break;
4120                 case PRIORITY_LOWEST: fprintf(fp, "Importance: low\n"
4121                                                   "X-Priority: 5 (Lowest)\n");
4122                         break;
4123                 default: debug_print("compose: priority unknown : %d\n",
4124                                      compose->priority);
4125         }
4126
4127         /* Request Return Receipt */
4128         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4129                 if (compose->return_receipt) {
4130                         if (compose->account->name
4131                             && *compose->account->name) {
4132                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
4133                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4134                         } else
4135                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
4136                 }
4137         }
4138
4139         /* get special headers */
4140         for (list = compose->header_list; list; list = list->next) {
4141                 ComposeHeaderEntry *headerentry;
4142                 gchar *tmp;
4143                 gchar *headername;
4144                 gchar *headername_wcolon;
4145                 gchar *headername_trans;
4146                 gchar *headervalue;
4147                 gchar **string;
4148                 gboolean standard_header = FALSE;
4149
4150                 headerentry = ((ComposeHeaderEntry *)list->data);
4151                 
4152                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4153                 if (!strstr(tmp, ":")) {
4154                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4155                         headername = g_strdup(tmp);
4156                 } else {
4157                         headername_wcolon = g_strdup(tmp);
4158                         headername = g_strdup(strtok(tmp, ":"));
4159                 }
4160                 g_free(tmp);
4161                 
4162                 headervalue = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4163                 string = std_headers;
4164                 while (*string != NULL) {
4165                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4166                         if (!strcmp(headername_trans,headername_wcolon))
4167                                 standard_header = TRUE;
4168                         string++;
4169                 }
4170                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4171                         fprintf(fp, "%s %s\n", headername_wcolon, headervalue);
4172                                 
4173                 g_free(headername);
4174                 g_free(headername_wcolon);
4175                 
4176         }
4177
4178         /* separator between header and body */
4179         fputs("\n", fp);
4180
4181         return 0;
4182 }
4183
4184 #undef IS_IN_CUSTOM_HEADER
4185
4186 static void compose_convert_header(gchar *dest, gint len, gchar *src,
4187                                    gint header_len)
4188 {
4189         g_return_if_fail(src != NULL);
4190         g_return_if_fail(dest != NULL);
4191
4192         if (len < 1) return;
4193
4194         remove_return(src);
4195
4196         if (is_ascii_str(src)) {
4197                 strncpy2(dest, src, len);
4198                 dest[len - 1] = '\0';
4199                 return;
4200         } else
4201                 conv_encode_header(dest, len, src, header_len);
4202 }
4203
4204 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
4205 {
4206         struct tm *lt;
4207         time_t t;
4208         gchar *addr;
4209
4210         t = time(NULL);
4211         lt = localtime(&t);
4212
4213         if (compose->account && compose->account->address &&
4214             *compose->account->address) {
4215                 if (strchr(compose->account->address, '@'))
4216                         addr = g_strdup(compose->account->address);
4217                 else
4218                         addr = g_strconcat(compose->account->address, "@",
4219                                            get_domain_name(), NULL);
4220         } else
4221                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
4222                                    NULL);
4223
4224         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
4225                    lt->tm_year + 1900, lt->tm_mon + 1,
4226                    lt->tm_mday, lt->tm_hour,
4227                    lt->tm_min, lt->tm_sec,
4228                    (guint)random(), addr);
4229
4230         debug_print("generated Message-ID: %s\n", buf);
4231
4232         g_free(addr);
4233 }
4234
4235 static void compose_create_header_entry(Compose *compose) 
4236 {
4237         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4238
4239         GtkWidget *combo;
4240         GtkWidget *entry;
4241         GList *combo_list = NULL;
4242         gchar **string, *header;
4243         ComposeHeaderEntry *headerentry;
4244         gboolean standard_header = FALSE;
4245
4246         headerentry = g_new0(ComposeHeaderEntry, 1);
4247
4248         /* Combo box */
4249         combo = gtk_combo_new();
4250         string = headers; 
4251         while(*string != NULL) {
4252             combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
4253             string++;
4254         }
4255         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
4256         g_list_free(combo_list);
4257         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
4258         gtk_widget_show(combo);
4259         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
4260         if (compose->header_last) {     
4261                 gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4262                 string = headers;
4263                 while (*string != NULL) {
4264                         if (!strcmp(*string, last_header_entry))
4265                                 standard_header = TRUE;
4266                         string++;
4267                 }
4268                 if (standard_header)
4269                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4270         }
4271         if (!compose->header_last || !standard_header) {
4272                 switch(compose->account->protocol) {
4273                         case A_NNTP:
4274                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
4275                                 break;
4276                         default:
4277                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
4278                                 break;
4279                 }                                                                   
4280         }
4281         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
4282
4283         /* Entry field */
4284         entry = gtk_entry_new(); 
4285         gtk_widget_show(entry);
4286         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);
4287
4288         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
4289         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
4290         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4291
4292         address_completion_register_entry(GTK_ENTRY(entry));
4293
4294         headerentry->compose = compose;
4295         headerentry->combo = combo;
4296         headerentry->entry = entry;
4297         headerentry->headernum = compose->header_nextrow;
4298
4299         compose->header_nextrow++;
4300         compose->header_last = headerentry;
4301 }
4302
4303 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
4304 {
4305         ComposeHeaderEntry *last_header;
4306         
4307         last_header = compose->header_last;
4308         
4309         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
4310         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
4311 }
4312
4313 static GtkWidget *compose_create_header(Compose *compose) 
4314 {
4315         GtkWidget *label;
4316         GtkWidget *hbox;
4317         GtkWidget *from_optmenu_hbox;
4318 #if 0 /* NEW COMPOSE GUI */
4319         GtkWidget *to_entry;
4320         GtkWidget *to_hbox;
4321         GtkWidget *newsgroups_entry;
4322         GtkWidget *newsgroups_hbox;
4323 #endif
4324         GtkWidget *header_scrolledwin;
4325         GtkWidget *header_table;
4326 #if 0 /* NEW COMPOSE GUI */
4327         GtkWidget *cc_entry;
4328         GtkWidget *cc_hbox;
4329         GtkWidget *bcc_entry;
4330         GtkWidget *bcc_hbox;
4331         GtkWidget *reply_entry;
4332         GtkWidget *reply_hbox;
4333         GtkWidget *followup_entry;
4334         GtkWidget *followup_hbox;
4335 #endif
4336
4337         gint count = 0;
4338
4339         /* header labels and entries */
4340         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4341         gtk_widget_show(header_scrolledwin);
4342         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
4343
4344         header_table = gtk_table_new(2, 2, FALSE);
4345         gtk_widget_show(header_table);
4346         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
4347         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
4348         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
4349         count = 0;
4350
4351         /* option menu for selecting accounts */
4352         hbox = gtk_hbox_new(FALSE, 0);
4353         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
4354         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
4355         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
4356                          GTK_FILL, 0, 2, 0);
4357         from_optmenu_hbox = compose_account_option_menu_create(compose);
4358         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
4359                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
4360 #if 0 /* NEW COMPOSE GUI */
4361         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4362 #endif
4363         count++;
4364
4365         compose->header_table = header_table;
4366         compose->header_list = NULL;
4367         compose->header_nextrow = count;
4368
4369         compose_create_header_entry(compose);
4370
4371 #if 0 /* NEW COMPOSE GUI */
4372         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
4373                                 "To:", TRUE); 
4374         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4375         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
4376                                 &count, "Newsgroups:", FALSE);
4377         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
4378
4379         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
4380
4381         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
4382                                 "Cc:", TRUE);
4383         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
4384         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
4385                                 "Bcc:", TRUE);
4386         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
4387         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
4388                                 "Reply-To:", TRUE);
4389         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
4390         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
4391                                 "Followup-To:", FALSE);
4392         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
4393
4394         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
4395
4396         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
4397                            GTK_SIGNAL_FUNC(to_activated), compose);
4398         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
4399                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
4400         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
4401                            GTK_SIGNAL_FUNC(subject_activated), compose);
4402         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
4403                            GTK_SIGNAL_FUNC(cc_activated), compose);
4404         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
4405                            GTK_SIGNAL_FUNC(bcc_activated), compose);
4406         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
4407                            GTK_SIGNAL_FUNC(replyto_activated), compose);
4408         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
4409                            GTK_SIGNAL_FUNC(followupto_activated), compose);
4410
4411         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
4412                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4413         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
4414                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4415         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
4416                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4417         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
4418                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4419         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
4420                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4421         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
4422                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4423         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
4424                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4425 #endif
4426
4427         compose->table            = NULL;
4428 #if 0 /* NEW COMPOSE GUI */
4429         compose->table            = table;
4430         compose->to_hbox          = to_hbox;
4431         compose->to_entry         = to_entry;
4432         compose->newsgroups_hbox  = newsgroups_hbox;
4433         compose->newsgroups_entry = newsgroups_entry;
4434 #endif
4435 #if 0 /* NEW COMPOSE GUI */
4436         compose->cc_hbox          = cc_hbox;
4437         compose->cc_entry         = cc_entry;
4438         compose->bcc_hbox         = bcc_hbox;
4439         compose->bcc_entry        = bcc_entry;
4440         compose->reply_hbox       = reply_hbox;
4441         compose->reply_entry      = reply_entry;
4442         compose->followup_hbox    = followup_hbox;
4443         compose->followup_entry   = followup_entry;
4444 #endif
4445
4446         return header_scrolledwin ;
4447 }
4448
4449 GtkWidget *compose_create_attach(Compose *compose)
4450 {
4451         gchar *titles[N_ATTACH_COLS];
4452         gint i;
4453
4454         GtkWidget *attach_scrwin;
4455         GtkWidget *attach_clist;
4456
4457         titles[COL_MIMETYPE] = _("MIME type");
4458         titles[COL_SIZE]     = _("Size");
4459         titles[COL_NAME]     = _("Name");
4460
4461         /* attachment list */
4462         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
4463         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
4464                                        GTK_POLICY_AUTOMATIC,
4465                                        GTK_POLICY_ALWAYS);
4466         gtk_widget_set_usize(attach_scrwin, -1, 80);
4467
4468         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
4469         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
4470                                            GTK_JUSTIFY_RIGHT);
4471         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
4472         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
4473         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
4474                                      GTK_SELECTION_EXTENDED);
4475         for (i = 0; i < N_ATTACH_COLS; i++)
4476                 GTK_WIDGET_UNSET_FLAGS
4477                         (GTK_CLIST(attach_clist)->column[i].button,
4478                          GTK_CAN_FOCUS);
4479         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
4480
4481         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4482                            GTK_SIGNAL_FUNC(attach_selected), compose);
4483         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4484                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4485         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4486                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4487
4488         /* drag and drop */
4489         gtk_drag_dest_set(attach_clist,
4490                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4491                           GDK_ACTION_COPY);
4492         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4493                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4494                            compose);
4495
4496         compose->attach_scrwin = attach_scrwin;
4497         compose->attach_clist  = attach_clist;
4498
4499         return attach_scrwin;
4500 }
4501
4502 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4503 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4504
4505 static GtkWidget *compose_create_others(Compose *compose)
4506 {
4507         GtkWidget *table;
4508         GtkWidget *savemsg_checkbtn;
4509         GtkWidget *savemsg_entry;
4510         GtkWidget *savemsg_select;
4511         
4512         guint rowcount = 0;
4513         gchar *folderidentifier;
4514
4515         /* Table for settings */
4516         table = gtk_table_new(3, 1, FALSE);
4517         gtk_widget_show(table);
4518         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4519         rowcount = 0;
4520
4521         /* Save Message to folder */
4522         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4523         gtk_widget_show(savemsg_checkbtn);
4524         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4525         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4526                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4527         }
4528         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4529                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4530
4531         savemsg_entry = gtk_entry_new();
4532         gtk_widget_show(savemsg_entry);
4533         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4534         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4535         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4536                 folderidentifier = folder_item_get_identifier(account_get_special_folder
4537                                   (compose->account, F_OUTBOX));
4538                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4539                 g_free(folderidentifier);
4540         }
4541
4542         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4543         gtk_widget_show (savemsg_select);
4544         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4545         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4546                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4547                             compose);
4548
4549         rowcount++;
4550
4551         compose->savemsg_checkbtn = savemsg_checkbtn;
4552         compose->savemsg_entry = savemsg_entry;
4553
4554         return table;   
4555 }
4556
4557 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4558 {
4559         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4560                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4561 }
4562
4563 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4564 {
4565         FolderItem *dest;
4566         gchar * path;
4567
4568         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
4569         if (!dest) return;
4570
4571         path = folder_item_get_identifier(dest);
4572
4573         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4574         g_free(path);
4575 }
4576
4577 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4578 {
4579         Compose   *compose;
4580         GtkWidget *window;
4581         GtkWidget *vbox;
4582         GtkWidget *menubar;
4583         GtkWidget *handlebox;
4584
4585         GtkWidget *notebook;
4586
4587         GtkWidget *vbox2;
4588
4589         GtkWidget *label;
4590         GtkWidget *subject_hbox;
4591         GtkWidget *subject_frame;
4592         GtkWidget *subject_entry;
4593         GtkWidget *subject;
4594         GtkWidget *paned;
4595
4596         GtkWidget *edit_vbox;
4597         GtkWidget *ruler_hbox;
4598         GtkWidget *ruler;
4599         GtkWidget *scrolledwin;
4600         GtkWidget *text;
4601
4602         UndoMain *undostruct;
4603
4604         gchar *titles[N_ATTACH_COLS];
4605         guint n_menu_entries;
4606         GtkStyle  *style, *new_style;
4607         GdkColormap *cmap;
4608         GdkColor color[1];
4609         gboolean success[1];
4610         GdkFont   *font;
4611         GtkWidget *popupmenu;
4612         GtkItemFactory *popupfactory;
4613         GtkItemFactory *ifactory;
4614         GtkWidget *tmpl_menu;
4615         gint n_entries;
4616
4617 #if USE_ASPELL
4618         GtkAspell * gtkaspell = NULL;
4619 #endif
4620
4621         static GdkGeometry geometry;
4622
4623         g_return_val_if_fail(account != NULL, NULL);
4624
4625         debug_print("Creating compose window...\n");
4626         compose = g_new0(Compose, 1);
4627
4628         titles[COL_MIMETYPE] = _("MIME type");
4629         titles[COL_SIZE]     = _("Size");
4630         titles[COL_NAME]     = _("Name");
4631
4632         compose->account = account;
4633         compose->orig_account = account;
4634
4635         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4636         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4637         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4638         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4639
4640         if (!geometry.max_width) {
4641                 geometry.max_width = gdk_screen_width();
4642                 geometry.max_height = gdk_screen_height();
4643         }
4644         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
4645                                       &geometry, GDK_HINT_MAX_SIZE);
4646
4647         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4648                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4649         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4650                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4651         MANAGE_WINDOW_SIGNALS_CONNECT(window);
4652         gtk_widget_realize(window);
4653
4654         gtkut_widget_set_composer_icon(window);
4655
4656         vbox = gtk_vbox_new(FALSE, 0);
4657         gtk_container_add(GTK_CONTAINER(window), vbox);
4658
4659         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4660         menubar = menubar_create(window, compose_entries,
4661                                  n_menu_entries, "<Compose>", compose);
4662         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4663
4664         handlebox = gtk_handle_box_new();
4665         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4666
4667         compose_toolbar_create(compose, handlebox);
4668
4669         vbox2 = gtk_vbox_new(FALSE, 2);
4670         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4671         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4672         
4673         /* Notebook */
4674         notebook = gtk_notebook_new();
4675         gtk_widget_set_usize(notebook, -1, 130);
4676         gtk_widget_show(notebook);
4677
4678         /* header labels and entries */
4679         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4680         /* attachment list */
4681         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4682         /* Others Tab */
4683         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4684
4685         /* Subject */
4686         subject_hbox = gtk_hbox_new(FALSE, 0);
4687         gtk_widget_show(subject_hbox);
4688
4689         subject_frame = gtk_frame_new(NULL);
4690         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4691         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4692         gtk_widget_show(subject_frame);
4693
4694         subject = gtk_hbox_new(FALSE, 0);
4695         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4696         gtk_widget_show(subject);
4697
4698         label = gtk_label_new(_("Subject:"));
4699         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4700         gtk_widget_show(label);
4701
4702         subject_entry = gtk_entry_new();
4703         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4704         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4705         gtk_widget_show(subject_entry);
4706         compose->subject_entry = subject_entry;
4707         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4708         
4709         edit_vbox = gtk_vbox_new(FALSE, 0);
4710 #if 0 /* NEW COMPOSE GUI */
4711         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
4712 #endif
4713
4714         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4715
4716         /* ruler */
4717         ruler_hbox = gtk_hbox_new(FALSE, 0);
4718         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4719
4720         ruler = gtk_shruler_new();
4721         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4722         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4723                            BORDER_WIDTH + 1);
4724         gtk_widget_set_usize(ruler_hbox, 1, -1);
4725
4726         /* text widget */
4727         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4728         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4729                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4730         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4731         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4732
4733         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4734                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4735                             gtk_scrolled_window_get_vadjustment
4736                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4737         GTK_STEXT(text)->default_tab_width = 8;
4738         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4739
4740         if (prefs_common.block_cursor) {
4741                 GTK_STEXT(text)->cursor_type = GTK_STEXT_CURSOR_BLOCK;
4742         }
4743         
4744         if (prefs_common.smart_wrapping) {      
4745                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
4746                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
4747         }               
4748
4749         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4750
4751         gtk_signal_connect(GTK_OBJECT(text), "changed",
4752                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4753         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4754                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4755         gtk_signal_connect(GTK_OBJECT(text), "activate",
4756                            GTK_SIGNAL_FUNC(text_activated), compose);
4757         gtk_signal_connect(GTK_OBJECT(text), "insert_text",
4758                            GTK_SIGNAL_FUNC(text_inserted), compose);
4759         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4760                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4761                                  edit_vbox);
4762 #if 0
4763         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4764                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4765                                  compose);
4766 #endif
4767         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4768                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4769                                  ruler);
4770
4771         /* drag and drop */
4772         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4773                           GDK_ACTION_COPY);
4774         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4775                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4776                            compose);
4777         gtk_widget_show_all(vbox);
4778
4779         /* pane between attach clist and text */
4780         paned = gtk_vpaned_new();
4781         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4782         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4783         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4784         gtk_paned_add1(GTK_PANED(paned), notebook);
4785         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4786         gtk_widget_show_all(paned);
4787
4788         style = gtk_widget_get_style(text);
4789
4790         /* workaround for the slow down of GtkSText when using Pixmap theme */
4791         if (style->engine) {
4792                 GtkThemeEngine *engine;
4793
4794                 engine = style->engine;
4795                 style->engine = NULL;
4796                 new_style = gtk_style_copy(style);
4797                 style->engine = engine;
4798         } else
4799                 new_style = gtk_style_copy(style);
4800
4801         if (prefs_common.textfont) {
4802                 if (MB_CUR_MAX == 1) {
4803                         gchar *fontstr, *p;
4804
4805                         Xstrdup_a(fontstr, prefs_common.textfont, );
4806                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
4807                                 *p = '\0';
4808                         font = gdk_font_load(fontstr);
4809                 } else
4810                         font = gdk_fontset_load(prefs_common.textfont);
4811                 if (font) {
4812                         gdk_font_unref(new_style->font);
4813                         new_style->font = font;
4814                 }
4815         }
4816
4817         gtk_widget_set_style(text, new_style);
4818
4819         color[0] = quote_color;
4820         cmap = gdk_window_get_colormap(window->window);
4821         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4822         if (success[0] == FALSE) {
4823                 g_warning("Compose: color allocation failed.\n");
4824                 style = gtk_widget_get_style(text);
4825                 quote_color = style->black;
4826         }
4827
4828         n_entries = sizeof(compose_popup_entries) /
4829                 sizeof(compose_popup_entries[0]);
4830         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4831                                       "<Compose>", &popupfactory,
4832                                       compose);
4833
4834         ifactory = gtk_item_factory_from_widget(menubar);
4835         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4836         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4837
4838         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
4839 #if 0 /* NEW COMPOSE GUI */
4840         gtk_widget_hide(bcc_hbox);
4841         gtk_widget_hide(bcc_entry);
4842         gtk_widget_hide(reply_hbox);
4843         gtk_widget_hide(reply_entry);
4844         gtk_widget_hide(followup_hbox);
4845         gtk_widget_hide(followup_entry);
4846         gtk_widget_hide(ruler_hbox);
4847         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4848         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4849         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4850
4851         if (account->protocol == A_NNTP) {
4852                 gtk_widget_hide(to_hbox);
4853                 gtk_widget_hide(to_entry);
4854                 gtk_widget_hide(cc_hbox);
4855                 gtk_widget_hide(cc_entry);
4856                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
4857                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
4858         } else {
4859                 gtk_widget_hide(newsgroups_hbox);
4860                 gtk_widget_hide(newsgroups_entry);
4861                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
4862         }
4863 #endif
4864
4865         update_compose_actions_menu(ifactory, "/Tools/Actions", compose);
4866
4867
4868         undostruct = undo_init(text);
4869         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
4870                                    menubar);
4871
4872         address_completion_start(window);
4873
4874         compose->window        = window;
4875         compose->vbox          = vbox;
4876         compose->menubar       = menubar;
4877         compose->handlebox     = handlebox;
4878
4879         compose->vbox2         = vbox2;
4880
4881         compose->paned = paned;
4882
4883         compose->edit_vbox     = edit_vbox;
4884         compose->ruler_hbox    = ruler_hbox;
4885         compose->ruler         = ruler;
4886         compose->scrolledwin   = scrolledwin;
4887         compose->text          = text;
4888
4889         compose->focused_editable = NULL;
4890
4891         compose->popupmenu    = popupmenu;
4892         compose->popupfactory = popupfactory;
4893
4894         compose->tmpl_menu = tmpl_menu;
4895
4896         compose->mode = mode;
4897
4898         compose->targetinfo = NULL;
4899         compose->replyinfo  = NULL;
4900
4901         compose->replyto     = NULL;
4902         compose->mailinglist = NULL;
4903         compose->cc          = NULL;
4904         compose->bcc         = NULL;
4905         compose->followup_to = NULL;
4906         compose->inreplyto   = NULL;
4907         compose->references  = NULL;
4908         compose->msgid       = NULL;
4909         compose->boundary    = NULL;
4910
4911 #if USE_GPGME
4912         compose->use_signing    = FALSE;
4913         compose->use_encryption = FALSE;
4914 #endif /* USE_GPGME */
4915
4916         compose->modified = FALSE;
4917
4918         compose->return_receipt = FALSE;
4919         compose->paste_as_quotation = FALSE;
4920
4921         compose->to_list        = NULL;
4922         compose->newsgroup_list = NULL;
4923
4924         compose->exteditor_file    = NULL;
4925         compose->exteditor_pid     = -1;
4926         compose->exteditor_readdes = -1;
4927         compose->exteditor_tag     = -1;
4928
4929         compose->redirect_filename = NULL;
4930         compose->undostruct = undostruct;
4931 #if USE_ASPELL
4932         
4933         menu_set_sensitive(ifactory, "/Spelling", FALSE);
4934         if (prefs_common.enable_aspell) {
4935                 gtkaspell = gtkaspell_new((const gchar*)prefs_common.dictionary,
4936                                           conv_get_current_charset_str(),
4937                                           prefs_common.misspelled_col,
4938                                           prefs_common.check_while_typing,
4939                                           prefs_common.use_alternate,
4940                                           GTK_STEXT(text));
4941                 if (!gtkaspell) {
4942                         alertpanel_error(_("Spell checker could not be started.\n%s"), gtkaspellcheckers->error_message);
4943                         gtkaspell_checkers_reset_error();
4944                 } else {
4945
4946                         GtkWidget *menuitem;
4947
4948                         if (!gtkaspell_set_sug_mode(gtkaspell, prefs_common.aspell_sugmode)) {
4949                                 debug_print("Aspell: could not set suggestion mode %s\n",
4950                                     gtkaspellcheckers->error_message);
4951                                 gtkaspell_checkers_reset_error();
4952                         }
4953
4954                         menuitem = gtk_item_factory_get_item(ifactory, "/Spelling/Spelling Configuration");
4955                         gtkaspell_populate_submenu(gtkaspell, menuitem);
4956                         menu_set_sensitive(ifactory, "/Spelling", TRUE);
4957                         }
4958         }
4959 #endif
4960
4961         compose_select_account(compose, account);
4962
4963 #if USE_ASPELL
4964         compose->gtkaspell      = gtkaspell;
4965 #endif
4966
4967         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
4968                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
4969
4970         if (account->set_autobcc) 
4971                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
4972         
4973         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
4974                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
4975
4976
4977         if (account->protocol != A_NNTP)
4978                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
4979         else
4980                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
4981
4982         addressbook_set_target_compose(compose);
4983         update_compose_actions_menu(ifactory, "/Tools/Actions", compose);
4984         compose_set_template_menu(compose);
4985
4986         compose_list = g_list_append(compose_list, compose);
4987
4988         if (!prefs_common.show_ruler)
4989                 gtk_widget_hide(ruler_hbox);
4990
4991         /* Priority */
4992         compose->priority = PRIORITY_NORMAL;
4993         compose_update_priority_menu_item(compose);
4994
4995         set_toolbar_style(compose);
4996
4997         gtk_widget_show(window);
4998         
4999         return compose;
5000 }
5001
5002 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
5003 {
5004         GtkWidget *toolbar;
5005         GtkWidget *icon_wid;
5006         GtkWidget *send_btn;
5007         GtkWidget *sendl_btn;
5008         GtkWidget *draft_btn;
5009         GtkWidget *insert_btn;
5010         GtkWidget *attach_btn;
5011         GtkWidget *sig_btn;
5012         GtkWidget *exteditor_btn;
5013         GtkWidget *linewrap_btn;
5014         GtkWidget *addrbook_btn;
5015
5016         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
5017                                   GTK_TOOLBAR_BOTH);
5018         gtk_container_add(GTK_CONTAINER(container), toolbar);
5019         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
5020         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
5021         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
5022                                     GTK_TOOLBAR_SPACE_LINE);
5023
5024         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND);
5025         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5026                                            _("Send"),
5027                                            _("Send message"),
5028                                            "Send",
5029                                            icon_wid, toolbar_send_cb, compose);
5030
5031         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND_QUEUE);
5032         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5033                                            _("Send later"),
5034                                            _("Put into queue folder and send later"),
5035                                            "Send later",
5036                                            icon_wid, toolbar_send_later_cb,
5037                                            compose);
5038
5039         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL);
5040         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5041                                             _("Draft"),
5042                                             _("Save to draft folder"),
5043                                             "Draft",
5044                                             icon_wid, toolbar_draft_cb,
5045                                             compose);
5046
5047         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
5048
5049         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_INSERT_FILE);
5050         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5051                                              _("Insert"),
5052                                              _("Insert file"),
5053                                              "Insert",
5054                                              icon_wid, toolbar_insert_cb,
5055                                              compose);
5056
5057         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_ATTACH);
5058         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5059                                              _("Attach"),
5060                                              _("Attach file"),
5061                                              "Attach",
5062                                              icon_wid, toolbar_attach_cb,
5063                                              compose);
5064
5065         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
5066
5067         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SIGN);
5068         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5069                                           _("Signature"),
5070                                           _("Insert signature"),
5071                                           "Signature",
5072                                           icon_wid, toolbar_sig_cb, compose);
5073
5074         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
5075
5076         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_EDIT_EXTERN);
5077         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5078                                                 _("Editor"),
5079                                                 _("Edit with external editor"),
5080                                                 "Editor",
5081                                                 icon_wid,
5082                                                 toolbar_ext_editor_cb,
5083                                                 compose);
5084
5085         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_LINEWRAP);
5086         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5087                                                _("Linewrap"),
5088                                                _("Wrap all long lines"),
5089                                                "Linewrap",
5090                                                icon_wid,
5091                                                toolbar_linewrap_cb,
5092                                                compose);
5093
5094         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
5095
5096         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_ADDRESS_BOOK);
5097         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
5098                                                _("Address"),
5099                                                _("Address book"),
5100                                                "Address",
5101                                                icon_wid, toolbar_address_cb,
5102                                                compose);
5103
5104         compose->toolbar       = toolbar;
5105         compose->send_btn      = send_btn;
5106         compose->sendl_btn     = sendl_btn;
5107         compose->draft_btn     = draft_btn;
5108         compose->insert_btn    = insert_btn;
5109         compose->attach_btn    = attach_btn;
5110         compose->sig_btn       = sig_btn;
5111         compose->exteditor_btn = exteditor_btn;
5112         compose->linewrap_btn  = linewrap_btn;
5113         compose->addrbook_btn  = addrbook_btn;
5114
5115         gtk_widget_show_all(toolbar);
5116 }
5117
5118 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5119 {
5120         GList *accounts;
5121         GtkWidget *hbox;
5122         GtkWidget *optmenu;
5123         GtkWidget *menu;
5124         gint num = 0, def_menu = 0;
5125
5126         accounts = account_get_list();
5127         g_return_val_if_fail(accounts != NULL, NULL);
5128
5129         hbox = gtk_hbox_new(FALSE, 0);
5130         optmenu = gtk_option_menu_new();
5131         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5132         menu = gtk_menu_new();
5133
5134         for (; accounts != NULL; accounts = accounts->next, num++) {
5135                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5136                 GtkWidget *menuitem;
5137                 gchar *name;
5138
5139                 if (ac == compose->account) def_menu = num;
5140
5141                 if (ac->name)
5142                         name = g_strdup_printf("%s: %s <%s>",
5143                                                ac->account_name,
5144                                                ac->name, ac->address);
5145                 else
5146                         name = g_strdup_printf("%s: %s",
5147                                                ac->account_name, ac->address);
5148                 MENUITEM_ADD(menu, menuitem, name, ac);
5149                 g_free(name);
5150                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
5151                                    GTK_SIGNAL_FUNC(account_activated),
5152                                    compose);
5153         }
5154
5155         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5156         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5157
5158         return hbox;
5159 }
5160
5161 static void compose_set_priority_cb(gpointer data,
5162                                     guint action,
5163                                     GtkWidget *widget)
5164 {
5165         Compose *compose = (Compose *) data;
5166         compose->priority = action;
5167 }
5168
5169 static void compose_update_priority_menu_item(Compose * compose)
5170 {
5171         GtkItemFactory *ifactory;
5172         GtkWidget *menuitem = NULL;
5173
5174         ifactory = gtk_item_factory_from_widget(compose->menubar);
5175         
5176         switch (compose->priority) {
5177                 case PRIORITY_HIGHEST:
5178                         menuitem = gtk_item_factory_get_item
5179                                 (ifactory, "/Message/Priority/Highest");
5180                         break;
5181                 case PRIORITY_HIGH:
5182                         menuitem = gtk_item_factory_get_item
5183                                 (ifactory, "/Message/Priority/High");
5184                         break;
5185                 case PRIORITY_NORMAL:
5186                         menuitem = gtk_item_factory_get_item
5187                                 (ifactory, "/Message/Priority/Normal");
5188                         break;
5189                 case PRIORITY_LOW:
5190                         menuitem = gtk_item_factory_get_item
5191                                 (ifactory, "/Message/Priority/Low");
5192                         break;
5193                 case PRIORITY_LOWEST:
5194                         menuitem = gtk_item_factory_get_item
5195                                 (ifactory, "/Message/Priority/Lowest");
5196                         break;
5197         }
5198         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5199 }       
5200  
5201 static void compose_set_template_menu(Compose *compose)
5202 {
5203         GSList *tmpl_list, *cur;
5204         GtkWidget *menu;
5205         GtkWidget *item;
5206
5207         tmpl_list = template_get_config();
5208
5209         menu = gtk_menu_new();
5210
5211         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5212                 Template *tmpl = (Template *)cur->data;
5213
5214                 item = gtk_menu_item_new_with_label(tmpl->name);
5215                 gtk_menu_append(GTK_MENU(menu), item);
5216                 gtk_signal_connect(GTK_OBJECT(item), "activate",
5217                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
5218                                    compose);
5219                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
5220                 gtk_widget_show(item);
5221         }
5222
5223         gtk_widget_show(menu);
5224         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5225 }
5226
5227 void compose_reflect_prefs_all(void)
5228 {
5229         GList *cur;
5230         Compose *compose;
5231
5232         for (cur = compose_list; cur != NULL; cur = cur->next) {
5233                 compose = (Compose *)cur->data;
5234                 compose_set_template_menu(compose);
5235         }
5236 }
5237
5238 void compose_reflect_prefs_pixmap_theme(void)
5239 {
5240         GList *cur;
5241         Compose *compose;
5242
5243         for (cur = compose_list; cur != NULL; cur = cur->next) {
5244                 compose = (Compose *)cur->data;
5245                 gtk_container_remove(GTK_CONTAINER(compose->handlebox), GTK_WIDGET(compose->toolbar));
5246                 compose->toolbar = NULL;
5247                 compose_toolbar_create(compose, compose->handlebox);
5248                 set_toolbar_style(compose);
5249         }
5250 }
5251
5252 static void compose_template_apply(Compose *compose, Template *tmpl,
5253                                    gboolean replace)
5254 {
5255         gchar *qmark;
5256         gchar *parsed_str;
5257
5258         if (!tmpl || !tmpl->value) return;
5259
5260         gtk_stext_freeze(GTK_STEXT(compose->text));
5261
5262         if (tmpl->subject && *tmpl->subject != '\0')
5263                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
5264                                    tmpl->subject);
5265         if (tmpl->to && *tmpl->to != '\0')
5266                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
5267
5268         if (replace)
5269                 gtk_stext_clear(GTK_STEXT(compose->text));
5270
5271         if (compose->replyinfo == NULL) {
5272                 parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
5273                                                NULL, NULL);
5274         } else {
5275                 if (prefs_common.quotemark && *prefs_common.quotemark)
5276                         qmark = prefs_common.quotemark;
5277                 else
5278                         qmark = "> ";
5279
5280                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
5281                                                tmpl->value, qmark, NULL);
5282         }
5283
5284         if (replace && parsed_str && prefs_common.auto_sig)
5285                 compose_insert_sig(compose);
5286
5287         if (replace && parsed_str) {
5288                 gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
5289                 gtk_stext_set_point(GTK_STEXT(compose->text), 0);
5290         }
5291
5292         if (parsed_str)
5293                 compose_changed_cb(NULL, compose);
5294
5295         gtk_stext_thaw(GTK_STEXT(compose->text));
5296 }
5297
5298 static void compose_destroy(Compose *compose)
5299 {
5300         gint row;
5301         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5302         AttachInfo *ainfo;
5303
5304         /* NOTE: address_completion_end() does nothing with the window
5305          * however this may change. */
5306         address_completion_end(compose->window);
5307
5308         slist_free_strings(compose->to_list);
5309         g_slist_free(compose->to_list);
5310         slist_free_strings(compose->newsgroup_list);
5311         g_slist_free(compose->newsgroup_list);
5312         slist_free_strings(compose->header_list);
5313         g_slist_free(compose->header_list);
5314
5315         procmsg_msginfo_free(compose->targetinfo);
5316         procmsg_msginfo_free(compose->replyinfo);
5317
5318         g_free(compose->replyto);
5319         g_free(compose->cc);
5320         g_free(compose->bcc);
5321         g_free(compose->newsgroups);
5322         g_free(compose->followup_to);
5323
5324         g_free(compose->inreplyto);
5325         g_free(compose->references);
5326         g_free(compose->msgid);
5327         g_free(compose->boundary);
5328
5329         if (compose->redirect_filename)
5330                 g_free(compose->redirect_filename);
5331
5332         g_free(compose->exteditor_file);
5333
5334         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
5335              row++)
5336                 compose_attach_info_free(ainfo);
5337
5338         if (addressbook_get_target_compose() == compose)
5339                 addressbook_set_target_compose(NULL);
5340
5341 #if USE_ASPELL
5342         if (compose->gtkaspell) {
5343                 gtkaspell_delete(compose->gtkaspell);
5344         }
5345 #endif
5346
5347         prefs_common.compose_width = compose->scrolledwin->allocation.width;
5348         prefs_common.compose_height = compose->window->allocation.height;
5349
5350         gtk_widget_destroy(compose->paned);
5351
5352         g_free(compose);
5353
5354         compose_list = g_list_remove(compose_list, compose);
5355 }
5356
5357 static void compose_attach_info_free(AttachInfo *ainfo)
5358 {
5359         g_free(ainfo->file);
5360         g_free(ainfo->content_type);
5361         g_free(ainfo->name);
5362         g_free(ainfo);
5363 }
5364
5365 static void compose_attach_remove_selected(Compose *compose)
5366 {
5367         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5368         AttachInfo *ainfo;
5369         gint row;
5370
5371         while (clist->selection != NULL) {
5372                 row = GPOINTER_TO_INT(clist->selection->data);
5373                 ainfo = gtk_clist_get_row_data(clist, row);
5374                 compose_attach_info_free(ainfo);
5375                 gtk_clist_remove(clist, row);
5376         }
5377 }
5378
5379 static struct _AttachProperty
5380 {
5381         GtkWidget *window;
5382         GtkWidget *mimetype_entry;
5383         GtkWidget *encoding_optmenu;
5384         GtkWidget *path_entry;
5385         GtkWidget *filename_entry;
5386         GtkWidget *ok_btn;
5387         GtkWidget *cancel_btn;
5388 } attach_prop;
5389
5390 static void compose_attach_property(Compose *compose)
5391 {
5392         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5393         AttachInfo *ainfo;
5394         gint row;
5395         GtkOptionMenu *optmenu;
5396         static gboolean cancelled;
5397
5398         if (!clist->selection) return;
5399         row = GPOINTER_TO_INT(clist->selection->data);
5400
5401         ainfo = gtk_clist_get_row_data(clist, row);
5402         if (!ainfo) return;
5403
5404         if (!attach_prop.window)
5405                 compose_attach_property_create(&cancelled);
5406         gtk_widget_grab_focus(attach_prop.ok_btn);
5407         gtk_widget_show(attach_prop.window);
5408         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
5409
5410         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
5411         if (ainfo->encoding == ENC_UNKNOWN)
5412                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
5413         else
5414                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
5415
5416         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
5417                            ainfo->content_type ? ainfo->content_type : "");
5418         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
5419                            ainfo->file ? ainfo->file : "");
5420         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
5421                            ainfo->name ? ainfo->name : "");
5422
5423         for (;;) {
5424                 gchar *text;
5425                 gchar *cnttype = NULL;
5426                 gchar *file = NULL;
5427                 off_t size = 0;
5428                 GtkWidget *menu;
5429                 GtkWidget *menuitem;
5430
5431                 cancelled = FALSE;
5432                 gtk_main();
5433
5434                 if (cancelled == TRUE) {
5435                         gtk_widget_hide(attach_prop.window);
5436                         break;
5437                 }
5438
5439                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
5440                 if (*text != '\0') {
5441                         gchar *p;
5442
5443                         text = g_strstrip(g_strdup(text));
5444                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
5445                                 cnttype = g_strdup(text);
5446                                 g_free(text);
5447                         } else {
5448                                 alertpanel_error(_("Invalid MIME type."));
5449                                 g_free(text);
5450                                 continue;
5451                         }
5452                 }
5453
5454                 menu = gtk_option_menu_get_menu(optmenu);
5455                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
5456                 ainfo->encoding = GPOINTER_TO_INT
5457                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
5458
5459                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
5460                 if (*text != '\0') {
5461                         if (is_file_exist(text) &&
5462                             (size = get_file_size(text)) > 0)
5463                                 file = g_strdup(text);
5464                         else {
5465                                 alertpanel_error
5466                                         (_("File doesn't exist or is empty."));
5467                                 g_free(cnttype);
5468                                 continue;
5469                         }
5470                 }
5471
5472                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
5473                 if (*text != '\0') {
5474                         g_free(ainfo->name);
5475                         ainfo->name = g_strdup(text);
5476                 }
5477
5478                 if (cnttype) {
5479                         g_free(ainfo->content_type);
5480                         ainfo->content_type = cnttype;
5481                 }
5482                 if (file) {
5483                         g_free(ainfo->file);
5484                         ainfo->file = file;
5485                 }
5486                 if (size)
5487                         ainfo->size = size;
5488
5489                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5490                                    ainfo->content_type);
5491                 gtk_clist_set_text(clist, row, COL_SIZE,
5492                                    to_human_readable(ainfo->size));
5493                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5494
5495                 gtk_widget_hide(attach_prop.window);
5496                 break;
5497         }
5498 }
5499
5500 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5501 { \
5502         label = gtk_label_new(str); \
5503         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5504                          GTK_FILL, 0, 0, 0); \
5505         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5506  \
5507         entry = gtk_entry_new(); \
5508         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5509                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5510 }
5511
5512 static void compose_attach_property_create(gboolean *cancelled)
5513 {
5514         GtkWidget *window;
5515         GtkWidget *vbox;
5516         GtkWidget *table;
5517         GtkWidget *label;
5518         GtkWidget *mimetype_entry;
5519         GtkWidget *hbox;
5520         GtkWidget *optmenu;
5521         GtkWidget *optmenu_menu;
5522         GtkWidget *menuitem;
5523         GtkWidget *path_entry;
5524         GtkWidget *filename_entry;
5525         GtkWidget *hbbox;
5526         GtkWidget *ok_btn;
5527         GtkWidget *cancel_btn;
5528         GList     *mime_type_list, *strlist;
5529
5530         debug_print("Creating attach_property window...\n");
5531
5532         window = gtk_window_new(GTK_WINDOW_DIALOG);
5533         gtk_widget_set_usize(window, 480, -1);
5534         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5535         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
5536         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5537         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5538         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5539                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5540                            cancelled);
5541         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5542                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5543                            cancelled);
5544
5545         vbox = gtk_vbox_new(FALSE, 8);
5546         gtk_container_add(GTK_CONTAINER(window), vbox);
5547
5548         table = gtk_table_new(4, 2, FALSE);
5549         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5550         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5551         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5552
5553         label = gtk_label_new(_("MIME type")); 
5554         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5555                          GTK_FILL, 0, 0, 0); 
5556         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5557         mimetype_entry = gtk_combo_new(); 
5558         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5559                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5560                          
5561         /* stuff with list */
5562         mime_type_list = procmime_get_mime_type_list();
5563         strlist = NULL;
5564         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5565                 MimeType *type = (MimeType *) mime_type_list->data;
5566                 strlist = g_list_append(strlist, 
5567                                 g_strdup_printf("%s/%s",
5568                                         type->type, type->sub_type));
5569         }
5570         
5571         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5572
5573         for (mime_type_list = strlist; mime_type_list != NULL; 
5574                 mime_type_list = mime_type_list->next)
5575                 g_free(mime_type_list->data);
5576         g_list_free(strlist);
5577                          
5578         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5579
5580         label = gtk_label_new(_("Encoding"));
5581         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5582                          GTK_FILL, 0, 0, 0);
5583         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5584
5585         hbox = gtk_hbox_new(FALSE, 0);
5586         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5587                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5588
5589         optmenu = gtk_option_menu_new();
5590         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
5591
5592         optmenu_menu = gtk_menu_new();
5593         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5594         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5595 #if 0
5596         gtk_widget_set_sensitive(menuitem, FALSE);
5597 #endif
5598         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
5599         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5600 #if 0
5601         gtk_widget_set_sensitive(menuitem, FALSE);
5602 #endif
5603         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
5604         gtk_widget_set_sensitive(menuitem, FALSE);
5605         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5606
5607         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5608
5609         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5610         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5611
5612         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5613                                 &cancel_btn, _("Cancel"), NULL, NULL);
5614         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5615         gtk_widget_grab_default(ok_btn);
5616
5617         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5618                            GTK_SIGNAL_FUNC(attach_property_ok),
5619                            cancelled);
5620         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5621                            GTK_SIGNAL_FUNC(attach_property_cancel),
5622                            cancelled);
5623
5624         gtk_widget_show_all(vbox);
5625
5626         attach_prop.window           = window;
5627         attach_prop.mimetype_entry   = mimetype_entry;
5628         attach_prop.encoding_optmenu = optmenu;
5629         attach_prop.path_entry       = path_entry;
5630         attach_prop.filename_entry   = filename_entry;
5631         attach_prop.ok_btn           = ok_btn;
5632         attach_prop.cancel_btn       = cancel_btn;
5633 }
5634
5635 #undef SET_LABEL_AND_ENTRY
5636
5637 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5638 {
5639         *cancelled = FALSE;
5640         gtk_main_quit();
5641 }
5642
5643 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5644 {
5645         *cancelled = TRUE;
5646         gtk_main_quit();
5647 }
5648
5649 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5650                                          gboolean *cancelled)
5651 {
5652         *cancelled = TRUE;
5653         gtk_main_quit();
5654
5655         return TRUE;
5656 }
5657
5658 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5659                                         gboolean *cancelled)
5660 {
5661         if (event && event->keyval == GDK_Escape) {
5662                 *cancelled = TRUE;
5663                 gtk_main_quit();
5664         }
5665 }
5666
5667 static void compose_exec_ext_editor(Compose *compose)
5668 {
5669         gchar *tmp;
5670         pid_t pid;
5671         gint pipe_fds[2];
5672
5673         tmp = g_strdup_printf("%s%ctmpmsg.%08x", get_tmp_dir(),
5674                               G_DIR_SEPARATOR, (gint)compose);
5675
5676         if (pipe(pipe_fds) < 0) {
5677                 perror("pipe");
5678                 g_free(tmp);
5679                 return;
5680         }
5681
5682         if ((pid = fork()) < 0) {
5683                 perror("fork");
5684                 g_free(tmp);
5685                 return;
5686         }
5687
5688         if (pid != 0) {
5689                 /* close the write side of the pipe */
5690                 close(pipe_fds[1]);
5691
5692                 compose->exteditor_file    = g_strdup(tmp);
5693                 compose->exteditor_pid     = pid;
5694                 compose->exteditor_readdes = pipe_fds[0];
5695
5696                 compose_set_ext_editor_sensitive(compose, FALSE);
5697
5698                 compose->exteditor_tag =
5699                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5700                                       compose_input_cb, compose);
5701         } else {        /* process-monitoring process */
5702                 pid_t pid_ed;
5703
5704                 if (setpgid(0, 0))
5705                         perror("setpgid");
5706
5707                 /* close the read side of the pipe */
5708                 close(pipe_fds[0]);
5709
5710                 if (compose_write_body_to_file(compose, tmp) < 0) {
5711                         fd_write(pipe_fds[1], "2\n", 2);
5712                         _exit(1);
5713                 }
5714
5715                 pid_ed = compose_exec_ext_editor_real(tmp);
5716                 if (pid_ed < 0) {
5717                         fd_write(pipe_fds[1], "1\n", 2);
5718                         _exit(1);
5719                 }
5720
5721                 /* wait until editor is terminated */
5722                 waitpid(pid_ed, NULL, 0);
5723
5724                 fd_write(pipe_fds[1], "0\n", 2);
5725
5726                 close(pipe_fds[1]);
5727                 _exit(0);
5728         }
5729
5730         g_free(tmp);
5731 }
5732
5733 static gint compose_exec_ext_editor_real(const gchar *file)
5734 {
5735         static gchar *def_cmd = "emacs %s";
5736         gchar buf[1024];
5737         gchar *p;
5738         gchar **cmdline;
5739         pid_t pid;
5740
5741         g_return_val_if_fail(file != NULL, -1);
5742
5743         if ((pid = fork()) < 0) {
5744                 perror("fork");
5745                 return -1;
5746         }
5747
5748         if (pid != 0) return pid;
5749
5750         /* grandchild process */
5751
5752         if (setpgid(0, getppid()))
5753                 perror("setpgid");
5754
5755         if (prefs_common.ext_editor_cmd &&
5756             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5757             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5758                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5759         } else {
5760                 if (prefs_common.ext_editor_cmd)
5761                         g_warning(_("External editor command line is invalid: `%s'\n"),
5762                                   prefs_common.ext_editor_cmd);
5763                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5764         }
5765
5766         cmdline = strsplit_with_quote(buf, " ", 1024);
5767         execvp(cmdline[0], cmdline);
5768
5769         perror("execvp");
5770         g_strfreev(cmdline);
5771
5772         _exit(1);
5773 }
5774
5775 static gboolean compose_ext_editor_kill(Compose *compose)
5776 {
5777         pid_t pgid = compose->exteditor_pid * -1;
5778         gint ret;
5779
5780         ret = kill(pgid, 0);
5781
5782         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5783                 AlertValue val;
5784                 gchar *msg;
5785
5786                 msg = g_strdup_printf
5787                         (_("The external editor is still working.\n"
5788                            "Force terminating the process?\n"
5789                            "process group id: %d"), -pgid);
5790                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5791                 g_free(msg);
5792
5793                 if (val == G_ALERTDEFAULT) {
5794                         gdk_input_remove(compose->exteditor_tag);
5795                         close(compose->exteditor_readdes);
5796
5797                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5798                         waitpid(compose->exteditor_pid, NULL, 0);
5799
5800                         g_warning(_("Terminated process group id: %d"), -pgid);
5801                         g_warning(_("Temporary file: %s"),
5802                                   compose->exteditor_file);
5803
5804                         compose_set_ext_editor_sensitive(compose, TRUE);
5805
5806                         g_free(compose->exteditor_file);
5807                         compose->exteditor_file    = NULL;
5808                         compose->exteditor_pid     = -1;
5809                         compose->exteditor_readdes = -1;
5810                         compose->exteditor_tag     = -1;
5811                 } else
5812                         return FALSE;
5813         }
5814
5815         return TRUE;
5816 }
5817
5818 static void compose_input_cb(gpointer data, gint source,
5819                              GdkInputCondition condition)
5820 {
5821         gchar buf[3];
5822         Compose *compose = (Compose *)data;
5823         gint i = 0;
5824
5825         debug_print("Compose: input from monitoring process\n");
5826
5827         gdk_input_remove(compose->exteditor_tag);
5828
5829         for (;;) {
5830                 if (read(source, &buf[i], 1) < 1) {
5831                         buf[0] = '3';
5832                         break;
5833                 }
5834                 if (buf[i] == '\n') {
5835                         buf[i] = '\0';
5836                         break;
5837                 }
5838                 i++;
5839                 if (i == sizeof(buf) - 1)
5840                         break;
5841         }
5842
5843         waitpid(compose->exteditor_pid, NULL, 0);
5844
5845         if (buf[0] == '0') {            /* success */
5846                 GtkSText *text = GTK_STEXT(compose->text);
5847
5848                 gtk_stext_freeze(text);
5849                 gtk_stext_set_point(text, 0);
5850                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5851                 compose_insert_file(compose, compose->exteditor_file);
5852                 compose_changed_cb(NULL, compose);
5853                 gtk_stext_thaw(text);
5854
5855                 if (unlink(compose->exteditor_file) < 0)
5856                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5857         } else if (buf[0] == '1') {     /* failed */
5858                 g_warning(_("Couldn't exec external editor\n"));
5859                 if (unlink(compose->exteditor_file) < 0)
5860                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5861         } else if (buf[0] == '2') {
5862                 g_warning(_("Couldn't write to file\n"));
5863         } else if (buf[0] == '3') {
5864                 g_warning(_("Pipe read failed\n"));
5865         }
5866
5867         close(source);
5868
5869         compose_set_ext_editor_sensitive(compose, TRUE);
5870
5871         g_free(compose->exteditor_file);
5872         compose->exteditor_file    = NULL;
5873         compose->exteditor_pid     = -1;
5874         compose->exteditor_readdes = -1;
5875         compose->exteditor_tag     = -1;
5876 }
5877
5878 static void compose_set_ext_editor_sensitive(Compose *compose,
5879                                              gboolean sensitive)
5880 {
5881         GtkItemFactory *ifactory;
5882
5883         ifactory = gtk_item_factory_from_widget(compose->menubar);
5884
5885         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5886         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5887         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
5888                            sensitive);
5889         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
5890         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
5891         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
5892         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
5893         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
5894                            sensitive);
5895
5896         gtk_widget_set_sensitive(compose->text,          sensitive);
5897         gtk_widget_set_sensitive(compose->send_btn,      sensitive);
5898         gtk_widget_set_sensitive(compose->sendl_btn,     sensitive);
5899         gtk_widget_set_sensitive(compose->draft_btn,     sensitive);
5900         gtk_widget_set_sensitive(compose->insert_btn,    sensitive);
5901         gtk_widget_set_sensitive(compose->sig_btn,       sensitive);
5902         gtk_widget_set_sensitive(compose->exteditor_btn, sensitive);
5903         gtk_widget_set_sensitive(compose->linewrap_btn,  sensitive);
5904 }
5905
5906 /**
5907  * compose_undo_state_changed:
5908  *
5909  * Change the sensivity of the menuentries undo and redo
5910  **/
5911 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
5912                                        gint redo_state, gpointer data)
5913 {
5914         GtkWidget *widget = GTK_WIDGET(data);
5915         GtkItemFactory *ifactory;
5916
5917         g_return_if_fail(widget != NULL);
5918
5919         debug_print("Set_undo.  UNDO:%i  REDO:%i\n", undo_state, redo_state);
5920
5921         ifactory = gtk_item_factory_from_widget(widget);
5922
5923         switch (undo_state) {
5924         case UNDO_STATE_TRUE:
5925                 if (!undostruct->undo_state) {
5926                         debug_print ("Set_undo - Testpoint\n");
5927                         undostruct->undo_state = TRUE;
5928                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
5929                 }
5930                 break;
5931         case UNDO_STATE_FALSE:
5932                 if (undostruct->undo_state) {
5933                         undostruct->undo_state = FALSE;
5934                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5935                 }
5936                 break;
5937         case UNDO_STATE_UNCHANGED:
5938                 break;
5939         case UNDO_STATE_REFRESH:
5940                 menu_set_sensitive(ifactory, "/Edit/Undo",
5941                                    undostruct->undo_state);
5942                 break;
5943         default:
5944                 g_warning("Undo state not recognized");
5945                 break;
5946         }
5947
5948         switch (redo_state) {
5949         case UNDO_STATE_TRUE:
5950                 if (!undostruct->redo_state) {
5951                         undostruct->redo_state = TRUE;
5952                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
5953                 }
5954                 break;
5955         case UNDO_STATE_FALSE:
5956                 if (undostruct->redo_state) {
5957                         undostruct->redo_state = FALSE;
5958                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5959                 }
5960                 break;
5961         case UNDO_STATE_UNCHANGED:
5962                 break;
5963         case UNDO_STATE_REFRESH:
5964                 menu_set_sensitive(ifactory, "/Edit/Redo",
5965                                    undostruct->redo_state);
5966                 break;
5967         default:
5968                 g_warning("Redo state not recognized");
5969                 break;
5970         }
5971 }
5972
5973 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
5974 {
5975         gint cursor_pos;
5976
5977         cursor_pos = (text->cursor_pos_x - extra) / char_width;
5978         cursor_pos = MAX(cursor_pos, 0);
5979
5980         return cursor_pos;
5981 }
5982
5983 /* callback functions */
5984
5985 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
5986  * includes "non-client" (windows-izm) in calculation, so this calculation
5987  * may not be accurate.
5988  */
5989 static gboolean compose_edit_size_alloc(GtkEditable *widget,
5990                                         GtkAllocation *allocation,
5991                                         GtkSHRuler *shruler)
5992 {
5993         if (prefs_common.show_ruler) {
5994                 gint char_width;
5995                 gint line_width_in_chars;
5996
5997                 char_width = gtkut_get_font_width
5998                         (GTK_WIDGET(widget)->style->font);
5999                 line_width_in_chars =
6000                         (allocation->width - allocation->x) / char_width;
6001
6002                 /* got the maximum */
6003                 gtk_ruler_set_range(GTK_RULER(shruler),
6004                                     0.0, line_width_in_chars,
6005                                     calc_cursor_xpos(GTK_STEXT(widget),
6006                                                      allocation->x,
6007                                                      char_width),
6008                                     /*line_width_in_chars*/ char_width);
6009         }
6010
6011         return TRUE;
6012 }
6013
6014 static void toolbar_send_cb(GtkWidget *widget, gpointer data)
6015 {
6016         compose_send_cb(data, 0, NULL);
6017 }
6018
6019 static void toolbar_send_later_cb(GtkWidget *widget, gpointer data)
6020 {
6021         compose_send_later_cb(data, 0, NULL);
6022 }
6023
6024 static void toolbar_draft_cb(GtkWidget *widget, gpointer data)
6025 {
6026         compose_draft_cb(data, 0, NULL);
6027 }
6028
6029 static void toolbar_insert_cb(GtkWidget *widget, gpointer data)
6030 {
6031         compose_insert_file_cb(data, 0, NULL);
6032 }
6033
6034 static void toolbar_attach_cb(GtkWidget *widget, gpointer data)
6035 {
6036         compose_attach_cb(data, 0, NULL);
6037 }
6038
6039 static void toolbar_sig_cb(GtkWidget *widget, gpointer data)
6040 {
6041         Compose *compose = (Compose *)data;
6042
6043         compose_insert_sig(compose);
6044 }
6045
6046 static void toolbar_ext_editor_cb(GtkWidget *widget, gpointer data)
6047 {
6048         Compose *compose = (Compose *)data;
6049
6050         compose_exec_ext_editor(compose);
6051 }
6052
6053 static void toolbar_linewrap_cb(GtkWidget *widget, gpointer data)
6054 {
6055         Compose *compose = (Compose *)data;
6056
6057         compose_wrap_line(compose);
6058 }
6059
6060 static void toolbar_address_cb(GtkWidget *widget, gpointer data)
6061 {
6062         compose_address_cb(data, 0, NULL);
6063 }
6064
6065 static void account_activated(GtkMenuItem *menuitem, gpointer data)
6066 {
6067         Compose *compose = (Compose *)data;
6068
6069         PrefsAccount *ac;
6070
6071         ac = (PrefsAccount *)gtk_object_get_user_data(GTK_OBJECT(menuitem));
6072         g_return_if_fail(ac != NULL);
6073
6074         if (ac != compose->account)
6075                 compose_select_account(compose, ac);
6076 }
6077
6078 static void attach_selected(GtkCList *clist, gint row, gint column,
6079                             GdkEvent *event, gpointer data)
6080 {
6081         Compose *compose = (Compose *)data;
6082
6083         if (event && event->type == GDK_2BUTTON_PRESS)
6084                 compose_attach_property(compose);
6085 }
6086
6087 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
6088                                   gpointer data)
6089 {
6090         Compose *compose = (Compose *)data;
6091         GtkCList *clist = GTK_CLIST(compose->attach_clist);
6092         gint row, column;
6093
6094         if (!event) return;
6095
6096         if (event->button == 3) {
6097                 if ((clist->selection && !clist->selection->next) ||
6098                     !clist->selection) {
6099                         gtk_clist_unselect_all(clist);
6100                         if (gtk_clist_get_selection_info(clist,
6101                                                          event->x, event->y,
6102                                                          &row, &column)) {
6103                                 gtk_clist_select_row(clist, row, column);
6104                                 gtkut_clist_set_focus_row(clist, row);
6105                         }
6106                 }
6107                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6108                                NULL, NULL, event->button, event->time);
6109         }
6110 }
6111
6112 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6113                                gpointer data)
6114 {
6115         Compose *compose = (Compose *)data;
6116
6117         if (!event) return;
6118
6119         switch (event->keyval) {
6120         case GDK_Delete:
6121                 compose_attach_remove_selected(compose);
6122                 break;
6123         }
6124 }
6125
6126 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
6127 {
6128         Compose *compose = (Compose *)data;
6129         gint val;
6130         
6131         if (prefs_common.work_offline)
6132                 if (alertpanel(_("Offline warning"), 
6133                                _("You're working offline. Override?"),
6134                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
6135                 return;
6136
6137         val = compose_send(compose);
6138
6139         if (val == 0) gtk_widget_destroy(compose->window);
6140 }
6141
6142 static void compose_send_later_cb(gpointer data, guint action,
6143                                   GtkWidget *widget)
6144 {
6145         Compose *compose = (Compose *)data;
6146         gint val;
6147
6148         val = compose_queue_sub(compose, NULL, NULL, TRUE);
6149         if (!val) gtk_widget_destroy(compose->window);
6150 }
6151
6152 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
6153 {
6154         Compose *compose = (Compose *)data;
6155         FolderItem *draft;
6156         gchar *tmp;
6157         gint msgnum;
6158         static gboolean lock = FALSE;
6159         MsgInfo *newmsginfo;
6160         
6161         if (lock) return;
6162
6163         draft = account_get_special_folder(compose->account, F_DRAFT);
6164         g_return_if_fail(draft != NULL);
6165
6166         lock = TRUE;
6167
6168         tmp = g_strdup_printf("%s%cdraft.%08x", get_tmp_dir(),
6169                               G_DIR_SEPARATOR, (gint)compose);
6170
6171         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
6172                 g_free(tmp);
6173                 lock = FALSE;
6174                 return;
6175         }
6176
6177         if ((msgnum = folder_item_add_msg(draft, tmp, TRUE)) < 0) {
6178                 unlink(tmp);
6179                 g_free(tmp);
6180                 lock = FALSE;
6181                 return;
6182         }
6183         g_free(tmp);
6184         draft->mtime = 0;       /* force updating */
6185
6186         if (compose->mode == COMPOSE_REEDIT) {
6187                 compose_remove_reedit_target(compose);
6188                 if (compose->targetinfo &&
6189                     compose->targetinfo->folder != draft)
6190                         folderview_update_item(compose->targetinfo->folder,
6191                                                TRUE);
6192         }
6193
6194         newmsginfo = folder_item_fetch_msginfo(draft, msgnum);
6195         procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
6196         MSG_SET_TMP_FLAGS(newmsginfo->flags, MSG_DRAFT);
6197         folderview_update_item(draft, TRUE);
6198         procmsg_msginfo_free(newmsginfo);
6199         
6200         lock = FALSE;
6201
6202         /* 0: quit editing  1: keep editing */
6203         if (action == 0)
6204                 gtk_widget_destroy(compose->window);
6205         else {
6206                 struct stat s;
6207                 gchar *path;
6208
6209                 path = folder_item_fetch_msg(draft, msgnum);
6210                 g_return_if_fail(path != NULL);
6211                 if (stat(path, &s) < 0) {
6212                         FILE_OP_ERROR(path, "stat");
6213                         g_free(path);
6214                         lock = FALSE;
6215                         return;
6216                 }
6217                 g_free(path);
6218
6219                 procmsg_msginfo_free(compose->targetinfo);
6220                 compose->targetinfo = procmsg_msginfo_new();
6221                 compose->targetinfo->msgnum = msgnum;
6222                 compose->targetinfo->size = s.st_size;
6223                 compose->targetinfo->mtime = s.st_mtime;
6224                 compose->targetinfo->folder = draft;
6225                 compose->mode = COMPOSE_REEDIT;
6226         }
6227 }
6228
6229 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
6230 {
6231         Compose *compose = (Compose *)data;
6232         GList *file_list;
6233
6234         if (compose->redirect_filename != NULL)
6235                 return;
6236
6237         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6238
6239         if (file_list) {
6240                 GList *tmp;
6241
6242                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6243                         gchar *file = (gchar *) tmp->data;
6244                         compose_attach_append(compose, file, file, NULL);
6245                         compose_changed_cb(NULL, compose);
6246                         g_free(file);
6247                 }
6248                 g_list_free(file_list);
6249         }               
6250 }
6251
6252 static void compose_insert_file_cb(gpointer data, guint action,
6253                                    GtkWidget *widget)
6254 {
6255         Compose *compose = (Compose *)data;
6256         GList *file_list;
6257
6258         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6259
6260         if (file_list) {
6261                 GList *tmp;
6262
6263                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6264                         gchar *file = (gchar *) tmp->data;
6265                         compose_insert_file(compose, file);
6266                         g_free(file);
6267                 }
6268                 g_list_free(file_list);
6269         }
6270 }
6271
6272 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
6273                               gpointer data)
6274 {
6275         compose_close_cb(data, 0, NULL);
6276         return TRUE;
6277 }
6278
6279 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
6280 {
6281         Compose *compose = (Compose *)data;
6282         AlertValue val;
6283         
6284         if (compose->exteditor_tag != -1) {
6285                 if (!compose_ext_editor_kill(compose))
6286                         return;
6287         }
6288
6289         if (compose->modified) {
6290                 val = alertpanel(_("Discard message"),
6291                                  _("This message has been modified. discard it?"),
6292                                  _("Discard"), _("to Draft"), _("Cancel"));
6293
6294                 switch (val) {
6295                 case G_ALERTDEFAULT:
6296                         if (prefs_common.autosave)
6297                                 compose_remove_draft(compose);                  
6298                         break;
6299                 case G_ALERTALTERNATE:
6300                         compose_draft_cb(data, 0, NULL);
6301                         return;
6302                 default:
6303                         return;
6304                 }
6305         }
6306
6307         gtk_widget_destroy(compose->window);
6308 }
6309
6310 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
6311 {
6312         Compose *compose = (Compose *)data;
6313
6314         addressbook_open(compose);
6315 }
6316
6317 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
6318 {
6319         Compose *compose = (Compose *)data;
6320         Template *tmpl;
6321         gchar *msg;
6322         AlertValue val;
6323
6324         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
6325         g_return_if_fail(tmpl != NULL);
6326
6327         msg = g_strdup_printf(_("Do you want to apply the template `%s' ?"),
6328                               tmpl->name);
6329         val = alertpanel(_("Apply template"), msg,
6330                          _("Replace"), _("Insert"), _("Cancel"));
6331         g_free(msg);
6332
6333         if (val == G_ALERTDEFAULT)
6334                 compose_template_apply(compose, tmpl, TRUE);
6335         else if (val == G_ALERTALTERNATE)
6336                 compose_template_apply(compose, tmpl, FALSE);
6337 }
6338
6339 static void compose_ext_editor_cb(gpointer data, guint action,
6340                                   GtkWidget *widget)
6341 {
6342         Compose *compose = (Compose *)data;
6343
6344         compose_exec_ext_editor(compose);
6345 }
6346
6347 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
6348 {
6349         compose_destroy(compose);
6350 }
6351
6352 static void compose_undo_cb(Compose *compose)
6353 {
6354         undo_undo(compose->undostruct);
6355 }
6356
6357 static void compose_redo_cb(Compose *compose)
6358 {
6359         undo_redo(compose->undostruct);
6360 }
6361
6362 static void compose_cut_cb(Compose *compose)
6363 {
6364         if (compose->focused_editable &&
6365             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6366                 gtk_editable_cut_clipboard
6367                         (GTK_EDITABLE(compose->focused_editable));
6368 }
6369
6370 static void compose_copy_cb(Compose *compose)
6371 {
6372         if (compose->focused_editable &&
6373             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6374                 gtk_editable_copy_clipboard
6375                         (GTK_EDITABLE(compose->focused_editable));
6376 }
6377
6378 static void compose_paste_cb(Compose *compose)
6379 {
6380         if (compose->focused_editable &&
6381             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6382                 gtk_editable_paste_clipboard
6383                         (GTK_EDITABLE(compose->focused_editable));
6384 }
6385
6386 static void compose_paste_as_quote_cb(Compose *compose)
6387 {
6388         if (compose->focused_editable &&
6389             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
6390                 compose->paste_as_quotation = TRUE;
6391                 gtk_editable_paste_clipboard
6392                         (GTK_EDITABLE(compose->focused_editable));
6393                 compose->paste_as_quotation = FALSE;
6394         }
6395 }
6396
6397 static void compose_allsel_cb(Compose *compose)
6398 {
6399         if (compose->focused_editable &&
6400             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6401                 gtk_editable_select_region
6402                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
6403 }
6404
6405 static void compose_gtk_stext_action_cb(Compose *compose,
6406                                         ComposeCallGtkSTextAction action)
6407 {
6408         GtkSText *text = GTK_STEXT(compose->text);
6409         static struct {
6410                 void (*do_action) (GtkSText *text);
6411         } action_table[] = {
6412                 {gtk_stext_move_beginning_of_line},
6413                 {gtk_stext_move_forward_character},
6414                 {gtk_stext_move_backward_character},
6415                 {gtk_stext_move_forward_word},
6416                 {gtk_stext_move_backward_word},
6417                 {gtk_stext_move_end_of_line},
6418                 {gtk_stext_move_next_line},
6419                 {gtk_stext_move_previous_line},
6420                 {gtk_stext_delete_forward_character},
6421                 {gtk_stext_delete_backward_character},
6422                 {gtk_stext_delete_forward_word},
6423                 {gtk_stext_delete_backward_word},
6424                 {gtk_stext_delete_line},
6425                 {gtk_stext_delete_line}, /* gtk_stext_delete_line_n */
6426                 {gtk_stext_delete_to_line_end}
6427         };
6428
6429         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
6430
6431         if (action >= COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE &&
6432             action <= COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END)
6433                 action_table[action].do_action(text);
6434 }
6435
6436 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
6437 {
6438         if (GTK_IS_EDITABLE(widget))
6439                 compose->focused_editable = widget;
6440 }
6441
6442 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
6443 {
6444         if (compose->modified == FALSE) {
6445                 compose->modified = TRUE;
6446                 compose_set_title(compose);
6447         }
6448 }
6449
6450 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
6451                                     Compose *compose)
6452 {
6453         gtk_stext_set_point(GTK_STEXT(widget),
6454                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6455 }
6456
6457 #if 0
6458 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
6459                                  Compose *compose)
6460 {
6461         gtk_stext_set_point(GTK_STEXT(widget),
6462                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6463 }
6464 #endif
6465
6466 #if 0 /* NEW COMPOSE GUI */
6467 static void compose_toggle_to_cb(gpointer data, guint action,
6468                                  GtkWidget *widget)
6469 {
6470         Compose *compose = (Compose *)data;
6471
6472         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6473                 gtk_widget_show(compose->to_hbox);
6474                 gtk_widget_show(compose->to_entry);
6475                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
6476                 compose->use_to = TRUE;
6477         } else {
6478                 gtk_widget_hide(compose->to_hbox);
6479                 gtk_widget_hide(compose->to_entry);
6480                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
6481                 gtk_widget_queue_resize(compose->table_vbox);
6482                 compose->use_to = FALSE;
6483         }
6484
6485         if (addressbook_get_target_compose() == compose)
6486                 addressbook_set_target_compose(compose);
6487 }
6488
6489 static void compose_toggle_cc_cb(gpointer data, guint action,
6490                                  GtkWidget *widget)
6491 {
6492         Compose *compose = (Compose *)data;
6493
6494         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6495                 gtk_widget_show(compose->cc_hbox);
6496                 gtk_widget_show(compose->cc_entry);
6497                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
6498                 compose->use_cc = TRUE;
6499         } else {
6500                 gtk_widget_hide(compose->cc_hbox);
6501                 gtk_widget_hide(compose->cc_entry);
6502                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
6503                 gtk_widget_queue_resize(compose->table_vbox);
6504                 compose->use_cc = FALSE;
6505         }
6506
6507         if (addressbook_get_target_compose() == compose)
6508                 addressbook_set_target_compose(compose);
6509 }
6510
6511 static void compose_toggle_bcc_cb(gpointer data, guint action,
6512                                   GtkWidget *widget)
6513 {
6514         Compose *compose = (Compose *)data;
6515
6516         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6517                 gtk_widget_show(compose->bcc_hbox);
6518                 gtk_widget_show(compose->bcc_entry);
6519                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
6520                 compose->use_bcc = TRUE;
6521         } else {
6522                 gtk_widget_hide(compose->bcc_hbox);
6523                 gtk_widget_hide(compose->bcc_entry);
6524                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
6525                 gtk_widget_queue_resize(compose->table_vbox);
6526                 compose->use_bcc = FALSE;
6527         }
6528
6529         if (addressbook_get_target_compose() == compose)
6530                 addressbook_set_target_compose(compose);
6531 }
6532
6533 static void compose_toggle_replyto_cb(gpointer data, guint action,
6534                                       GtkWidget *widget)
6535 {
6536         Compose *compose = (Compose *)data;
6537
6538         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6539                 gtk_widget_show(compose->reply_hbox);
6540                 gtk_widget_show(compose->reply_entry);
6541                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
6542                 compose->use_replyto = TRUE;
6543         } else {
6544                 gtk_widget_hide(compose->reply_hbox);
6545                 gtk_widget_hide(compose->reply_entry);
6546                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
6547                 gtk_widget_queue_resize(compose->table_vbox);
6548                 compose->use_replyto = FALSE;
6549         }
6550 }
6551
6552 static void compose_toggle_followupto_cb(gpointer data, guint action,
6553                                          GtkWidget *widget)
6554 {
6555         Compose *compose = (Compose *)data;
6556
6557         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6558                 gtk_widget_show(compose->followup_hbox);
6559                 gtk_widget_show(compose->followup_entry);
6560                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
6561                 compose->use_followupto = TRUE;
6562         } else {
6563                 gtk_widget_hide(compose->followup_hbox);
6564                 gtk_widget_hide(compose->followup_entry);
6565                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
6566                 gtk_widget_queue_resize(compose->table_vbox);
6567                 compose->use_followupto = FALSE;
6568         }
6569 }
6570
6571 static void compose_toggle_attach_cb(gpointer data, guint action,
6572                                      GtkWidget *widget)
6573 {
6574         Compose *compose = (Compose *)data;
6575
6576         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6577                 gtk_widget_ref(compose->edit_vbox);
6578
6579                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6580                                        compose->edit_vbox);
6581                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
6582                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
6583                                    TRUE, TRUE, 0);
6584                 gtk_widget_show(compose->paned);
6585
6586                 gtk_widget_unref(compose->edit_vbox);
6587                 gtk_widget_unref(compose->paned);
6588
6589                 compose->use_attach = TRUE;
6590         } else {
6591                 gtk_widget_ref(compose->paned);
6592                 gtk_widget_ref(compose->edit_vbox);
6593
6594                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6595                                        compose->paned);
6596                 gtkut_container_remove(GTK_CONTAINER(compose->paned),
6597                                        compose->edit_vbox);
6598                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
6599                                    compose->edit_vbox, TRUE, TRUE, 0);
6600
6601                 gtk_widget_unref(compose->edit_vbox);
6602
6603                 compose->use_attach = FALSE;
6604         }
6605 }
6606 #endif
6607
6608 #if USE_GPGME
6609 static void compose_toggle_sign_cb(gpointer data, guint action,
6610                                    GtkWidget *widget)
6611 {
6612         Compose *compose = (Compose *)data;
6613
6614         if (GTK_CHECK_MENU_ITEM(widget)->active)
6615                 compose->use_signing = TRUE;
6616         else
6617                 compose->use_signing = FALSE;
6618 }
6619
6620 static void compose_toggle_encrypt_cb(gpointer data, guint action,
6621                                       GtkWidget *widget)
6622 {
6623         Compose *compose = (Compose *)data;
6624
6625         if (GTK_CHECK_MENU_ITEM(widget)->active)
6626                 compose->use_encryption = TRUE;
6627         else
6628                 compose->use_encryption = FALSE;
6629 }
6630 #endif /* USE_GPGME */
6631
6632 static void compose_toggle_ruler_cb(gpointer data, guint action,
6633                                     GtkWidget *widget)
6634 {
6635         Compose *compose = (Compose *)data;
6636
6637         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6638                 gtk_widget_show(compose->ruler_hbox);
6639                 prefs_common.show_ruler = TRUE;
6640         } else {
6641                 gtk_widget_hide(compose->ruler_hbox);
6642                 gtk_widget_queue_resize(compose->edit_vbox);
6643                 prefs_common.show_ruler = FALSE;
6644         }
6645 }
6646
6647 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6648                                              GdkDragContext     *drag_context,
6649                                              gint                x,
6650                                              gint                y,
6651                                              GtkSelectionData   *data,
6652                                              guint               info,
6653                                              guint               time,
6654                                              gpointer            user_data)
6655 {
6656         Compose *compose = (Compose *)user_data;
6657         GList *list, *tmp;
6658
6659         list = uri_list_extract_filenames((const gchar *)data->data);
6660         for (tmp = list; tmp != NULL; tmp = tmp->next)
6661                 compose_attach_append
6662                         (compose, (const gchar *)tmp->data,
6663                          (const gchar *)tmp->data, NULL);
6664         if (list) compose_changed_cb(NULL, compose);
6665         list_free_strings(list);
6666         g_list_free(list);
6667 }
6668
6669 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6670                                              GdkDragContext     *drag_context,
6671                                              gint                x,
6672                                              gint                y,
6673                                              GtkSelectionData   *data,
6674                                              guint               info,
6675                                              guint               time,
6676                                              gpointer            user_data)
6677 {
6678         Compose *compose = (Compose *)user_data;
6679         GList *list, *tmp;
6680
6681         list = uri_list_extract_filenames((const gchar *)data->data);
6682         for (tmp = list; tmp != NULL; tmp = tmp->next)
6683                 compose_insert_file(compose, (const gchar *)tmp->data);
6684         list_free_strings(list);
6685         g_list_free(list);
6686 }
6687
6688 #if 0 /* NEW COMPOSE GUI */
6689 static void to_activated(GtkWidget *widget, Compose *compose)
6690 {
6691         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6692                 gtk_widget_grab_focus(compose->newsgroups_entry);
6693         else
6694                 gtk_widget_grab_focus(compose->subject_entry);
6695 }
6696
6697 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6698 {
6699         gtk_widget_grab_focus(compose->subject_entry);
6700 }
6701
6702 static void subject_activated(GtkWidget *widget, Compose *compose)
6703 {
6704         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6705                 gtk_widget_grab_focus(compose->cc_entry);
6706         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6707                 gtk_widget_grab_focus(compose->bcc_entry);
6708         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6709                 gtk_widget_grab_focus(compose->reply_entry);
6710         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6711                 gtk_widget_grab_focus(compose->followup_entry);
6712         else
6713                 gtk_widget_grab_focus(compose->text);
6714 }
6715
6716 static void cc_activated(GtkWidget *widget, Compose *compose)
6717 {
6718         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6719                 gtk_widget_grab_focus(compose->bcc_entry);
6720         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6721                 gtk_widget_grab_focus(compose->reply_entry);
6722         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6723                 gtk_widget_grab_focus(compose->followup_entry);
6724         else
6725                 gtk_widget_grab_focus(compose->text);
6726 }
6727
6728 static void bcc_activated(GtkWidget *widget, Compose *compose)
6729 {
6730         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6731                 gtk_widget_grab_focus(compose->reply_entry);
6732         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6733                 gtk_widget_grab_focus(compose->followup_entry);
6734         else
6735                 gtk_widget_grab_focus(compose->text);
6736 }
6737
6738 static void replyto_activated(GtkWidget *widget, Compose *compose)
6739 {
6740         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6741                 gtk_widget_grab_focus(compose->followup_entry);
6742         else
6743                 gtk_widget_grab_focus(compose->text);
6744 }
6745
6746 static void followupto_activated(GtkWidget *widget, Compose *compose)
6747 {
6748         gtk_widget_grab_focus(compose->text);
6749 }
6750 #endif
6751
6752 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6753                                              GtkWidget *widget)
6754 {
6755         Compose *compose = (Compose *)data;
6756
6757         if (GTK_CHECK_MENU_ITEM(widget)->active)
6758                 compose->return_receipt = TRUE;
6759         else
6760                 compose->return_receipt = FALSE;
6761 }
6762
6763 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6764                                             GdkEventKey *event,
6765                                             ComposeHeaderEntry *headerentry)
6766 {
6767         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6768             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6769             !(event->state & GDK_MODIFIER_MASK) &&
6770             (event->keyval == GDK_BackSpace) &&
6771             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6772                 gtk_container_remove
6773                         (GTK_CONTAINER(headerentry->compose->header_table),
6774                          headerentry->combo);
6775                 gtk_container_remove
6776                         (GTK_CONTAINER(headerentry->compose->header_table),
6777                          headerentry->entry);
6778                 headerentry->compose->header_list =
6779                         g_slist_remove(headerentry->compose->header_list,
6780                                        headerentry);
6781                 g_free(headerentry);
6782         } else  if (event->keyval == GDK_Tab) {
6783                 if (headerentry->compose->header_last == headerentry) {
6784                         /* Override default next focus, and give it to subject_entry
6785                          * instead of notebook tabs
6786                          */
6787                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6788                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6789                 }
6790         }
6791
6792 }
6793
6794 void compose_headerentry_changed_cb(GtkWidget *entry,
6795                                     ComposeHeaderEntry *headerentry)
6796 {
6797         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6798                 headerentry->compose->header_list =
6799                         g_slist_append(headerentry->compose->header_list,
6800                                        headerentry);
6801                 compose_create_header_entry(headerentry->compose);
6802                 gtk_signal_disconnect_by_func
6803                         (GTK_OBJECT(entry),
6804                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6805                          headerentry);
6806                 /* Automatically scroll down */
6807                 compose_show_first_last_header(headerentry->compose, FALSE);
6808                 
6809         }
6810 }
6811
6812 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6813 {
6814         GtkAdjustment *vadj;
6815
6816         g_return_if_fail(compose);
6817         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6818         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6819
6820         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6821         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6822 }
6823
6824 static void text_activated(GtkWidget *widget, Compose *compose)
6825 {
6826         compose_send_control_enter(compose);
6827 }
6828
6829 #define EDITABLE_LENGTH(x) \
6830         strlen(gtk_editable_get_chars(x,0,-1))
6831
6832 static void text_inserted(GtkWidget *widget, const gchar *text,
6833                           gint length, gint *position, Compose *compose)
6834 {
6835         GtkEditable *editable = GTK_EDITABLE(widget);
6836
6837         gtk_signal_handler_block_by_func(GTK_OBJECT(widget),
6838                                          GTK_SIGNAL_FUNC(text_inserted),
6839                                          compose);
6840         if (compose->paste_as_quotation) {
6841                 gchar *new_text;
6842                 gchar *qmark;
6843                 gint pos;
6844
6845                 new_text = g_strndup(text, length);
6846                 if (prefs_common.quotemark && *prefs_common.quotemark)
6847                         qmark = prefs_common.quotemark;
6848                 else
6849                         qmark = "> ";
6850                 gtk_stext_set_point(GTK_STEXT(widget), *position);
6851                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text);
6852                 pos = gtk_stext_get_point(GTK_STEXT(widget));
6853                 gtk_editable_set_position(editable, pos);
6854                 *position = pos;
6855                 g_free(new_text);
6856         } else
6857                 gtk_editable_insert_text(editable, text, length, position);
6858
6859         if (prefs_common.autowrap)
6860                 compose_wrap_line_all_full(compose, TRUE);
6861
6862         gtk_signal_handler_unblock_by_func(GTK_OBJECT(widget),
6863                                            GTK_SIGNAL_FUNC(text_inserted),
6864                                            compose);
6865         gtk_signal_emit_stop_by_name(GTK_OBJECT(editable), "insert_text");
6866
6867         
6868         if (prefs_common.autosave && 
6869             EDITABLE_LENGTH(editable) % prefs_common.autosave_length == 0)
6870                 compose_draft_cb((gpointer)compose, 1, NULL);
6871 }
6872
6873 static gboolean compose_send_control_enter(Compose *compose)
6874 {
6875         GdkEvent *ev;
6876         GdkEventKey *kev;
6877         GtkItemFactory *ifactory;
6878         GtkAccelEntry *accel;
6879         GtkWidget *send_menu;
6880         GSList *list;
6881         GdkModifierType ignored_mods =
6882                 (GDK_LOCK_MASK | GDK_MOD2_MASK | GDK_MOD3_MASK |
6883                  GDK_MOD4_MASK | GDK_MOD5_MASK);
6884
6885         ev = gtk_get_current_event();
6886         if (ev->type != GDK_KEY_PRESS) return FALSE;
6887
6888         kev = (GdkEventKey *)ev;
6889         if (!(kev->keyval == GDK_Return && (kev->state & GDK_CONTROL_MASK)))
6890                 return FALSE;
6891
6892         ifactory = gtk_item_factory_from_widget(compose->menubar);
6893         send_menu = gtk_item_factory_get_widget(ifactory, "/Message/Send");
6894         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_menu));
6895         accel = (GtkAccelEntry *)list->data;
6896         if (accel->accelerator_key == kev->keyval &&
6897             (accel->accelerator_mods & ~ignored_mods) ==
6898             (kev->state & ~ignored_mods)) {
6899                 compose_send_cb(compose, 0, NULL);
6900                 return TRUE;
6901         }
6902
6903         return FALSE;
6904 }
6905
6906 #if USE_ASPELL
6907 static void compose_check_all(Compose *compose)
6908 {
6909         if (compose->gtkaspell)
6910                 gtkaspell_check_all(compose->gtkaspell);
6911 }
6912
6913 static void compose_highlight_all(Compose *compose)
6914 {
6915         if (compose->gtkaspell)
6916                 gtkaspell_highlight_all(compose->gtkaspell);
6917 }
6918
6919 static void compose_check_backwards(Compose *compose)
6920 {
6921         if (compose->gtkaspell) 
6922                 gtkaspell_check_backwards(compose->gtkaspell);
6923         else {
6924                 GtkItemFactory *ifactory;
6925                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6926                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6927                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6928         }
6929 }
6930
6931 static void compose_check_forwards_go(Compose *compose)
6932 {
6933         if (compose->gtkaspell) 
6934                 gtkaspell_check_forwards_go(compose->gtkaspell);
6935         else {
6936                 GtkItemFactory *ifactory;
6937                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6938                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6939                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6940         }
6941 }
6942 #endif
6943
6944 static void set_toolbar_style(Compose *compose)
6945 {
6946         switch (prefs_common.toolbar_style) {
6947         case TOOLBAR_NONE:
6948                 gtk_widget_hide(compose->handlebox);
6949                 break;
6950         case TOOLBAR_ICON:
6951                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
6952                                       GTK_TOOLBAR_ICONS);
6953                 break;
6954         case TOOLBAR_TEXT:
6955                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
6956                                       GTK_TOOLBAR_TEXT);
6957                 break;
6958         case TOOLBAR_BOTH:
6959                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
6960                                       GTK_TOOLBAR_BOTH);
6961                 break;
6962         }
6963         
6964         if (prefs_common.toolbar_style != TOOLBAR_NONE) {
6965                 gtk_widget_show(compose->handlebox);
6966                 gtk_widget_queue_resize(compose->handlebox);
6967         }
6968 }