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