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