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