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