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