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