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