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