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