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