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