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