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