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