sync with 0.7.8cvs3
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gdk/gdkkeysyms.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkmenu.h>
30 #include <gtk/gtkmenuitem.h>
31 #include <gtk/gtkitemfactory.h>
32 #include <gtk/gtkcheckmenuitem.h>
33 #include <gtk/gtkoptionmenu.h>
34 #include <gtk/gtkwidget.h>
35 #include <gtk/gtkclist.h>
36 #include <gtk/gtkctree.h>
37 #include <gtk/gtkvpaned.h>
38 #include <gtk/gtkentry.h>
39 #include <gtk/gtkeditable.h>
40 #include <gtk/gtkwindow.h>
41 #include <gtk/gtksignal.h>
42 #include <gtk/gtkvbox.h>
43 #include <gtk/gtkcontainer.h>
44 #include <gtk/gtkhandlebox.h>
45 #include <gtk/gtktoolbar.h>
46 #include <gtk/gtktable.h>
47 #include <gtk/gtkhbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkscrolledwindow.h>
50 #include <gtk/gtkthemes.h>
51 #include <gtk/gtkdnd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <sys/types.h>
57 #include <sys/stat.h>
58 #include <unistd.h>
59 #include <time.h>
60 /* #include <sys/utsname.h> */
61 #include <stdlib.h>
62 #include <sys/wait.h>
63 #include <signal.h>
64 #include <errno.h>
65
66 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
67 #  include <wchar.h>
68 #  include <wctype.h>
69 #endif
70
71 #include "intl.h"
72 #include "main.h"
73 #include "mainwindow.h"
74 #include "compose.h"
75 #include "gtkstext.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "stock_pixmap.h"
81 #include "send.h"
82 #include "imap.h"
83 #include "news.h"
84 #include "customheader.h"
85 #include "prefs_common.h"
86 #include "prefs_account.h"
87 #include "account.h"
88 #include "filesel.h"
89 #include "procheader.h"
90 #include "procmime.h"
91 #include "statusbar.h"
92 #include "about.h"
93 #include "base64.h"
94 #include "codeconv.h"
95 #include "utils.h"
96 #include "gtkutils.h"
97 #include "socket.h"
98 #include "alertpanel.h"
99 #include "manage_window.h"
100 #include "gtkshruler.h"
101 #include "folder.h"
102 #include "addr_compl.h"
103 #include "quote_fmt.h"
104 #include "template.h"
105 #include "undo.h"
106 #include "foldersel.h"
107 #include "prefs_actions.h"
108
109 #if USE_GPGME
110 #  include "rfc2015.h"
111 #endif
112
113 typedef enum
114 {
115         COL_MIMETYPE = 0,
116         COL_SIZE     = 1,
117         COL_NAME     = 2
118 } AttachColumnPos;
119
120 #define N_ATTACH_COLS           3
121
122 typedef enum
123 {
124         COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE,
125         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_CHARACTER,
126         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_CHARACTER,
127         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_WORD,
128         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_WORD,
129         COMPOSE_CALL_GTK_STEXT_MOVE_END_OF_LINE,
130         COMPOSE_CALL_GTK_STEXT_MOVE_NEXT_LINE,
131         COMPOSE_CALL_GTK_STEXT_MOVE_PREVIOUS_LINE,
132         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_CHARACTER,
133         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_CHARACTER,
134         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_WORD,
135         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_WORD,
136         COMPOSE_CALL_GTK_STEXT_DELETE_LINE,
137         COMPOSE_CALL_GTK_STEXT_DELETE_LINE_N,
138         COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END
139 } ComposeCallGtkSTextAction;
140
141 typedef enum
142 {
143         PRIORITY_HIGHEST = 1,
144         PRIORITY_HIGH,
145         PRIORITY_NORMAL,
146         PRIORITY_LOW,
147         PRIORITY_LOWEST
148 } PriorityLevel;
149
150 #define B64_LINE_SIZE           57
151 #define B64_BUFFSIZE            77
152
153 #define MAX_REFERENCES_LEN      999
154
155 static GdkColor quote_color = {0, 0, 0, 0xbfff};
156
157 static GList *compose_list = NULL;
158
159 Compose *compose_generic_new                    (PrefsAccount   *account,
160                                                  const gchar    *to,
161                                                  FolderItem     *item);
162
163 static Compose *compose_create                  (PrefsAccount   *account,
164                                                  ComposeMode     mode);
165 static void compose_toolbar_create              (Compose        *compose,
166                                                  GtkWidget      *container);
167 static GtkWidget *compose_account_option_menu_create
168                                                 (Compose        *compose);
169 static void compose_set_template_menu           (Compose        *compose);
170 static void compose_template_apply              (Compose        *compose,
171                                                  Template       *tmpl,
172                                                  gboolean        replace);
173 static void compose_destroy                     (Compose        *compose);
174
175 static void compose_entries_set                 (Compose        *compose,
176                                                  const gchar    *mailto);
177 static gint compose_parse_header                (Compose        *compose,
178                                                  MsgInfo        *msginfo);
179 static gchar *compose_parse_references          (const gchar    *ref,
180                                                  const gchar    *msgid);
181
182 static gchar *compose_quote_fmt                 (Compose        *compose,
183                                                  MsgInfo        *msginfo,
184                                                  const gchar    *fmt,
185                                                  const gchar    *qmark,
186                                                  const gchar    *body);
187
188 static void compose_reply_set_entry             (Compose        *compose,
189                                                  MsgInfo        *msginfo,
190                                                  gboolean        to_all,
191                                                  gboolean        to_sender,
192                                                  gboolean
193                                                  followup_and_reply_to);
194 static void compose_reedit_set_entry            (Compose        *compose,
195                                                  MsgInfo        *msginfo);
196 static void compose_insert_sig                  (Compose        *compose);
197 static void compose_insert_file                 (Compose        *compose,
198                                                  const gchar    *file);
199 static void compose_attach_append               (Compose        *compose,
200                                                  const gchar    *file,
201                                                  const gchar    *type,
202                                                  const gchar    *content_type);
203 static void compose_attach_parts                (Compose        *compose,
204                                                  MsgInfo        *msginfo);
205 static void compose_wrap_line                   (Compose        *compose);
206 static void compose_wrap_line_all               (Compose        *compose);
207 static void compose_set_title                   (Compose        *compose);
208
209 static PrefsAccount *compose_current_mail_account(void);
210 /* static gint compose_send                     (Compose        *compose); */
211 static gboolean compose_check_for_valid_recipient
212                                                 (Compose        *compose);
213 static gboolean compose_check_entries           (Compose        *compose,
214                                                  gboolean       check_subject);
215 static gint compose_write_to_file               (Compose        *compose,
216                                                  const gchar    *file,
217                                                  gboolean        is_draft);
218 static gint compose_write_body_to_file          (Compose        *compose,
219                                                  const gchar    *file);
220 static gint compose_remove_reedit_target        (Compose        *compose);
221 static gint compose_queue                       (Compose        *compose,
222                                                  gint           *msgnum,
223                                                  FolderItem     **item);
224 static gint compose_queue_sub                   (Compose        *compose,
225                                                  gint           *msgnum,
226                                                  FolderItem     **item,
227                                                  gboolean       check_subject);
228 static void compose_write_attach                (Compose        *compose,
229                                                  FILE           *fp);
230 static gint compose_write_headers               (Compose        *compose,
231                                                  FILE           *fp,
232                                                  const gchar    *charset,
233                                                  EncodingType    encoding,
234                                                  gboolean        is_draft);
235
236 static void compose_convert_header              (gchar          *dest,
237                                                  gint            len,
238                                                  gchar          *src,
239                                                  gint            header_len);
240 static void compose_generate_msgid              (Compose        *compose,
241                                                  gchar          *buf,
242                                                  gint            len);
243
244 static void compose_attach_info_free            (AttachInfo     *ainfo);
245 static void compose_attach_remove_selected      (Compose        *compose);
246
247 static void compose_attach_property             (Compose        *compose);
248 static void compose_attach_property_create      (gboolean       *cancelled);
249 static void attach_property_ok                  (GtkWidget      *widget,
250                                                  gboolean       *cancelled);
251 static void attach_property_cancel              (GtkWidget      *widget,
252                                                  gboolean       *cancelled);
253 static gint attach_property_delete_event        (GtkWidget      *widget,
254                                                  GdkEventAny    *event,
255                                                  gboolean       *cancelled);
256 static void attach_property_key_pressed         (GtkWidget      *widget,
257                                                  GdkEventKey    *event,
258                                                  gboolean       *cancelled);
259
260 static void compose_exec_ext_editor             (Compose           *compose);
261 static gint compose_exec_ext_editor_real        (const gchar       *file);
262 static gboolean compose_ext_editor_kill         (Compose           *compose);
263 static void compose_input_cb                    (gpointer           data,
264                                                  gint               source,
265                                                  GdkInputCondition  condition);
266 static void compose_set_ext_editor_sensitive    (Compose           *compose,
267                                                  gboolean           sensitive);
268
269 static void compose_undo_state_changed          (UndoMain       *undostruct,
270                                                  gint            undo_state,
271                                                  gint            redo_state,
272                                                  gpointer        data);
273
274 static gint calc_cursor_xpos    (GtkSText       *text,
275                                  gint            extra,
276                                  gint            char_width);
277
278 static void compose_create_header_entry (Compose *compose);
279 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
280 static void compose_update_priority_menu_item(Compose * compose);
281
282 /* callback functions */
283
284 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
285                                          GtkAllocation  *allocation,
286                                          GtkSHRuler     *shruler);
287
288 static void toolbar_send_cb             (GtkWidget      *widget,
289                                          gpointer        data);
290 static void toolbar_send_later_cb       (GtkWidget      *widget,
291                                          gpointer        data);
292 static void toolbar_draft_cb            (GtkWidget      *widget,
293                                          gpointer        data);
294 static void toolbar_insert_cb           (GtkWidget      *widget,
295                                          gpointer        data);
296 static void toolbar_attach_cb           (GtkWidget      *widget,
297                                          gpointer        data);
298 static void toolbar_sig_cb              (GtkWidget      *widget,
299                                          gpointer        data);
300 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
301                                          gpointer        data);
302 static void toolbar_linewrap_cb         (GtkWidget      *widget,
303                                          gpointer        data);
304 static void toolbar_address_cb          (GtkWidget      *widget,
305                                          gpointer        data);
306
307 static void select_account              (Compose        *compose,
308                                          PrefsAccount   *ac);
309
310 static void account_activated           (GtkMenuItem    *menuitem,
311                                          gpointer        data);
312
313 static void attach_selected             (GtkCList       *clist,
314                                          gint            row,
315                                          gint            column,
316                                          GdkEvent       *event,
317                                          gpointer        data);
318 static void attach_button_pressed       (GtkWidget      *widget,
319                                          GdkEventButton *event,
320                                          gpointer        data);
321 static void attach_key_pressed          (GtkWidget      *widget,
322                                          GdkEventKey    *event,
323                                          gpointer        data);
324
325 static void compose_send_cb             (gpointer        data,
326                                          guint           action,
327                                          GtkWidget      *widget);
328 static void compose_send_later_cb       (gpointer        data,
329                                          guint           action,
330                                          GtkWidget      *widget);
331
332 static void compose_draft_cb            (gpointer        data,
333                                          guint           action,
334                                          GtkWidget      *widget);
335
336 static void compose_attach_cb           (gpointer        data,
337                                          guint           action,
338                                          GtkWidget      *widget);
339 static void compose_insert_file_cb      (gpointer        data,
340                                          guint           action,
341                                          GtkWidget      *widget);
342
343 static void compose_close_cb            (gpointer        data,
344                                          guint           action,
345                                          GtkWidget      *widget);
346
347 static void compose_address_cb          (gpointer        data,
348                                          guint           action,
349                                          GtkWidget      *widget);
350 static void compose_template_activate_cb(GtkWidget      *widget,
351                                          gpointer        data);
352
353 static void compose_ext_editor_cb       (gpointer        data,
354                                          guint           action,
355                                          GtkWidget      *widget);
356
357 static gint compose_delete_cb           (GtkWidget      *widget,
358                                          GdkEventAny    *event,
359                                          gpointer        data);
360 static void compose_destroy_cb          (GtkWidget      *widget,
361                                          Compose        *compose);
362
363 static void compose_undo_cb             (Compose        *compose);
364 static void compose_redo_cb             (Compose        *compose);
365 static void compose_cut_cb              (Compose        *compose);
366 static void compose_copy_cb             (Compose        *compose);
367 static void compose_paste_cb            (Compose        *compose);
368 static void compose_allsel_cb           (Compose        *compose);
369
370 static void compose_gtk_stext_action_cb (Compose                   *compose,
371                                          ComposeCallGtkSTextAction  action);
372
373 static void compose_grab_focus_cb       (GtkWidget      *widget,
374                                          Compose        *compose);
375
376 static void compose_changed_cb          (GtkEditable    *editable,
377                                          Compose        *compose);
378 static void compose_button_press_cb     (GtkWidget      *widget,
379                                          GdkEventButton *event,
380                                          Compose        *compose);
381 #if 0
382 static void compose_key_press_cb        (GtkWidget      *widget,
383                                          GdkEventKey    *event,
384                                          Compose        *compose);
385 #endif
386
387 #if 0
388 static void compose_toggle_to_cb        (gpointer        data,
389                                          guint           action,
390                                          GtkWidget      *widget);
391 static void compose_toggle_cc_cb        (gpointer        data,
392                                          guint           action,
393                                          GtkWidget      *widget);
394 static void compose_toggle_bcc_cb       (gpointer        data,
395                                          guint           action,
396                                          GtkWidget      *widget);
397 static void compose_toggle_replyto_cb   (gpointer        data,
398                                          guint           action,
399                                          GtkWidget      *widget);
400 static void compose_toggle_followupto_cb(gpointer        data,
401                                          guint           action,
402                                          GtkWidget      *widget);
403 static void compose_toggle_attach_cb    (gpointer        data,
404                                          guint           action,
405                                          GtkWidget      *widget);
406 #endif
407 static void compose_toggle_ruler_cb     (gpointer        data,
408                                          guint           action,
409                                          GtkWidget      *widget);
410 #if USE_GPGME
411 static void compose_toggle_sign_cb      (gpointer        data,
412                                          guint           action,
413                                          GtkWidget      *widget);
414 static void compose_toggle_encrypt_cb   (gpointer        data,
415                                          guint           action,
416                                          GtkWidget      *widget);
417 #endif
418 static void compose_toggle_return_receipt_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 subject_activated           (GtkWidget      *widget,
447                                          Compose        *compose);
448 static void cc_activated                (GtkWidget      *widget,
449                                          Compose        *compose);
450 static void bcc_activated               (GtkWidget      *widget,
451                                          Compose        *compose);
452 static void replyto_activated           (GtkWidget      *widget,
453                                          Compose        *compose);
454 static void followupto_activated        (GtkWidget      *widget,
455                                          Compose        *compose);
456 #endif
457
458 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
459                                   gboolean to_all,
460                                   gboolean ignore_replyto,
461                                   gboolean followup_and_reply_to,
462                                   const gchar *body);
463
464 void compose_headerentry_changed_cb        (GtkWidget          *entry,
465                                             ComposeHeaderEntry *headerentry);
466 void compose_headerentry_key_press_event_cb(GtkWidget          *entry,
467                                             GdkEventKey        *event,
468                                             ComposeHeaderEntry *headerentry);
469
470 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
471
472 #if USE_PSPELL
473 static void compose_check_all              (Compose *compose);
474 static void compose_highlight_all          (Compose *compose);
475 static void compose_check_backwards        (Compose *compose);
476 static void compose_check_forwards_go      (Compose *compose);
477 #endif
478
479 static gboolean compose_send_control_enter (Compose *compose);
480 static void text_activated                 (GtkWidget   *widget,
481                                             Compose     *compose);
482
483 static GtkItemFactoryEntry compose_popup_entries[] =
484 {
485         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
486         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
487         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
488         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
489 };
490
491 static GtkItemFactoryEntry compose_entries[] =
492 {
493         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
494         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
495         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
496         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
497         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
498         {N_("/_File/_Close"),                   "<control>W", compose_close_cb, 0, NULL},
499
500         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
501         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
502         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
503         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
504         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
505         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
506         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
507         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
508         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
509         {N_("/_Edit/A_dvanced/Move a character backward"),
510                                         "<control>B",
511                                         compose_gtk_stext_action_cb,
512                                         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_CHARACTER,
513                                         NULL},
514         {N_("/_Edit/A_dvanced/Move a character forward"),
515                                         "<control>F",
516                                         compose_gtk_stext_action_cb,
517                                         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_CHARACTER,
518                                         NULL},
519         {N_("/_Edit/A_dvanced/Move a word backward"),
520                                         NULL, /* "<alt>B" */
521                                         compose_gtk_stext_action_cb,
522                                         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_WORD,
523                                         NULL},
524         {N_("/_Edit/A_dvanced/Move a word forward"),
525                                         NULL, /* "<alt>F" */
526                                         compose_gtk_stext_action_cb,
527                                         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_WORD,
528                                         NULL},
529         {N_("/_Edit/A_dvanced/Move to beginning of line"),
530                                         NULL, /* "<control>A" */
531                                         compose_gtk_stext_action_cb,
532                                         COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE,
533                                         NULL},
534         {N_("/_Edit/A_dvanced/Move to end of line"),
535                                         "<control>E",
536                                         compose_gtk_stext_action_cb,
537                                         COMPOSE_CALL_GTK_STEXT_MOVE_END_OF_LINE,
538                                         NULL},
539         {N_("/_Edit/A_dvanced/Move to previous line"),
540                                         "<control>P",
541                                         compose_gtk_stext_action_cb,
542                                         COMPOSE_CALL_GTK_STEXT_MOVE_PREVIOUS_LINE,
543                                         NULL},
544         {N_("/_Edit/A_dvanced/Move to next line"),
545                                         "<control>N",
546                                         compose_gtk_stext_action_cb,
547                                         COMPOSE_CALL_GTK_STEXT_MOVE_NEXT_LINE,
548                                         NULL},
549         {N_("/_Edit/A_dvanced/Delete a character backward"),
550                                         "<control>H",
551                                         compose_gtk_stext_action_cb,
552                                         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_CHARACTER,
553                                         NULL},
554         {N_("/_Edit/A_dvanced/Delete a character forward"),
555                                         "<control>D",
556                                         compose_gtk_stext_action_cb,
557                                         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_CHARACTER,
558                                         NULL},
559         {N_("/_Edit/A_dvanced/Delete a word backward"),
560                                         NULL, /* "<control>W" */
561                                         compose_gtk_stext_action_cb,
562                                         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_WORD,
563                                         NULL},
564         {N_("/_Edit/A_dvanced/Delete a word forward"),
565                                         NULL, /* "<alt>D", */
566                                         compose_gtk_stext_action_cb,
567                                         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_WORD,
568                                         NULL},
569         {N_("/_Edit/A_dvanced/Delete line"),
570                                         "<control>U",
571                                         compose_gtk_stext_action_cb,
572                                         COMPOSE_CALL_GTK_STEXT_DELETE_LINE,
573                                         NULL},
574         {N_("/_Edit/A_dvanced/Delete entire line"),
575                                         NULL,
576                                         compose_gtk_stext_action_cb,
577                                         COMPOSE_CALL_GTK_STEXT_DELETE_LINE_N,
578                                         NULL},
579         {N_("/_Edit/A_dvanced/Delete to end of line"),
580                                         "<control>K",
581                                         compose_gtk_stext_action_cb,
582                                         COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END,
583                                         NULL},
584         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
585         {N_("/_Edit/_Wrap current paragraph"),
586                                         "<control>L", compose_wrap_line, 0, NULL},
587         {N_("/_Edit/Wrap all long _lines"),
588                                         "<control><alt>L", compose_wrap_line_all, 0, NULL},
589         {N_("/_Edit/Edit with e_xternal editor"),
590                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
591 #if USE_PSPELL
592         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
593         {N_("/_Spelling/_Check all or check selection"),
594                                         NULL, compose_check_all, 0, NULL},
595         {N_("/_Spelling/_Highlight all misspelled words"),
596                                         NULL, compose_highlight_all, 0, NULL},
597         {N_("/_Spelling/Check _backwards misspelled word"),
598                                         NULL, compose_check_backwards , 0, NULL},
599         {N_("/_Spelling/_Forward to next misspelled word"),
600                                         NULL, compose_check_forwards_go, 0, NULL},
601         {N_("/_Spelling/---"),          NULL, NULL, 0, "<Separator>"},
602         {N_("/_Spelling/_Spelling Configuration"),
603                                         NULL, NULL, 0, "<Branch>"},
604 #endif
605 #if 0 /* NEW COMPOSE GUI */
606         {N_("/_View"),                  NULL, NULL, 0, "<Branch>"},
607         {N_("/_View/_To"),              NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
608         {N_("/_View/_Cc"),              NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
609         {N_("/_View/_Bcc"),             NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
610         {N_("/_View/_Reply to"),        NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
611         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
612         {N_("/_View/_Followup to"),     NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
613         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
614         {N_("/_View/R_uler"),           NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
615         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
616         {N_("/_View/_Attachment"),      NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
617 #endif
618         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
619         {N_("/_Message/_Send"),         "<control>Return",
620                                         compose_send_cb, 0, NULL},
621         {N_("/_Message/Send _later"),   "<shift><control>S",
622                                         compose_send_later_cb,  0, NULL},
623         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
624         {N_("/_Message/Save to _draft folder"),
625                                         "<shift><control>D", compose_draft_cb, 0, NULL},
626         {N_("/_Message/Save and _keep editing"),
627                                         "<control>S", compose_draft_cb, 1, NULL},
628 #if 0 /* NEW COMPOSE GUI */
629         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
630         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
631         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
632         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
633         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
634         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
635         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
636         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
637         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
638 #endif
639 #if USE_GPGME
640         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
641         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
642         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
643 #endif /* USE_GPGME */
644         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
645         {N_("/_Message/Priority"),      NULL,           NULL,   0, "<Branch>"},
646         {N_("/_Message/Priority/Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
647         {N_("/_Message/Priority/High"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Message/Priority/Highest"},
648         {N_("/_Message/Priority/Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Message/Priority/Highest"},
649         {N_("/_Message/Priority/Low"),     NULL, compose_set_priority_cb, PRIORITY_LOW, "/Message/Priority/Highest"},
650         {N_("/_Message/Priority/Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Message/Priority/Highest"},
651         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
652         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
653         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
654         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
655         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
656         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
657         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
658         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
659         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
660 };
661
662 static GtkTargetEntry compose_mime_types[] =
663 {
664         {"text/uri-list", 0, 0}
665 };
666
667 Compose *compose_new(PrefsAccount *account)
668 {
669         return compose_generic_new(account, NULL, NULL);
670 }
671
672 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
673 {
674         Compose *c;
675         gchar *filename;
676         GtkItemFactory *ifactory;
677         
678         c = compose_generic_new(account, NULL, NULL);
679
680         filename = procmsg_get_message_file(msginfo);
681         if (filename == NULL)
682                 return NULL;
683
684         c->redirect_filename = filename;
685
686         if (msginfo->subject)
687                 gtk_entry_set_text(GTK_ENTRY(c->subject_entry),
688                                    msginfo->subject);
689         gtk_editable_set_editable(GTK_EDITABLE(c->subject_entry), FALSE);
690
691         compose_quote_fmt(c, msginfo, "%M", NULL, NULL);
692         gtk_editable_set_editable(GTK_EDITABLE(c->text), FALSE);
693
694         ifactory = gtk_item_factory_from_widget(c->popupmenu);
695         menu_set_sensitive(ifactory, "/Add...", FALSE);
696         menu_set_sensitive(ifactory, "/Remove", FALSE);
697         menu_set_sensitive(ifactory, "/Property...", FALSE);
698
699         ifactory = gtk_item_factory_from_widget(c->menubar);
700         menu_set_sensitive(ifactory, "/File/Insert file", FALSE);
701         menu_set_sensitive(ifactory, "/File/Attach file", FALSE);
702         menu_set_sensitive(ifactory, "/File/Insert signature", FALSE);
703         menu_set_sensitive(ifactory, "/Edit/Paste", FALSE);
704         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", FALSE);
705         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", FALSE);
706         menu_set_sensitive(ifactory, "/Edit/Edit with external editor", FALSE);
707         menu_set_sensitive(ifactory, "/Message/Attach", FALSE);
708 #if USE_GPGME
709         menu_set_sensitive(ifactory, "/Message/Sign", FALSE);
710         menu_set_sensitive(ifactory, "/Message/Encrypt", FALSE);
711 #endif
712         menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE);
713         menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
714         
715         gtk_widget_set_sensitive(c->insert_btn, FALSE);
716         gtk_widget_set_sensitive(c->attach_btn, FALSE);
717         gtk_widget_set_sensitive(c->sig_btn, FALSE);
718         gtk_widget_set_sensitive(c->exteditor_btn, FALSE);
719         gtk_widget_set_sensitive(c->linewrap_btn, FALSE);
720
721         return c;
722 }
723
724 Compose *compose_new_with_recipient(PrefsAccount *account, const gchar *mailto)
725 {
726         return compose_generic_new(account, mailto, NULL);
727 }
728
729 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
730 {
731         return compose_generic_new(account, NULL, item);
732 }
733
734 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item)
735 {
736         Compose *compose;
737         GtkSText *text;
738
739         if (item && item->prefs && item->prefs->enable_default_account)
740                 account = account_find_from_id(item->prefs->default_account);
741
742         if (!account) account = cur_account;
743         g_return_val_if_fail(account != NULL, NULL);
744
745         compose = compose_create(account, COMPOSE_NEW);
746         compose->replyinfo = NULL;
747
748         text = GTK_STEXT(compose->text);
749         gtk_stext_freeze(text);
750
751         if (prefs_common.auto_sig)
752                 compose_insert_sig(compose);
753         gtk_editable_set_position(GTK_EDITABLE(text), 0);
754         gtk_stext_set_point(text, 0);
755
756         gtk_stext_thaw(text);
757
758         /* workaround for initial XIM problem */
759         gtk_widget_grab_focus(compose->text);
760         gtkut_widget_wait_for_draw(compose->text);
761
762         if (account->protocol != A_NNTP) {
763                 if (mailto) {
764                         compose_entries_set(compose, mailto);
765
766                 } else if(item && item->prefs->enable_default_to) {
767                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
768                 }
769                 if (item && item->ret_rcpt) {
770                         GtkItemFactory *ifactory;
771                 
772                         ifactory = gtk_item_factory_from_widget(compose->menubar);
773                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
774                 }
775         } else {
776                 if (mailto) {
777                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
778                 }
779         }
780         compose_show_first_last_header(compose, TRUE);
781
782         /* Set save folder */
783         if(item && item->prefs && item->prefs->save_copy_to_folder) {
784                 gchar *folderidentifier;
785
786                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
787                 folderidentifier = folder_item_get_identifier(item);
788                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
789                 g_free(folderidentifier);
790         }
791
792         gtk_widget_grab_focus(compose->header_last->entry);
793
794         if (prefs_common.auto_exteditor)
795                 compose_exec_ext_editor(compose);
796
797         return compose;
798 }
799
800 #define CHANGE_FLAGS(msginfo) \
801 { \
802 if (msginfo->folder->folder->change_flags != NULL) \
803 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
804                                       msginfo->folder, \
805                                       msginfo); \
806 }
807
808 /*
809 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
810                                            const gchar *followupto, gchar * to)
811 {
812         Compose *compose;
813
814         if (!account) account = cur_account;
815         g_return_val_if_fail(account != NULL, NULL);
816         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
817
818         compose = compose_create(account, COMPOSE_NEW);
819
820         if (prefs_common.auto_sig)
821                 compose_insert_sig(compose);
822         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
823         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
824
825         compose_entry_append(compose, to, COMPOSE_TO);
826         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
827         gtk_widget_grab_focus(compose->subject_entry);
828
829         return compose;
830 }
831 */
832
833 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
834                    gboolean ignore_replyto, const gchar *body)
835 {
836         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, FALSE,
837                               body);
838 }
839
840 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
841                                    gboolean to_all,
842                                    gboolean ignore_replyto,
843                                    const gchar *body)
844 {
845         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, TRUE,
846                               body);
847 }
848
849 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
850                                   gboolean to_all,
851                                   gboolean ignore_replyto,
852                                   gboolean followup_and_reply_to,
853                                   const gchar *body)
854 {
855         Compose *compose;
856         PrefsAccount *account;
857         PrefsAccount *reply_account;
858         GtkSText *text;
859
860         g_return_if_fail(msginfo != NULL);
861         g_return_if_fail(msginfo->folder != NULL);
862
863         account = NULL;
864         /* select the account set in folderitem's property (if enabled) */
865         if (msginfo->folder->prefs && msginfo->folder->prefs->enable_default_account)
866                 account = account_find_from_id(msginfo->folder->prefs->default_account);
867         
868         /* select the account for the whole folder (IMAP / NNTP) */
869         if (!account)
870                 /* FIXME: this is not right, because folder may be nested. we should
871                  * ascend the tree until we find a parent with proper account 
872                  * information */
873                 account = msginfo->folder->folder->account;
874
875         /* select account by to: and cc: header if enabled */
876         if (prefs_common.reply_account_autosel) {
877                 if (!account && msginfo->to) {
878                         gchar *to;
879                         Xstrdup_a(to, msginfo->to, return);
880                         extract_address(to);
881                         account = account_find_from_address(to);
882                 }
883                 if (!account) {
884                         gchar cc[BUFFSIZE];
885                         if(!get_header_from_msginfo(msginfo, cc, sizeof(cc), "CC:")) { /* Found a CC header */
886                                 extract_address(cc);
887                                 account = account_find_from_address(cc);
888                         }        
889                 }
890         }
891
892         /* select current account */
893         if (!account) account = cur_account;
894         g_return_if_fail(account != NULL);
895
896         if (ignore_replyto && account->protocol == A_NNTP &&
897             !followup_and_reply_to) {
898                 reply_account =
899                         account_find_from_address(account->address);
900                 if (!reply_account)
901                         reply_account = compose_current_mail_account();
902                 if (!reply_account)
903                         return;
904         } else
905                 reply_account = account;
906
907         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
908         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
909         if (MSG_IS_IMAP(msginfo->flags))
910                 imap_msg_set_perm_flags(msginfo, MSG_REPLIED);
911         CHANGE_FLAGS(msginfo);
912
913         compose = compose_create(account, COMPOSE_REPLY);
914         compose->replyinfo = procmsg_msginfo_copy(msginfo);
915
916 #if 0 /* NEW COMPOSE GUI */
917         if (followup_and_reply_to) {
918                 gtk_widget_show(compose->to_hbox);
919                 gtk_widget_show(compose->to_entry);
920                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
921                 compose->use_to = TRUE;
922         }
923 #endif
924         if (msginfo->folder && msginfo->folder->ret_rcpt) {
925                 GtkItemFactory *ifactory;
926         
927                 ifactory = gtk_item_factory_from_widget(compose->menubar);
928                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
929         }
930
931         /* Set save folder */
932         if(msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
933                 gchar *folderidentifier;
934
935                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
936                 folderidentifier = folder_item_get_identifier(msginfo->folder);
937                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
938                 g_free(folderidentifier);
939         }
940
941         if (compose_parse_header(compose, msginfo) < 0) return;
942         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto,
943                                 followup_and_reply_to);
944         compose_show_first_last_header(compose, TRUE);
945
946         text = GTK_STEXT(compose->text);
947         gtk_stext_freeze(text);
948
949         if (quote) {
950                 gchar *qmark;
951                 gchar *quote_str;
952
953                 if (prefs_common.quotemark && *prefs_common.quotemark)
954                         qmark = prefs_common.quotemark;
955                 else
956                         qmark = "> ";
957
958                 quote_str = compose_quote_fmt(compose, msginfo,
959                                               prefs_common.quotefmt,
960                                               qmark, body);
961         }
962
963         if (prefs_common.auto_sig)
964                 compose_insert_sig(compose);
965
966         if (quote && prefs_common.linewrap_quote)
967                 compose_wrap_line_all(compose);
968
969         gtk_editable_set_position(GTK_EDITABLE(text), 0);
970         gtk_stext_set_point(text, 0);
971
972         gtk_stext_thaw(text);
973         gtk_widget_grab_focus(compose->text);
974
975         if (prefs_common.auto_exteditor)
976                 compose_exec_ext_editor(compose);
977 }
978
979 static void set_toolbar_style(Compose *compose);
980
981 static gchar *procmime_get_file_name(MimeInfo *mimeinfo)
982 {
983         gchar *base;
984         gchar *filename;
985
986         g_return_val_if_fail(mimeinfo != NULL, NULL);
987
988         base = mimeinfo->filename ? mimeinfo->filename
989                 : mimeinfo->name ? mimeinfo->name : NULL;
990
991         if (MIME_TEXT_HTML == mimeinfo->mime_type && base == NULL){
992                 filename = g_strdup_printf("%s%smimetmp.%08x.html",
993                                            get_mime_tmp_dir(),
994                                            G_DIR_SEPARATOR_S,
995                                            (gint)mimeinfo);
996                 return filename;
997         }
998         else {
999                 base = base ? base : "";
1000                 base = g_basename(base);
1001                 if (*base == '\0') {
1002                         filename = g_strdup_printf("%s%smimetmp.%08x",
1003                                                    get_mime_tmp_dir(),
1004                                                    G_DIR_SEPARATOR_S,
1005                                                    (gint)mimeinfo);
1006                         return filename;
1007                 }
1008         }
1009
1010         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
1011                                base, NULL);
1012
1013         return filename;
1014 }
1015
1016 static gchar *mime_extract_file(gchar *source, MimeInfo *partinfo)
1017 {
1018         gchar *filename;
1019
1020         if (!partinfo) return NULL;
1021
1022         filename = procmime_get_file_name(partinfo);
1023
1024         if (procmime_get_part(filename, source, partinfo) < 0)
1025                 alertpanel_error
1026                         (_("Can't get the part of multipart message."));
1027
1028         return filename;
1029 }
1030
1031
1032
1033 #define INSERT_FW_HEADER(var, hdr) \
1034 if (msginfo->var && *msginfo->var) { \
1035         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1036         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1037         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1038 }
1039
1040 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1041                          gboolean as_attach, const gchar *body)
1042 {
1043         Compose *compose;
1044         /*      PrefsAccount *account; */
1045         GtkSText *text;
1046
1047         g_return_val_if_fail(msginfo != NULL, NULL);
1048         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1049
1050         account = msginfo->folder->folder->account;
1051         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1052                 gchar *to;
1053                 Xstrdup_a(to, msginfo->to, return NULL);
1054                 extract_address(to);
1055                 account = account_find_from_address(to);
1056         }
1057
1058         if(!account && prefs_common.forward_account_autosel) {
1059                 gchar cc[BUFFSIZE];
1060                 if(!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1061                         extract_address(cc);
1062                         account = account_find_from_address(cc);
1063                 }
1064         }
1065
1066         if (account == NULL) {
1067                 account = cur_account;
1068                 /*
1069                 account = msginfo->folder->folder->account;
1070                 if (!account) account = cur_account;
1071                 */
1072         }
1073         g_return_val_if_fail(account != NULL, NULL);
1074
1075         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
1076         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
1077         if (MSG_IS_IMAP(msginfo->flags))
1078                 imap_msg_unset_perm_flags(msginfo, MSG_REPLIED);
1079         CHANGE_FLAGS(msginfo);
1080
1081         compose = compose_create(account, COMPOSE_FORWARD);
1082
1083         if (msginfo->subject && *msginfo->subject) {
1084                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1085                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1086                                       msginfo->subject);
1087         }
1088
1089         text = GTK_STEXT(compose->text);
1090         gtk_stext_freeze(text);
1091
1092
1093                 if (as_attach) {
1094                         gchar *msgfile;
1095
1096                         msgfile = procmsg_get_message_file_path(msginfo);
1097                         if (!is_file_exist(msgfile))
1098                                 g_warning(_("%s: file not exist\n"), msgfile);
1099                         else
1100                                 compose_attach_append(compose, msgfile, msgfile,
1101                                                       "message/rfc822");
1102
1103                         g_free(msgfile);
1104                 } else {
1105                         gchar *qmark;
1106                         gchar *quote_str;
1107
1108                         if (prefs_common.fw_quotemark &&
1109                             *prefs_common.fw_quotemark)
1110                                 qmark = prefs_common.fw_quotemark;
1111                         else
1112                                 qmark = "> ";
1113
1114                         quote_str = compose_quote_fmt(compose, msginfo,
1115                                                       prefs_common.fw_quotefmt,
1116                                                       qmark, body);
1117                         compose_attach_parts(compose, msginfo);
1118                 }
1119
1120         if (prefs_common.auto_sig)
1121                 compose_insert_sig(compose);
1122
1123         if (prefs_common.linewrap_quote)
1124                 compose_wrap_line_all(compose);
1125
1126         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1127         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1128
1129         gtk_stext_thaw(text);
1130 #if 0 /* NEW COMPOSE GUI */
1131         if (account->protocol != A_NNTP)
1132                 gtk_widget_grab_focus(compose->to_entry);
1133         else
1134                 gtk_widget_grab_focus(compose->newsgroups_entry);
1135 #endif
1136         gtk_widget_grab_focus(compose->header_last->entry);
1137
1138         if (prefs_common.auto_exteditor)
1139                 compose_exec_ext_editor(compose);
1140
1141         return compose;
1142 }
1143
1144 #undef INSERT_FW_HEADER
1145
1146 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1147 {
1148         Compose *compose;
1149         GtkSText *text;
1150         GSList *msginfo;
1151         gchar *msgfile;
1152
1153         g_return_val_if_fail(msginfo_list != NULL, NULL);
1154         
1155         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1156                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1157                         return NULL;
1158         }
1159
1160         if (account == NULL) {
1161                 account = cur_account;
1162                 /*
1163                 account = msginfo->folder->folder->account;
1164                 if (!account) account = cur_account;
1165                 */
1166         }
1167         g_return_val_if_fail(account != NULL, NULL);
1168
1169         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1170                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1171                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1172                 CHANGE_FLAGS(((MsgInfo *)msginfo->data));
1173         }
1174
1175         compose = compose_create(account, COMPOSE_FORWARD);
1176
1177         text = GTK_STEXT(compose->text);
1178         gtk_stext_freeze(text);
1179
1180         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1181                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1182                 if (!is_file_exist(msgfile))
1183                         g_warning(_("%s: file not exist\n"), msgfile);
1184                 else
1185                         compose_attach_append(compose, msgfile, msgfile,
1186                                 "message/rfc822");
1187                 g_free(msgfile);
1188         }
1189
1190         if (prefs_common.auto_sig)
1191                 compose_insert_sig(compose);
1192
1193         if (prefs_common.linewrap_quote)
1194                 compose_wrap_line_all(compose);
1195
1196         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1197         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1198
1199         gtk_stext_thaw(text);
1200 #if 0 /* NEW COMPOSE GUI */
1201         if (account->protocol != A_NNTP)
1202                 gtk_widget_grab_focus(compose->to_entry);
1203         else
1204                 gtk_widget_grab_focus(compose->newsgroups_entry);
1205 #endif
1206
1207         return compose;
1208 }
1209
1210 void compose_reedit(MsgInfo *msginfo)
1211 {
1212         Compose *compose;
1213         PrefsAccount *account = NULL;
1214         GtkSText *text;
1215         FILE *fp;
1216         gchar buf[BUFFSIZE];
1217
1218         g_return_if_fail(msginfo != NULL);
1219         g_return_if_fail(msginfo->folder != NULL);
1220
1221         if (msginfo->folder->stype == F_QUEUE) {
1222                 gchar queueheader_buf[BUFFSIZE];
1223                 gint id;
1224
1225                 /* Select Account from queue headers */
1226                 if (!get_header_from_msginfo(msginfo, queueheader_buf, 
1227                                              sizeof(queueheader_buf), "NAID:")) {
1228                         id = atoi(&queueheader_buf[5]);
1229                         account = account_find_from_id(id);
1230                 }
1231                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1232                                                     sizeof(queueheader_buf), "MAID:")) {
1233                         id = atoi(&queueheader_buf[5]);
1234                         account = account_find_from_id(id);
1235                 }
1236                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1237                                                                 sizeof(queueheader_buf), "S:")) {
1238                         account = account_find_from_address(queueheader_buf);
1239                 }
1240         } else 
1241                 account = msginfo->folder->folder->account;
1242
1243         if (!account && prefs_common.reedit_account_autosel) {
1244                 gchar from[BUFFSIZE];
1245                 if (!get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1246                         extract_address(from);
1247                         account = account_find_from_address(from);
1248                 }
1249         }
1250         if (!account) account = cur_account;
1251         g_return_if_fail(account != NULL);
1252
1253         compose = compose_create(account, COMPOSE_REEDIT);
1254         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1255
1256         if (msginfo->folder->stype == F_QUEUE) {
1257                 gchar queueheader_buf[BUFFSIZE];
1258
1259                 /* Set message save folder */
1260                 if (!get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1261                         gint startpos = 0;
1262
1263                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1264                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1265                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1266                 }
1267         }
1268         
1269         if (compose_parse_header(compose, msginfo) < 0) return;
1270         compose_reedit_set_entry(compose, msginfo);
1271
1272         text = GTK_STEXT(compose->text);
1273         gtk_stext_freeze(text);
1274
1275         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1276                 g_warning(_("Can't get text part\n"));
1277         else {
1278                 while (fgets(buf, sizeof(buf), fp) != NULL)
1279                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1280                 fclose(fp);
1281         }
1282         compose_attach_parts(compose, msginfo);
1283
1284         gtk_stext_thaw(text);
1285         gtk_widget_grab_focus(compose->text);
1286
1287         if (prefs_common.auto_exteditor)
1288                 compose_exec_ext_editor(compose);
1289 }
1290
1291 GList *compose_get_compose_list(void)
1292 {
1293         return compose_list;
1294 }
1295
1296 void compose_entry_append(Compose *compose, const gchar *address,
1297                           ComposeEntryType type)
1298 {
1299         GtkEntry *entry;
1300         const gchar *text;
1301         gchar *header;
1302
1303         if (!address || *address == '\0') return;
1304
1305 #if 0 /* NEW COMPOSE GUI */
1306         switch (type) {
1307         case COMPOSE_CC:
1308                 entry = GTK_ENTRY(compose->cc_entry);
1309                 break;
1310         case COMPOSE_BCC:
1311                 entry = GTK_ENTRY(compose->bcc_entry);
1312                 break;
1313         case COMPOSE_NEWSGROUPS:
1314                 entry = GTK_ENTRY(compose->newsgroups_entry);
1315                 break;
1316         case COMPOSE_TO:
1317         default:
1318                 entry = GTK_ENTRY(compose->to_entry);
1319                 break;
1320         }
1321
1322         text = gtk_entry_get_text(entry);
1323         if (*text != '\0')
1324                 gtk_entry_append_text(entry, ", ");
1325         gtk_entry_append_text(entry, address);
1326 #endif
1327
1328         switch (type) {
1329         case COMPOSE_CC:
1330                 header = N_("Cc:");
1331                 break;
1332         case COMPOSE_BCC:
1333                 header = N_("Bcc:");
1334                 break;
1335         case COMPOSE_REPLYTO:
1336                 header = N_("Reply-To:");
1337                 break;
1338         case COMPOSE_NEWSGROUPS:
1339                 header = N_("Newsgroups:");
1340                 break;
1341         case COMPOSE_FOLLOWUPTO:
1342                 header = N_( "Followup-To:");
1343                 break;
1344         case COMPOSE_TO:
1345         default:
1346                 header = N_("To:");
1347                 break;
1348         }
1349         header = prefs_common.trans_hdr ? gettext(header) : header;
1350
1351         compose_add_header_entry(compose, header, (gchar *)address);
1352 }
1353
1354 static void compose_entries_set(Compose *compose, const gchar *mailto)
1355 {
1356         gchar *subject = NULL;
1357         gchar *to = NULL;
1358         gchar *cc = NULL;
1359         gchar *bcc = NULL;
1360         gchar *body = NULL;
1361         gchar *p;
1362         gchar *tmp_mailto;
1363
1364         Xstrdup_a(tmp_mailto, mailto, return);
1365
1366         to = tmp_mailto;
1367
1368         p = strchr(tmp_mailto, '?');
1369         if (p) {
1370                 *p = '\0';
1371                 p++;
1372         }
1373
1374         while (p) {
1375                 gchar *field, *value;
1376
1377                 field = p;
1378
1379                 p = strchr(p, '=');
1380                 if (!p) break;
1381                 *p = '\0';
1382                 p++;
1383
1384                 value = p;
1385
1386                 p = strchr(p, '&');
1387                 if (p) {
1388                         *p = '\0';
1389                         p++;
1390                 }
1391
1392                 if (*value == '\0') continue;
1393
1394                 if (!g_strcasecmp(field, "subject")) {
1395                         Xalloca(subject, strlen(value) + 1, return);
1396                         decode_uri(subject, value);
1397                 } else if (!g_strcasecmp(field, "cc")) {
1398                         cc = value;
1399                 } else if (!g_strcasecmp(field, "bcc")) {
1400                         bcc = value;
1401                 } else if (!g_strcasecmp(field, "body")) {
1402                         Xalloca(body, strlen(value) + 1, return);
1403                         decode_uri(body, value);
1404                 }
1405         }
1406
1407         if (to)
1408                 compose_entry_append(compose, to, COMPOSE_TO);
1409         if (subject)
1410                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1411         if (cc)
1412                 compose_entry_append(compose, cc, COMPOSE_CC);
1413         if (bcc)
1414                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1415         if (body) {
1416                 gtk_stext_insert(GTK_STEXT(compose->text),
1417                                 NULL, NULL, NULL, body, -1);
1418                 gtk_stext_insert(GTK_STEXT(compose->text),
1419                                 NULL, NULL, NULL, "\n", 1);
1420         }
1421 }
1422
1423 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1424 {
1425         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1426                                        {"Cc:",             NULL, FALSE},
1427                                        {"References:",     NULL, FALSE},
1428                                        {"Bcc:",            NULL, FALSE},
1429                                        {"Newsgroups:",     NULL, FALSE},
1430                                        {"Followup-To:",    NULL, FALSE},
1431                                        {"X-Mailing-List:", NULL, FALSE},
1432                                        {"X-BeenThere:",    NULL, FALSE},
1433                                        {"X-Priority:",     NULL, FALSE},
1434                                        {NULL,              NULL, FALSE}};
1435
1436         enum
1437         {
1438                 H_REPLY_TO       = 0,
1439                 H_CC             = 1,
1440                 H_REFERENCES     = 2,
1441                 H_BCC            = 3,
1442                 H_NEWSGROUPS     = 4,
1443                 H_FOLLOWUP_TO    = 5,
1444                 H_X_MAILING_LIST = 6,
1445                 H_X_BEENTHERE    = 7,
1446                 H_X_PRIORITY     = 8
1447         };
1448
1449         FILE *fp;
1450
1451         g_return_val_if_fail(msginfo != NULL, -1);
1452
1453         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1454         procheader_get_header_fields(fp, hentry);
1455         fclose(fp);
1456
1457         if (hentry[H_REPLY_TO].body != NULL) {
1458                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1459                 compose->replyto = hentry[H_REPLY_TO].body;
1460                 hentry[H_REPLY_TO].body = NULL;
1461         }
1462         if (hentry[H_CC].body != NULL) {
1463                 conv_unmime_header_overwrite(hentry[H_CC].body);
1464                 compose->cc = hentry[H_CC].body;
1465                 hentry[H_CC].body = NULL;
1466         }
1467         if (hentry[H_X_MAILING_LIST].body != NULL) {
1468                 /* this is good enough to parse debian-devel */
1469                 gchar *buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1470                 g_return_val_if_fail(buf != NULL, -1 );
1471                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1472                         compose->mailinglist = g_strdup(buf);
1473                 g_free(buf);
1474                 g_free(hentry[H_X_MAILING_LIST].body);
1475                 hentry[H_X_MAILING_LIST].body = NULL ;
1476         }
1477         if (hentry[H_X_BEENTHERE].body != NULL) {
1478                 /* this is good enough to parse the sylpheed-claws lists */
1479                 gchar *buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1480                 g_return_val_if_fail(buf != NULL, -1 );
1481                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1482                         compose->mailinglist = g_strdup(buf);
1483                 g_free(buf);
1484                 g_free(hentry[H_X_BEENTHERE].body);
1485                 hentry[H_X_BEENTHERE].body = NULL ;
1486         }
1487         if (hentry[H_REFERENCES].body != NULL) {
1488                 if (compose->mode == COMPOSE_REEDIT)
1489                         compose->references = hentry[H_REFERENCES].body;
1490                 else {
1491                         compose->references = compose_parse_references
1492                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1493                         g_free(hentry[H_REFERENCES].body);
1494                 }
1495                 hentry[H_REFERENCES].body = NULL;
1496         }
1497         if (hentry[H_BCC].body != NULL) {
1498                 if (compose->mode == COMPOSE_REEDIT) {
1499                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1500                         compose->bcc = hentry[H_BCC].body;
1501                 } else
1502                         g_free(hentry[H_BCC].body);
1503                 hentry[H_BCC].body = NULL;
1504         }
1505         if (hentry[H_NEWSGROUPS].body != NULL) {
1506                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1507                 hentry[H_NEWSGROUPS].body = NULL;
1508         }
1509         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1510                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1511                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1512                 hentry[H_FOLLOWUP_TO].body = NULL;
1513         }
1514
1515         if (compose->mode == COMPOSE_REEDIT)
1516                 if (hentry[H_X_PRIORITY].body != NULL) {
1517                         gint priority;
1518                         
1519                         priority = atoi(hentry[H_X_PRIORITY].body);
1520                         g_free(hentry[H_X_PRIORITY].body);
1521                         
1522                         hentry[H_X_PRIORITY].body = NULL;
1523                         
1524                         if (priority < PRIORITY_HIGHEST || 
1525                             priority > PRIORITY_LOWEST)
1526                                 priority = PRIORITY_NORMAL;
1527                         
1528                         compose->priority =  priority;
1529                 }
1530  
1531         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1532                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1533         else if (compose->mode != COMPOSE_REEDIT &&
1534                  msginfo->msgid && *msginfo->msgid) {
1535                 compose->inreplyto = g_strdup(msginfo->msgid);
1536
1537                 if (!compose->references) {
1538                         if (msginfo->inreplyto && *msginfo->inreplyto)
1539                                 compose->references =
1540                                         g_strdup_printf("<%s>\n\t<%s>",
1541                                                         msginfo->inreplyto,
1542                                                         msginfo->msgid);
1543                         else
1544                                 compose->references =
1545                                         g_strconcat("<", msginfo->msgid, ">",
1546                                                     NULL);
1547                 }
1548         }
1549
1550         return 0;
1551 }
1552
1553 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1554 {
1555         GSList *ref_id_list, *cur;
1556         GString *new_ref;
1557         gchar *new_ref_str;
1558
1559         ref_id_list = references_list_append(NULL, ref);
1560         if (!ref_id_list) return NULL;
1561         if (msgid && *msgid)
1562                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1563
1564         for (;;) {
1565                 gint len = 0;
1566
1567                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1568                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1569                         len += strlen((gchar *)cur->data) + 5;
1570
1571                 if (len > MAX_REFERENCES_LEN) {
1572                         /* remove second message-ID */
1573                         if (ref_id_list && ref_id_list->next &&
1574                             ref_id_list->next->next) {
1575                                 g_free(ref_id_list->next->data);
1576                                 ref_id_list = g_slist_remove
1577                                         (ref_id_list, ref_id_list->next->data);
1578                         } else {
1579                                 slist_free_strings(ref_id_list);
1580                                 g_slist_free(ref_id_list);
1581                                 return NULL;
1582                         }
1583                 } else
1584                         break;
1585         }
1586
1587         new_ref = g_string_new("");
1588         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1589                 if (new_ref->len > 0)
1590                         g_string_append(new_ref, "\n\t");
1591                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1592         }
1593
1594         slist_free_strings(ref_id_list);
1595         g_slist_free(ref_id_list);
1596
1597         new_ref_str = new_ref->str;
1598         g_string_free(new_ref, FALSE);
1599
1600         return new_ref_str;
1601 }
1602
1603 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1604                                 const gchar *fmt, const gchar *qmark,
1605                                 const gchar *body)
1606 {
1607         GtkSText *text = GTK_STEXT(compose->text);
1608         gchar *quote_str = NULL;
1609         gchar *buf;
1610         gchar *p, *lastp;
1611         gint len;
1612
1613         if (qmark != NULL) {
1614                 quote_fmt_init(msginfo, NULL, NULL);
1615                 quote_fmt_scan_string(qmark);
1616                 quote_fmt_parse();
1617
1618                 buf = quote_fmt_get_buffer();
1619                 if (buf == NULL)
1620                         alertpanel_error(_("Quote mark format error."));
1621                 else
1622                         Xstrdup_a(quote_str, buf, return NULL)
1623         }
1624
1625         if (fmt && *fmt != '\0') {
1626                 quote_fmt_init(msginfo, quote_str, body);
1627                 quote_fmt_scan_string(fmt);
1628                 quote_fmt_parse();
1629
1630                 buf = quote_fmt_get_buffer();
1631                 if (buf == NULL) {
1632                         alertpanel_error(_("Message reply/forward format error."));
1633                         return NULL;
1634                 }
1635         } else
1636                 buf = "";
1637
1638         gtk_stext_freeze(text);
1639
1640         for (p = buf; *p != '\0'; ) {
1641                 lastp = strchr(p, '\n');
1642                 len = lastp ? lastp - p + 1 : -1;
1643                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1644                 if (lastp)
1645                         p = lastp + 1;
1646                 else
1647                         break;
1648         }
1649
1650         gtk_stext_thaw(text);
1651
1652         return buf;
1653 }
1654
1655 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1656                                     gboolean to_all, gboolean ignore_replyto,
1657                                     gboolean followup_and_reply_to)
1658 {
1659         GSList *cc_list = NULL;
1660         GSList *cur;
1661         gchar *from = NULL;
1662         gchar *replyto = NULL;
1663         GHashTable *to_table;
1664
1665         g_return_if_fail(compose->account != NULL);
1666         g_return_if_fail(msginfo != NULL);
1667
1668         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1669                 compose_entry_append(compose,
1670                                     ((compose->replyto && !ignore_replyto)
1671                                      ? compose->replyto
1672                                      : (compose->mailinglist && !ignore_replyto)
1673                                      ? compose->mailinglist
1674                                      : msginfo->from ? msginfo->from : ""),
1675                                      COMPOSE_TO);
1676
1677         if (compose->account->protocol == A_NNTP) {
1678                 if (ignore_replyto)
1679                         compose_entry_append
1680                                 (compose, msginfo->from ? msginfo->from : "",
1681                                  COMPOSE_TO);
1682                 else
1683                         compose_entry_append
1684                                 (compose,
1685                                  compose->followup_to ? compose->followup_to
1686                                  : compose->newsgroups ? compose->newsgroups
1687                                  : "",
1688                                  COMPOSE_NEWSGROUPS);
1689         }
1690
1691         if (msginfo->subject && *msginfo->subject) {
1692                 gchar *buf, *buf2, *p;
1693
1694                 buf = g_strdup(msginfo->subject);
1695                 while (!strncasecmp(buf, "Re:", 3)) {
1696                         p = buf + 3;
1697                         while (isspace(*p)) p++;
1698                         memmove(buf, p, strlen(p) + 1);
1699                 }
1700
1701                 buf2 = g_strdup_printf("Re: %s", buf);
1702                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1703                 g_free(buf2);
1704                 g_free(buf);
1705         } else
1706                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1707
1708         if (!to_all || compose->account->protocol == A_NNTP) return;
1709
1710         if (compose->replyto) {
1711                 Xstrdup_a(replyto, compose->replyto, return);
1712                 extract_address(replyto);
1713         }
1714         if (msginfo->from) {
1715                 Xstrdup_a(from, msginfo->from, return);
1716                 extract_address(from);
1717         }
1718
1719         if (compose->mailinglist && from) {
1720                 cc_list = address_list_append(cc_list, from);
1721         }
1722
1723         if (replyto && from)
1724                 cc_list = address_list_append(cc_list, from);
1725
1726         if (!compose->mailinglist)
1727                 cc_list = address_list_append(cc_list, msginfo->to);
1728
1729         cc_list = address_list_append(cc_list, compose->cc);
1730
1731         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1732         if (replyto)
1733                 g_hash_table_insert(to_table, replyto, GINT_TO_POINTER(1));
1734         if (compose->account)
1735                 g_hash_table_insert(to_table, compose->account->address,
1736                                     GINT_TO_POINTER(1));
1737
1738         /* remove address on To: and that of current account */
1739         for (cur = cc_list; cur != NULL; ) {
1740                 GSList *next = cur->next;
1741
1742                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1743                         cc_list = g_slist_remove(cc_list, cur->data);
1744                 else
1745                         g_hash_table_insert(to_table, cur->data, cur);
1746
1747                 cur = next;
1748         }
1749         g_hash_table_destroy(to_table);
1750
1751         if (cc_list) {
1752                 for (cur = cc_list; cur != NULL; cur = cur->next)
1753                         compose_entry_append(compose, (gchar *)cur->data,
1754                                              COMPOSE_CC);
1755                 slist_free_strings(cc_list);
1756                 g_slist_free(cc_list);
1757         }
1758 }
1759
1760 #define SET_ENTRY(entry, str) \
1761 { \
1762         if (str && *str) \
1763                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1764 }
1765
1766 #define SET_ADDRESS(type, str) \
1767 { \
1768         if (str && *str) \
1769                 compose_entry_append(compose, str, type); \
1770 }
1771
1772 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1773 {
1774         g_return_if_fail(msginfo != NULL);
1775
1776         SET_ENTRY(subject_entry, msginfo->subject);
1777         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1778         SET_ADDRESS(COMPOSE_CC, compose->cc);
1779         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1780         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1781
1782         compose_update_priority_menu_item(compose);
1783
1784         compose_show_first_last_header(compose, TRUE);
1785
1786 #if 0 /* NEW COMPOSE GUI */
1787         if (compose->bcc) {
1788                 GtkItemFactory *ifactory;
1789                 GtkWidget *menuitem;
1790
1791                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1792                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Bcc");
1793                 gtk_check_menu_item_set_active
1794                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1795         }
1796         if (compose->replyto) {
1797                 GtkItemFactory *ifactory;
1798                 GtkWidget *menuitem;
1799
1800                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1801                 menuitem = gtk_item_factory_get_item
1802                         (ifactory, "/View/Reply to");
1803                 gtk_check_menu_item_set_active
1804                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1805         }
1806 #endif
1807 }
1808
1809 #undef SET_ENTRY
1810 #undef SET_ADDRESS
1811
1812 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1813 {
1814         FILE *tmpfp;
1815         pid_t thepid;
1816         gchar *sigtext;
1817         FILE  *sigprg;
1818         gchar  *buf;
1819         size_t buf_len = 128;
1820  
1821         if (strlen(sigfile) < 2)
1822           return;
1823  
1824         sigprg = popen(sigfile+1, "r");
1825         if (sigprg) {
1826
1827                 buf = g_malloc(buf_len);
1828
1829                 if (!buf) {
1830                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1831                         "Unable to insert signature (malloc failed)\n", -1);
1832
1833                         pclose(sigprg);
1834                         return;
1835                 }
1836
1837                 while (!feof(sigprg)) {
1838                         bzero(buf, buf_len);
1839                         fread(buf, buf_len-1, 1, sigprg);
1840                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1841                 }
1842
1843                 g_free(buf);
1844                 pclose(sigprg);
1845         }
1846         else
1847         {
1848                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1849                 "Can't exec file: ", -1);
1850                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1851                 sigfile+1, -1);
1852         }
1853 }
1854
1855 static void compose_insert_sig(Compose *compose)
1856 {
1857         gchar *sigfile;
1858
1859         if (compose->account && compose->account->sig_path)
1860                 sigfile = g_strdup(compose->account->sig_path);
1861         else
1862                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1863                                       DEFAULT_SIGNATURE, NULL);
1864
1865         if (!is_file_or_fifo_exist(sigfile) && sigfile[0] != '|') {
1866                 g_free(sigfile);
1867                 return;
1868         }
1869
1870         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1871         if (prefs_common.sig_sep) {
1872                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1873                                 prefs_common.sig_sep, -1);
1874                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1875                                 "\n", 1);
1876         }
1877
1878         if (sigfile[0] == '|')
1879                 compose_exec_sig(compose, sigfile);
1880         else
1881                 compose_insert_file(compose, sigfile);
1882         g_free(sigfile);
1883 }
1884
1885 static void compose_insert_file(Compose *compose, const gchar *file)
1886 {
1887         GtkSText *text = GTK_STEXT(compose->text);
1888         gchar buf[BUFFSIZE];
1889         gint len;
1890         FILE *fp;
1891
1892         g_return_if_fail(file != NULL);
1893
1894         if ((fp = fopen(file, "rb")) == NULL) {
1895                 FILE_OP_ERROR(file, "fopen");
1896                 return;
1897         }
1898
1899         gtk_stext_freeze(text);
1900
1901         while (fgets(buf, sizeof(buf), fp) != NULL) {
1902                 /* strip <CR> if DOS/Windows file,
1903                    replace <CR> with <LF> if Macintosh file. */
1904                 strcrchomp(buf);
1905                 len = strlen(buf);
1906                 if (len > 0 && buf[len - 1] != '\n') {
1907                         while (--len >= 0)
1908                                 if (buf[len] == '\r') buf[len] = '\n';
1909                 }
1910                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1911         }
1912
1913         gtk_stext_thaw(text);
1914
1915         fclose(fp);
1916 }
1917
1918 static void compose_attach_append(Compose *compose, const gchar *file,
1919                                   const gchar *filename,
1920                                   const gchar *content_type)
1921 {
1922         AttachInfo *ainfo;
1923         gchar *text[N_ATTACH_COLS];
1924         FILE *fp;
1925         off_t size;
1926         gint row;
1927
1928         if (!is_file_exist(file)) {
1929                 g_warning(_("File %s doesn't exist\n"), file);
1930                 return;
1931         }
1932         if ((size = get_file_size(file)) < 0) {
1933                 g_warning(_("Can't get file size of %s\n"), file);
1934                 return;
1935         }
1936         if (size == 0) {
1937                 alertpanel_notice(_("File %s is empty."), file);
1938                 return;
1939         }
1940         if ((fp = fopen(file, "rb")) == NULL) {
1941                 alertpanel_error(_("Can't read %s."), file);
1942                 return;
1943         }
1944         fclose(fp);
1945
1946 #if 0 /* NEW COMPOSE GUI */
1947         if (!compose->use_attach) {
1948                 GtkItemFactory *ifactory;
1949                 GtkWidget *menuitem;
1950
1951                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1952                 menuitem = gtk_item_factory_get_item(ifactory,
1953                                                      "/View/Attachment");
1954                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1955                                                TRUE);
1956         }
1957 #endif
1958         ainfo = g_new0(AttachInfo, 1);
1959         ainfo->file = g_strdup(file);
1960
1961         if (content_type) {
1962                 ainfo->content_type = g_strdup(content_type);
1963                 if (!strcasecmp(content_type, "message/rfc822")) {
1964                         ainfo->encoding = ENC_7BIT;
1965                         ainfo->name = g_strdup_printf
1966                                 (_("Message: %s"),
1967                                  g_basename(filename ? filename : file));
1968                 } else {
1969                         if (!g_strncasecmp(content_type, "text", 4))
1970                                 ainfo->encoding =
1971                                         procmime_get_encoding_for_file(file);
1972                         else
1973                                 ainfo->encoding = ENC_BASE64;
1974                         ainfo->name = g_strdup
1975                                 (g_basename(filename ? filename : file));
1976                 }
1977         } else {
1978                 ainfo->content_type = procmime_get_mime_type(file);
1979                 if (!ainfo->content_type) {
1980                         ainfo->content_type =
1981                                 g_strdup("application/octet-stream");
1982                         ainfo->encoding = ENC_BASE64;
1983                 } else if (!g_strncasecmp(ainfo->content_type, "text", 4))
1984                         ainfo->encoding = procmime_get_encoding_for_file(file);
1985                 else
1986                         ainfo->encoding = ENC_BASE64;
1987                 ainfo->name = g_strdup(g_basename(filename ? filename : file)); 
1988         }
1989         ainfo->size = size;
1990
1991         text[COL_MIMETYPE] = ainfo->content_type;
1992         text[COL_SIZE] = to_human_readable(size);
1993         text[COL_NAME] = ainfo->name;
1994
1995         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1996         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1997 }
1998
1999 #define IS_FIRST_PART_TEXT(info) \
2000         ((info->mime_type == MIME_TEXT || info->mime_type == MIME_TEXT_HTML || \
2001           info->mime_type == MIME_TEXT_ENRICHED) || \
2002          (info->mime_type == MIME_MULTIPART && info->content_type && \
2003           !strcasecmp(info->content_type, "multipart/alternative") && \
2004           (info->children && \
2005            (info->children->mime_type == MIME_TEXT || \
2006             info->children->mime_type == MIME_TEXT_HTML || \
2007             info->children->mime_type == MIME_TEXT_ENRICHED))))
2008
2009 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2010 {
2011         MimeInfo *mimeinfo;
2012         MimeInfo *child;
2013         gchar *infile;
2014         gchar *outfile;
2015
2016         mimeinfo = procmime_scan_message(msginfo);
2017         if (!mimeinfo) return;
2018
2019         /* skip first text (presumably message body) */
2020         child = mimeinfo->children;
2021         if (!child || IS_FIRST_PART_TEXT(mimeinfo)) {
2022                 procmime_mimeinfo_free_all(mimeinfo);
2023                 return;
2024         }
2025         if (IS_FIRST_PART_TEXT(child))
2026                 child = child->next;
2027
2028         infile = procmsg_get_message_file_path(msginfo);
2029
2030         while (child != NULL) {
2031                 if (child->children || child->mime_type == MIME_MULTIPART) {
2032                         child = procmime_mimeinfo_next(child);
2033                         continue;
2034                 }
2035
2036                 outfile = procmime_get_tmp_file_name(child);
2037                 if (procmime_get_part(outfile, infile, child) < 0)
2038                         g_warning(_("Can't get the part of multipart message."));
2039                 else
2040                         compose_attach_append
2041                                 (compose, outfile,
2042                                  child->filename ? child->filename : child->name,
2043                                  child->content_type);
2044
2045                 child = child->next;
2046         }
2047
2048         g_free(infile);
2049         procmime_mimeinfo_free_all(mimeinfo);
2050 }
2051
2052 #undef IS_FIRST_PART_TEXT
2053
2054 #define GET_CHAR(pos, buf, len)                                              \
2055 {                                                                            \
2056         if (text->use_wchar)                                                 \
2057                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));    \
2058         else {                                                               \
2059                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
2060                 len = 1;                                                     \
2061         }                                                                    \
2062 }
2063
2064 #define INDENT_CHARS    ">|#"
2065 #define SPACE_CHARS     " \t"
2066
2067 static void compose_wrap_line(Compose *compose)
2068 {
2069         GtkSText *text = GTK_STEXT(compose->text);
2070         gint ch_len, last_ch_len;
2071         gchar cbuf[MB_LEN_MAX], last_ch;
2072         guint text_len;
2073         guint line_end;
2074         guint quoted;
2075         gint p_start, p_end;
2076         gint line_pos, cur_pos;
2077         gint line_len, cur_len;
2078
2079         gtk_stext_freeze(text);
2080
2081         text_len = gtk_stext_get_length(text);
2082
2083         /* check to see if the point is on the paragraph mark (empty line). */
2084         cur_pos = gtk_stext_get_point(text);
2085         GET_CHAR(cur_pos, cbuf, ch_len);
2086         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2087                 if (cur_pos == 0)
2088                         goto compose_end; /* on the paragraph mark */
2089                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
2090                 if (ch_len == 1 && *cbuf == '\n')
2091                         goto compose_end; /* on the paragraph mark */
2092         }
2093
2094         /* find paragraph start. */
2095         line_end = quoted = 0;
2096         for (p_start = cur_pos; p_start >= 0; --p_start) {
2097                 GET_CHAR(p_start, cbuf, ch_len);
2098                 if (ch_len == 1 && *cbuf == '\n') {
2099                         if (quoted)
2100                                 goto compose_end; /* quoted part */
2101                         if (line_end) {
2102                                 p_start += 2;
2103                                 break;
2104                         }
2105                         line_end = 1;
2106                 } else {
2107                         if (ch_len == 1 
2108                             && strchr(prefs_common.quote_chars, *cbuf))
2109                                 quoted = 1;
2110                         else if (ch_len != 1 || !isspace(*cbuf))
2111                                 quoted = 0;
2112
2113                         line_end = 0;
2114                 }
2115         }
2116         if (p_start < 0)
2117                 p_start = 0;
2118
2119         /* find paragraph end. */
2120         line_end = 0;
2121         for (p_end = cur_pos; p_end < text_len; p_end++) {
2122                 GET_CHAR(p_end, cbuf, ch_len);
2123                 if (ch_len == 1 && *cbuf == '\n') {
2124                         if (line_end) {
2125                                 p_end -= 1;
2126                                 break;
2127                         }
2128                         line_end = 1;
2129                 } else {
2130                         if (line_end && ch_len == 1 &&
2131                             strchr(prefs_common.quote_chars, *cbuf))
2132                                 goto compose_end; /* quoted part */
2133
2134                         line_end = 0;
2135                 }
2136         }
2137         if (p_end >= text_len)
2138                 p_end = text_len;
2139
2140         if (p_start >= p_end)
2141                 goto compose_end;
2142
2143         line_len = cur_len = 0;
2144         last_ch_len = 0;
2145         last_ch = '\0';
2146         line_pos = p_start;
2147         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2148                 guint space = 0;
2149
2150                 GET_CHAR(cur_pos, cbuf, ch_len);
2151
2152                 if (ch_len < 0) {
2153                         cbuf[0] = '\0';
2154                         ch_len = 1;
2155                 }
2156
2157                 if (ch_len == 1 && isspace(*cbuf))
2158                         space = 1;
2159
2160                 if (ch_len == 1 && *cbuf == '\n') {
2161                         guint replace = 0;
2162                         if (last_ch_len == 1 && !isspace(last_ch)) {
2163                                 if (cur_pos + 1 < p_end) {
2164                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2165                                         if (ch_len == 1 && !isspace(*cbuf))
2166                                                 replace = 1;
2167                                 }
2168                         }
2169                         gtk_stext_set_point(text, cur_pos + 1);
2170                         gtk_stext_backward_delete(text, 1);
2171                         if (replace) {
2172                                 gtk_stext_set_point(text, cur_pos);
2173                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2174                                 space = 1;
2175                         }
2176                         else {
2177                                 p_end--;
2178                                 cur_pos--;
2179                                 continue;
2180                         }
2181                 }
2182
2183                 last_ch_len = ch_len;
2184                 last_ch = *cbuf;
2185
2186                 if (space) {
2187                         line_pos = cur_pos + 1;
2188                         line_len = cur_len + ch_len;
2189                 }
2190
2191                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2192                     line_len > 0) {
2193                         gint tlen = ch_len;
2194
2195                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2196                         if (ch_len == 1 && isspace(*cbuf)) {
2197                                 gtk_stext_set_point(text, line_pos);
2198                                 gtk_stext_backward_delete(text, 1);
2199                                 p_end--;
2200                                 cur_pos--;
2201                                 line_pos--;
2202                                 cur_len--;
2203                                 line_len--;
2204                         }
2205                         ch_len = tlen;
2206
2207                         gtk_stext_set_point(text, line_pos);
2208                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2209                         p_end++;
2210                         cur_pos++;
2211                         line_pos++;
2212                         cur_len = cur_len - line_len + ch_len;
2213                         line_len = 0;
2214                         continue;
2215                 }
2216
2217                 if (ch_len > 1) {
2218                         line_pos = cur_pos + 1;
2219                         line_len = cur_len + ch_len;
2220                 }
2221                 cur_len += ch_len;
2222         }
2223
2224 compose_end:
2225         gtk_stext_thaw(text);
2226 }
2227
2228 #undef WRAP_DEBUG
2229 #ifdef WRAP_DEBUG
2230 /* Darko: used when I debug wrapping */
2231 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2232 {
2233         gint i;
2234         gchar ch;
2235
2236         printf("%d [", pos);
2237         for (i = pos; i < tlen; i++) {
2238                 ch = GTK_STEXT_INDEX(text, i);
2239                 if (breakoncr && ch == '\n')
2240                         break;
2241                 printf("%c", ch);
2242         }
2243         printf("]\n");
2244 }
2245 #endif
2246
2247 typedef enum {
2248         WAIT_FOR_SPACE,
2249         WAIT_FOR_INDENT_CHAR,
2250         WAIT_FOR_INDENT_CHAR_OR_SPACE
2251 } IndentState;
2252
2253 /* return indent length, we allow:
2254    > followed by spaces/tabs
2255    | followed by spaces/tabs
2256    uppercase characters immediately followed by >,
2257    and the repeating sequences of the above */
2258 /* return indent length */
2259 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2260 {
2261         guint i_len = 0;
2262         guint i, ch_len, alnum_cnt = 0;
2263         IndentState state = WAIT_FOR_INDENT_CHAR;
2264         gchar cbuf[MB_LEN_MAX];
2265         gboolean is_space;
2266         gboolean is_indent;
2267
2268         for (i = start_pos; i < text_len; i++) {
2269                 GET_CHAR(i, cbuf, ch_len);
2270                 if (ch_len > 1)
2271                         break;
2272
2273                 if (cbuf[0] == '\n')
2274                         break;
2275
2276                 is_indent = strchr(prefs_common.quote_chars, cbuf[0]) ? TRUE : FALSE;
2277                 is_space = strchr(SPACE_CHARS, cbuf[0]) ? TRUE : FALSE;
2278
2279                 switch (state) {
2280                 case WAIT_FOR_SPACE:
2281                         if (is_space == FALSE)
2282                                 goto out;
2283                         state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2284                         break;
2285                 case WAIT_FOR_INDENT_CHAR_OR_SPACE:
2286                         if (is_indent == FALSE && is_space == FALSE &&
2287                             !isupper(cbuf[0]))
2288                                 goto out;
2289                         if (is_space == TRUE) {
2290                                 alnum_cnt = 0;
2291                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2292                         } else if (is_indent == TRUE) {
2293                                 alnum_cnt = 0;
2294                                 state = WAIT_FOR_SPACE;
2295                         } else {
2296                                 alnum_cnt++;
2297                                 state = WAIT_FOR_INDENT_CHAR;
2298                         }
2299                         break;
2300                 case WAIT_FOR_INDENT_CHAR:
2301                         if (is_indent == FALSE && !isupper(cbuf[0]))
2302                                 goto out;
2303                         if (is_indent == TRUE) {
2304                                 if (alnum_cnt > 0 
2305                                     && !strchr(prefs_common.quote_chars, cbuf[0]))
2306                                         goto out;
2307                                 alnum_cnt = 0;
2308                                 state = WAIT_FOR_SPACE;
2309                         } else {
2310                                 alnum_cnt++;
2311                         }
2312                         break;
2313                 }
2314
2315                 i_len++;
2316         }
2317
2318 out:
2319         if ((i_len > 0) && (state == WAIT_FOR_INDENT_CHAR))
2320                 i_len -= alnum_cnt;
2321
2322         return i_len;
2323 }
2324
2325 /* insert quotation string when line was wrapped */
2326 static guint ins_quote(GtkSText *text, guint indent_len,
2327                        guint prev_line_pos, guint text_len,
2328                        gchar *quote_fmt)
2329 {
2330         guint i, ins_len;
2331         gchar ch;
2332
2333         if (indent_len) {
2334                 for (i = 0; i < indent_len; i++) {
2335                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2336                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2337                 }
2338                 ins_len = indent_len;
2339         }
2340
2341         return ins_len;
2342 }
2343
2344 /* check if we should join the next line */
2345 static gboolean join_next_line(GtkSText *text, guint start_pos, guint tlen,
2346                                guint prev_ilen)
2347 {
2348         guint indent_len, ch_len;
2349         gboolean do_join = FALSE;
2350         gchar cbuf[MB_LEN_MAX];
2351
2352         indent_len = get_indent_length(text, start_pos, tlen);
2353
2354         if ((indent_len > 0) && (indent_len == prev_ilen)) {
2355                 GET_CHAR(start_pos + indent_len, cbuf, ch_len);
2356                 if (ch_len > 0 && (cbuf[0] != '\n'))
2357                         do_join = TRUE;
2358         }
2359
2360         return do_join;
2361 }
2362
2363 static void compose_wrap_line_all(Compose *compose)
2364 {
2365         GtkSText *text = GTK_STEXT(compose->text);
2366         guint tlen;
2367         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2368         gint line_len = 0, cur_len = 0;
2369         gint ch_len;
2370         gboolean is_new_line = TRUE, do_delete = FALSE;
2371         guint i_len = 0;
2372         gboolean linewrap_quote = TRUE;
2373         guint linewrap_len = prefs_common.linewrap_len;
2374         gchar *qfmt = prefs_common.quotemark;
2375         gchar cbuf[MB_LEN_MAX];
2376
2377         gtk_stext_freeze(text);
2378
2379         /* make text buffer contiguous */
2380         /* gtk_stext_compact_buffer(text); */
2381
2382         tlen = gtk_stext_get_length(text);
2383
2384         for (; cur_pos < tlen; cur_pos++) {
2385                 /* mark position of new line - needed for quotation wrap */
2386                 if (is_new_line) {
2387                         if (linewrap_quote)
2388                                 i_len = get_indent_length(text, cur_pos, tlen);
2389
2390                         is_new_line = FALSE;
2391                         p_pos = cur_pos;
2392 #ifdef WRAP_DEBUG
2393                         printf("new line i_len=%d p_pos=", i_len);
2394                         dump_text(text, p_pos, tlen, 1);
2395 #endif
2396                 }
2397
2398                 GET_CHAR(cur_pos, cbuf, ch_len);
2399
2400                 /* fix line length for tabs */
2401                 if (ch_len == 1 && *cbuf == '\t') {
2402                         guint tab_width = text->default_tab_width;
2403                         guint tab_offset = line_len % tab_width;
2404
2405 #ifdef WRAP_DEBUG
2406                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2407                                 line_len);
2408 #endif
2409                         if (tab_offset) {
2410                                 line_len += tab_width - tab_offset - 1;
2411                                 cur_len = line_len;
2412                         }
2413 #ifdef WRAP_DEBUG
2414                         printf("new_len=%d\n", line_len);
2415 #endif
2416                 }
2417
2418                 /* we have encountered line break */
2419                 if (ch_len == 1 && *cbuf == '\n') {
2420                         gint clen;
2421                         gchar cb[MB_CUR_MAX];
2422
2423                         /* should we join the next line */
2424                         if ((i_len != cur_len) && do_delete &&
2425                             join_next_line(text, cur_pos + 1, tlen, i_len))
2426                                 do_delete = TRUE;
2427                         else
2428                                 do_delete = FALSE;
2429
2430 #ifdef WRAP_DEBUG
2431                         printf("found CR at %d do_del is %d next line is ",
2432                                cur_pos, do_delete);
2433                         dump_text(text, cur_pos + 1, tlen, 1);
2434 #endif
2435
2436                         /* skip delete if it is continuous URL */
2437                         if (do_delete && (line_pos - p_pos <= i_len) &&
2438                             gtkut_stext_is_uri_string(text, line_pos, tlen))
2439                                 do_delete = FALSE;
2440
2441 #ifdef WRAP_DEBUG
2442                         printf("l_len=%d wrap_len=%d do_del=%d\n",
2443                                 line_len, linewrap_len, do_delete);
2444 #endif
2445                         /* should we delete to perform smart wrapping */
2446                         if (line_len < linewrap_len && do_delete) {
2447                                 /* get rid of newline */
2448                                 gtk_stext_set_point(text, cur_pos);
2449                                 gtk_stext_forward_delete(text, 1);
2450                                 tlen--;
2451
2452                                 /* if text starts with quote fmt or with
2453                                    indent string, delete them */
2454                                 if (i_len) {
2455                                         guint ilen;
2456                                         ilen =  gtkut_stext_str_compare_n
2457                                                 (text, cur_pos, p_pos, i_len,
2458                                                  tlen);
2459                                         if (ilen) {
2460                                                 gtk_stext_forward_delete
2461                                                         (text, ilen);
2462                                                 tlen -= ilen;
2463                                         }
2464                                 }
2465
2466                                 GET_CHAR(cur_pos, cb, clen);
2467
2468                                 /* insert space if it's alphanumeric */
2469                                 if ((cur_pos != line_pos) &&
2470                                     ((clen > 1) || isalnum(cb[0]))) {
2471                                         gtk_stext_insert(text, NULL, NULL,
2472                                                         NULL, " ", 1);
2473                                         /* gtk_stext_compact_buffer(text); */
2474                                         tlen++;
2475                                 }
2476
2477                                 /* and start over with current line */
2478                                 cur_pos = p_pos - 1;
2479                                 line_pos = cur_pos;
2480                                 line_len = cur_len = 0;
2481                                 do_delete = FALSE;
2482                                 is_new_line = TRUE;
2483 #ifdef WRAP_DEBUG
2484                                 printf("after delete l_pos=");
2485                                 dump_text(text, line_pos, tlen, 1);
2486 #endif
2487                                 continue;
2488                         }
2489
2490                         /* mark new line beginning */
2491                         line_pos = cur_pos + 1;
2492                         line_len = cur_len = 0;
2493                         do_delete = FALSE;
2494                         is_new_line = TRUE;
2495                         continue;
2496                 }
2497
2498                 if (ch_len < 0) {
2499                         cbuf[0] = '\0';
2500                         ch_len = 1;
2501                 }
2502
2503                 /* possible line break */
2504                 if (ch_len == 1 && isspace(*cbuf)) {
2505                         line_pos = cur_pos + 1;
2506                         line_len = cur_len + ch_len;
2507                 }
2508
2509                 /* are we over wrapping length set in preferences ? */
2510                 if (cur_len + ch_len > linewrap_len) {
2511                         gint clen;
2512
2513 #ifdef WRAP_DEBUG
2514                         printf("should wrap cur_pos=%d ", cur_pos);
2515                         dump_text(text, p_pos, tlen, 1);
2516                         dump_text(text, line_pos, tlen, 1);
2517 #endif
2518                         /* force wrapping if it is one long word but not URL */
2519                         if (line_pos - p_pos <= i_len)
2520                                 if (!gtkut_stext_is_uri_string
2521                                     (text, line_pos, tlen))
2522                                         line_pos = cur_pos - 1;
2523 #ifdef WRAP_DEBUG
2524                         printf("new line_pos=%d\n", line_pos);
2525 #endif
2526
2527                         GET_CHAR(line_pos - 1, cbuf, clen);
2528
2529                         /* if next character is space delete it */
2530                         if (clen == 1 && isspace(*cbuf)) {
2531                                 if (p_pos + i_len != line_pos ||
2532                                     !gtkut_stext_is_uri_string
2533                                         (text, line_pos, tlen)) {
2534                                         gtk_stext_set_point(text, line_pos);
2535                                         gtk_stext_backward_delete(text, 1);
2536                                         tlen--;
2537                                         cur_pos--;
2538                                         line_pos--;
2539                                         cur_len--;
2540                                         line_len--;
2541                                 }
2542                         }
2543
2544                         /* if it is URL at beginning of line don't wrap */
2545                         if (p_pos + i_len == line_pos &&
2546                             gtkut_stext_is_uri_string(text, line_pos, tlen)) {
2547 #ifdef WRAP_DEBUG
2548                                 printf("found URL at ");
2549                                 dump_text(text, line_pos, tlen, 1);
2550 #endif
2551                                 continue;
2552                         }
2553
2554                         /* insert CR */
2555                         gtk_stext_set_point(text, line_pos);
2556                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2557                         /* gtk_stext_compact_buffer(text); */
2558                         tlen++;
2559                         line_pos++;
2560                         /* for loop will increase it */
2561                         cur_pos = line_pos - 1;
2562                         /* start over with current line */
2563                         is_new_line = TRUE;
2564                         line_len = 0;
2565                         cur_len = 0;
2566                         if (i_len)
2567                                 do_delete = TRUE;
2568                         else
2569                                 do_delete = FALSE;
2570 #ifdef WRAP_DEBUG
2571                         printf("after CR insert ");
2572                         dump_text(text, line_pos, tlen, 1);
2573                         dump_text(text, cur_pos, tlen, 1);
2574 #endif
2575
2576                         /* should we insert quotation ? */
2577                         if (linewrap_quote && i_len) {
2578                                 /* only if line is not already quoted  */
2579                                 if (!gtkut_stext_str_compare
2580                                         (text, line_pos, tlen, qfmt)) {
2581                                         guint ins_len;
2582
2583                                         if (line_pos - p_pos > i_len) {
2584                                                 ins_len = ins_quote
2585                                                         (text, i_len, p_pos,
2586                                                          tlen, qfmt);
2587
2588                                                 /* gtk_stext_compact_buffer(text); */
2589                                                 tlen += ins_len;
2590                                         }
2591 #ifdef WRAP_DEBUG
2592                                         printf("after quote insert ");
2593                                         dump_text(text, line_pos, tlen, 1);
2594 #endif
2595                                 }
2596                         }
2597                         continue;
2598                 }
2599
2600                 if (ch_len > 1) {
2601                         line_pos = cur_pos + 1;
2602                         line_len = cur_len + ch_len;
2603                 }
2604                 /* advance to next character in buffer */
2605                 cur_len += ch_len;
2606         }
2607
2608         gtk_stext_thaw(text);
2609 }
2610
2611 #undef GET_CHAR
2612
2613 static void compose_set_title(Compose *compose)
2614 {
2615         gchar *str;
2616         gchar *edited;
2617
2618         edited = compose->modified ? _(" [Edited]") : "";
2619         if (compose->account && compose->account->address)
2620                 str = g_strdup_printf(_("%s - Compose message%s"),
2621                                       compose->account->address, edited);
2622         else
2623                 str = g_strdup_printf(_("Compose message%s"), edited);
2624         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2625         g_free(str);
2626 }
2627
2628 /**
2629  * compose_current_mail_account:
2630  * 
2631  * Find a current mail account (the currently selected account, or the
2632  * default account, if a news account is currently selected).  If a
2633  * mail account cannot be found, display an error message.
2634  * 
2635  * Return value: Mail account, or NULL if not found.
2636  **/
2637 static PrefsAccount *
2638 compose_current_mail_account(void)
2639 {
2640         PrefsAccount *ac;
2641
2642         if (cur_account && cur_account->protocol != A_NNTP)
2643                 ac = cur_account;
2644         else {
2645                 ac = account_get_default();
2646                 if (!ac || ac->protocol == A_NNTP) {
2647                         alertpanel_error(_("Account for sending mail is not specified.\n"
2648                                            "Please select a mail account before sending."));
2649                         return NULL;
2650                 }
2651         }
2652         return ac;
2653 }
2654
2655 gboolean compose_check_for_valid_recipient(Compose *compose) {
2656         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2657         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2658         gboolean recipient_found = FALSE;
2659         GSList *list;
2660         gchar **strptr;
2661
2662         /* free to and newsgroup list */
2663         slist_free_strings(compose->to_list);
2664         g_slist_free(compose->to_list);
2665         compose->to_list = NULL;
2666                         
2667         slist_free_strings(compose->newsgroup_list);
2668         g_slist_free(compose->newsgroup_list);
2669         compose->newsgroup_list = NULL;
2670
2671         /* search header entries for to and newsgroup entries */
2672         for(list = compose->header_list; list; list = list->next) {
2673                 gchar *header;
2674                 gchar *entry;
2675                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry));
2676                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2677                 g_strstrip(entry);
2678                 if(entry[0] != '\0') {
2679                         for(strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2680                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2681                                         compose->to_list = address_list_append(compose->to_list, entry);
2682                                         recipient_found = TRUE;
2683                                 }
2684                         }
2685                         for(strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2686                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2687                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2688                                         recipient_found = TRUE;
2689                                 }
2690                         }
2691                 }
2692                 g_free(entry);
2693         }
2694         return recipient_found;
2695 }
2696
2697 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
2698 {
2699         gchar *str;
2700
2701         if (compose_check_for_valid_recipient(compose) == FALSE) {
2702                 alertpanel_error(_("Recipient is not specified."));
2703                 return FALSE;
2704         }
2705
2706         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2707         if (*str == '\0' && check_subject == TRUE) {
2708                 AlertValue aval;
2709
2710                 aval = alertpanel(_("Send"),
2711                                   _("Subject is empty. Send it anyway?"),
2712                                   _("Yes"), _("No"), NULL);
2713                 if (aval != G_ALERTDEFAULT)
2714                         return FALSE;
2715         }
2716
2717         return TRUE;
2718 }
2719
2720 gint compose_send(Compose *compose)
2721 {
2722         gint msgnum;
2723         FolderItem *folder;
2724         gint val;
2725
2726         if (compose_check_entries(compose, TRUE) == FALSE)
2727                 return -1;
2728
2729         val = compose_queue(compose, &msgnum, &folder);
2730         if (val) {
2731                 alertpanel_error(_("Could not queue message for sending"));
2732                 return -1;
2733         }
2734         
2735         val = procmsg_send_message_queue(folder_item_fetch_msg(folder, msgnum));
2736
2737         folder_item_remove_msg(folder, msgnum);
2738         folderview_update_item(folder, TRUE);
2739
2740         return val;
2741 }
2742
2743 #if 0 /* compose restructure */
2744 gint compose_send(Compose *compose)
2745 {
2746         gchar tmp[MAXPATHLEN + 1];
2747         gint ok = 0;
2748         static gboolean lock = FALSE;
2749
2750         if (lock) return 1;
2751
2752         g_return_val_if_fail(compose->account != NULL, -1);
2753         g_return_val_if_fail(compose->orig_account != NULL, -1);
2754
2755         lock = TRUE;
2756
2757         if (compose_check_entries(compose, TRUE) == FALSE) {
2758                 lock = FALSE;
2759                 return 1;
2760         }
2761
2762         /* write to temporary file */
2763         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2764                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2765
2766         if (prefs_common.linewrap_at_send)
2767                 compose_wrap_line_all(compose);
2768
2769         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2770                 lock = FALSE;
2771                 return -1;
2772         }
2773
2774         if (!compose->to_list && !compose->newsgroup_list) {
2775                 g_warning(_("can't get recipient list."));
2776                 unlink(tmp);
2777                 lock = FALSE;
2778                 return -1;
2779         }
2780
2781         if (compose->to_list) {
2782                 PrefsAccount *ac;
2783
2784 #if 0 /* NEW COMPOSE GUI */
2785                 if (compose->account->protocol != A_NNTP)
2786                         ac = compose->account;
2787                 else if (compose->orig_account->protocol != A_NNTP)
2788                         ac = compose->orig_account;
2789                 else if (cur_account && cur_account->protocol != A_NNTP)
2790                         ac = cur_account;
2791                 else {
2792                         ac = compose_current_mail_account();
2793                         if (!ac) {
2794                                 unlink(tmp);
2795                                 lock = FALSE;
2796                                 return -1;
2797                         }
2798                 }
2799 #endif
2800                 ac = compose->account;
2801
2802                 ok = send_message(tmp, ac, compose->to_list);
2803                 statusbar_pop_all();
2804         }
2805
2806         if (ok == 0 && compose->newsgroup_list) {
2807                 Folder *folder;
2808
2809                 if (compose->account->protocol == A_NNTP)
2810                         folder = FOLDER(compose->account->folder);
2811                 else
2812                         folder = FOLDER(compose->orig_account->folder);
2813
2814                 ok = news_post(folder, tmp);
2815                 if (ok < 0) {
2816                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2817                                          compose->account->nntp_server);
2818                         unlink(tmp);
2819                         lock = FALSE;
2820                         return -1;
2821                 }
2822         }
2823
2824         /* queue message if failed to send */
2825         if (ok < 0) {
2826                 if (prefs_common.queue_msg) {
2827                         AlertValue val;
2828
2829                         val = alertpanel
2830                                 (_("Queueing"),
2831                                  _("Error occurred while sending the message.\n"
2832                                    "Put this message into queue folder?"),
2833                                  _("OK"), _("Cancel"), NULL);
2834                         if (G_ALERTDEFAULT == val) {
2835                                 ok = compose_queue(compose, tmp);
2836                                 if (ok < 0)
2837                                         alertpanel_error(_("Can't queue the message."));
2838                         }
2839                 } else
2840                         alertpanel_error(_("Error occurred while sending the message."));
2841         } else {
2842                 if (compose->mode == COMPOSE_REEDIT) {
2843                         compose_remove_reedit_target(compose);
2844                         if (compose->targetinfo)
2845                                 folderview_update_item
2846                                         (compose->targetinfo->folder, TRUE);
2847                 }
2848                 /* save message to outbox */
2849                 if (prefs_common.savemsg) {
2850                         FolderItem *outbox;
2851
2852                         outbox = account_get_special_folder
2853                                 (compose->account, F_OUTBOX);
2854                         if (procmsg_save_to_outbox(outbox, tmp, FALSE) < 0)
2855                                 alertpanel_error
2856                                         (_("Can't save the message to Sent."));
2857                         else
2858                                 folderview_update_item(outbox, TRUE);
2859                 }
2860         }
2861
2862         unlink(tmp);
2863         lock = FALSE;
2864         return ok;
2865 }
2866 #endif
2867
2868 static gboolean compose_use_attach(Compose *compose) {
2869     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2870 }
2871
2872 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
2873                                                            FILE *fp)
2874 {
2875         gchar buf[BUFFSIZE];
2876         gchar *str;
2877         gboolean first_address;
2878         GSList *list;
2879         ComposeHeaderEntry *headerentry;
2880         gchar *headerentryname;
2881         gchar *cc_hdr;
2882         gchar *to_hdr;
2883
2884         debug_print(_("Writing redirect header\n"));
2885
2886         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
2887         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
2888
2889         first_address = TRUE;
2890         for(list = compose->header_list; list; list = list->next) {
2891                 headerentry = ((ComposeHeaderEntry *)list->data);
2892                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
2893
2894                 if(g_strcasecmp(headerentryname, cc_hdr) == 0 
2895                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
2896                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
2897                         Xstrdup_a(str, str, return -1);
2898                         g_strstrip(str);
2899                         if(str[0] != '\0') {
2900                                 compose_convert_header
2901                                         (buf, sizeof(buf), str,
2902                                         strlen("Resent-To") + 2);
2903                                 if(first_address) {
2904                                         fprintf(fp, "Resent-To: ");
2905                                         first_address = FALSE;
2906                                 } else {
2907                                         fprintf(fp, ",");
2908                                 }
2909                                 fprintf(fp, "%s", buf);
2910                         }
2911                 }
2912         }
2913         /* if(!first_address) { */
2914         fprintf(fp, "\n");
2915         /* } */
2916
2917         return(0);
2918 }
2919
2920 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
2921 {
2922         gchar buf[BUFFSIZE];
2923         gchar *str;
2924         /* struct utsname utsbuf; */
2925
2926         g_return_val_if_fail(fp != NULL, -1);
2927         g_return_val_if_fail(compose->account != NULL, -1);
2928         g_return_val_if_fail(compose->account->address != NULL, -1);
2929
2930         /* Resent-Date */
2931         get_rfc822_date(buf, sizeof(buf));
2932         fprintf(fp, "Resent-Date: %s\n", buf);
2933
2934         /* Resent-From */
2935         if (compose->account->name && *compose->account->name) {
2936                 compose_convert_header
2937                         (buf, sizeof(buf), compose->account->name,
2938                          strlen("From: "));
2939                 fprintf(fp, "Resent-From: %s <%s>\n",
2940                         buf, compose->account->address);
2941         } else
2942                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
2943
2944         /* Subject */
2945         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2946         if (*str != '\0') {
2947                 Xstrdup_a(str, str, return -1);
2948                 g_strstrip(str);
2949                 if (*str != '\0') {
2950                         compose_convert_header(buf, sizeof(buf), str,
2951                                                strlen("Subject: "));
2952                         fprintf(fp, "Subject: %s\n", buf);
2953                 }
2954         }
2955
2956         /* Resent-Message-ID */
2957         if (compose->account->gen_msgid) {
2958                 compose_generate_msgid(compose, buf, sizeof(buf));
2959                 fprintf(fp, "Resent-Message-Id: <%s>\n", buf);
2960                 compose->msgid = g_strdup(buf);
2961         }
2962
2963         compose_redirect_write_headers_from_headerlist(compose, fp);
2964
2965         /* separator between header and body */
2966         fputs("\n", fp);
2967
2968         return 0;
2969 }
2970
2971 static gint compose_redirect_write_to_file(Compose *compose, const gchar *file)
2972 {
2973         FILE *fp;
2974         FILE *fdest;
2975         size_t len;
2976         gchar buf[BUFFSIZE];
2977
2978         if ((fp = fopen(compose->redirect_filename, "rb")) == NULL) {
2979                 FILE_OP_ERROR(file, "fopen");
2980                 return -1;
2981         }
2982
2983         if ((fdest = fopen(file, "wb")) == NULL) {
2984                 FILE_OP_ERROR(file, "fopen");
2985                 fclose(fp);
2986                 return -1;
2987         }
2988
2989         /* chmod for security */
2990         if (change_file_mode_rw(fdest, file) < 0) {
2991                 FILE_OP_ERROR(file, "chmod");
2992                 g_warning(_("can't change file mode\n"));
2993         }
2994
2995         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
2996                 /* should filter returnpath, delivered-to */
2997                 if (g_strncasecmp(buf, "Return-Path:",
2998                                    strlen("Return-Path:")) == 0 ||
2999                     g_strncasecmp(buf, "Delivered-To:",
3000                                   strlen("Delivered-To:")) == 0 ||
3001                     g_strncasecmp(buf, "Received:",
3002                                   strlen("Received:")) == 0 ||
3003                     g_strncasecmp(buf, "Subject:",
3004                                   strlen("Subject:")) == 0 ||
3005                     g_strncasecmp(buf, "X-UIDL:",
3006                                   strlen("X-UIDL:")) == 0)
3007                         continue;
3008
3009                 if (fputs(buf, fdest) == -1)
3010                         goto error;
3011
3012                 if (!prefs_common.redirect_keep_from) {
3013                         if (g_strncasecmp(buf, "From:",
3014                                           strlen("From:")) == 0) {
3015                                 fputs(" (by way of ", fdest);
3016                                 if (compose->account->name
3017                                     && *compose->account->name) {
3018                                         compose_convert_header
3019                                                 (buf, sizeof(buf),
3020                                                  compose->account->name,
3021                                                  strlen("From: "));
3022                                         fprintf(fdest, "%s <%s>",
3023                                                 buf,
3024                                                 compose->account->address);
3025                                 } else
3026                                         fprintf(fdest, "%s",
3027                                                 compose->account->address);
3028                                 fputs(")", fdest);
3029                         }
3030                 }
3031
3032                 if (fputs("\n", fdest) == -1)
3033                         goto error;
3034         }
3035
3036         compose_redirect_write_headers(compose, fdest);
3037
3038         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3039                 if (fwrite(buf, sizeof(gchar), len, fdest) != len) {
3040                         FILE_OP_ERROR(file, "fwrite");
3041                         goto error;
3042                 }
3043         }
3044
3045         fclose(fp);
3046         if (fclose(fdest) == EOF) {
3047                 FILE_OP_ERROR(file, "fclose");
3048                 unlink(file);
3049                 return -1;
3050         }
3051
3052         return 0;
3053  error:
3054         fclose(fp);
3055         fclose(fdest);
3056         unlink(file);
3057
3058         return -1;
3059 }
3060
3061
3062 #ifdef USE_GPGME
3063 /*
3064  * interfaces to rfc2015 to keep out the prefs stuff there.
3065  * returns 0 on success and -1 on error. */
3066 static int compose_create_signers_list (Compose *compose, GSList **pkey_list)
3067 {
3068         const char *keyid = NULL;
3069         GSList *key_list;
3070
3071         switch (compose->account->sign_key) {
3072         case SIGN_KEY_DEFAULT:
3073                 *pkey_list = NULL;
3074                 return 0;               /* nothing to do */
3075
3076         case SIGN_KEY_BY_FROM:
3077                 keyid = compose->account->address;
3078                 break;
3079
3080         case SIGN_KEY_CUSTOM:
3081                 keyid = compose->account->sign_key_id;
3082                 break;
3083
3084         default:
3085                 g_assert_not_reached ();
3086         }
3087
3088         key_list = rfc2015_create_signers_list(keyid);
3089
3090         if (!key_list) {
3091             alertpanel_error("Could not find any key associated with currently "
3092                                 "selected keyid `%s'!", keyid);
3093             return -1;
3094         }
3095         
3096         *pkey_list = key_list;
3097         return 0;
3098 }
3099 #endif /* USE_GPGME */
3100
3101 static gint compose_write_to_file(Compose *compose, const gchar *file,
3102                                   gboolean is_draft)
3103 {
3104         FILE *fp;
3105         size_t len;
3106         gchar *chars;
3107         gchar *buf;
3108         const gchar *out_codeset;
3109         EncodingType encoding;
3110
3111         if ((fp = fopen(file, "wb")) == NULL) {
3112                 FILE_OP_ERROR(file, "fopen");
3113                 return -1;
3114         }
3115
3116         /* chmod for security */
3117         if (change_file_mode_rw(fp, file) < 0) {
3118                 FILE_OP_ERROR(file, "chmod");
3119                 g_warning(_("can't change file mode\n"));
3120         }
3121
3122         /* get all composed text */
3123         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3124         len = strlen(chars);
3125         if (is_ascii_str(chars)) {
3126                 buf = g_strdup(chars);
3127                 out_codeset = CS_US_ASCII;
3128                 encoding = ENC_7BIT;
3129         } else {
3130                 const gchar *src_codeset;
3131
3132                 out_codeset = conv_get_outgoing_charset_str();
3133                 if (!strcasecmp(out_codeset, CS_US_ASCII))
3134                         out_codeset = CS_ISO_8859_1;
3135                 encoding = procmime_get_encoding_for_charset(out_codeset);
3136
3137                 src_codeset = conv_get_current_charset_str();
3138                 /* if current encoding is US-ASCII, set it the same as
3139                    outgoing one to prevent code conversion failure */
3140                 if (!strcasecmp(src_codeset, CS_US_ASCII))
3141                         src_codeset = out_codeset;
3142
3143                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3144                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3145
3146                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3147                 if (!buf) {
3148                         AlertValue aval;
3149
3150                         aval = alertpanel
3151                                 (_("Error"),
3152                                  _("Can't convert the character encoding of the message.\n"
3153                                    "Send it anyway?"), _("Yes"), _("+No"), NULL);
3154                         if (aval != G_ALERTDEFAULT) {
3155                                 g_free(chars);
3156                                 fclose(fp);
3157                                 unlink(file);
3158                                 return -1;
3159                         } else {
3160                                 buf = g_strdup(chars);
3161                         }
3162                 }
3163         }
3164         g_free(chars);
3165
3166         /* write headers */
3167         if (compose_write_headers
3168                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
3169                 g_warning(_("can't write headers\n"));
3170                 fclose(fp);
3171                 /* unlink(file); */
3172                 g_free(buf);
3173                 return -1;
3174         }
3175
3176         if (compose_use_attach(compose)) {
3177 #if USE_GPGME
3178             /* This prolog message is ignored by mime software and
3179              * because it would make our signing/encryption task
3180              * tougher, we don't emit it in that case */
3181             if (!compose->use_signing && !compose->use_encryption)
3182 #endif
3183                 fputs("This is a multi-part message in MIME format.\n", fp);
3184
3185                 fprintf(fp, "\n--%s\n", compose->boundary);
3186                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
3187                         out_codeset);
3188                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3189                         procmime_get_encoding_str(encoding));
3190                 fputc('\n', fp);
3191         }
3192
3193         /* write body */
3194         len = strlen(buf);
3195         if (encoding == ENC_BASE64) {
3196                 gchar outbuf[B64_BUFFSIZE];
3197                 gint i, l;
3198
3199                 for (i = 0; i < len; i += B64_LINE_SIZE) {
3200                         l = MIN(B64_LINE_SIZE, len - i);
3201                         to64frombits(outbuf, buf + i, l);
3202                         fputs(outbuf, fp);
3203                         fputc('\n', fp);
3204                 }
3205         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
3206                 FILE_OP_ERROR(file, "fwrite");
3207                 fclose(fp);
3208                 unlink(file);
3209                 g_free(buf);
3210                 return -1;
3211         }
3212         g_free(buf);
3213
3214         if (compose_use_attach(compose))
3215                 compose_write_attach(compose, fp);
3216
3217         if (fclose(fp) == EOF) {
3218                 FILE_OP_ERROR(file, "fclose");
3219                 unlink(file);
3220                 return -1;
3221         }
3222
3223 #if USE_GPGME
3224         if (compose->use_signing) {
3225                 GSList *key_list;
3226                 
3227