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