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