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