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