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