2005-09-18 [colin] 1.9.14cvs39
[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 void compose_create_tags(GtkTextView *text, Compose *compose)
789 {
790         GtkTextBuffer *buffer;
791         GdkColor black = {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
792
793         buffer = gtk_text_view_get_buffer(text);
794         
795         if (prefs_common.enable_color) {
796                 /* grab the quote colors, converting from an int to a GdkColor */
797                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
798                                                &quote_color);
799                 gtkut_convert_int_to_gdk_color(prefs_common.signature_col,
800                                                &signature_color);
801                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
802                                                &uri_color);
803         } else {
804                 signature_color = quote_color = uri_color = black;
805         }
806
807         gtk_text_buffer_create_tag(buffer, "quote",
808                                    "foreground-gdk", &quote_color,
809                                    NULL);
810         gtk_text_buffer_create_tag(buffer, "signature",
811                                    "foreground-gdk", &signature_color,
812                                    NULL);
813         gtk_text_buffer_create_tag(buffer, "link",
814                                          "foreground-gdk", &uri_color,
815                                          NULL);
816         compose->no_wrap_tag = gtk_text_buffer_create_tag(buffer, "no_wrap", NULL);
817 }
818
819 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
820                      GPtrArray *attach_files)
821 {
822         return compose_generic_new(account, mailto, NULL, attach_files, NULL);
823 }
824
825 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
826 {
827         return compose_generic_new(account, NULL, item, NULL, NULL);
828 }
829
830 Compose *compose_new_with_list( PrefsAccount *account, GList *listAddress )
831 {
832         return compose_generic_new( account, NULL, NULL, NULL, listAddress );
833 }
834
835 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
836                              GPtrArray *attach_files, GList *listAddress )
837 {
838         Compose *compose;
839         GtkTextView *textview;
840         GtkTextBuffer *textbuf;
841         GtkTextIter iter;
842         GtkItemFactory *ifactory;
843
844         if (item && item->prefs && item->prefs->enable_default_account)
845                 account = account_find_from_id(item->prefs->default_account);
846
847         if (!account) account = cur_account;
848         g_return_val_if_fail(account != NULL, NULL);
849
850         compose = compose_create(account, COMPOSE_NEW);
851         ifactory = gtk_item_factory_from_widget(compose->menubar);
852
853         compose->replyinfo = NULL;
854         compose->fwdinfo   = NULL;
855
856         textview = GTK_TEXT_VIEW(compose->text);
857         textbuf = gtk_text_view_get_buffer(textview);
858         compose_create_tags(textview, compose);
859
860         undo_block(compose->undostruct);
861 #ifdef USE_ASPELL
862         if (item && item->prefs && item->prefs->enable_default_dictionary &&
863             compose->gtkaspell) 
864                 gtkaspell_change_dict(compose->gtkaspell, 
865                     item->prefs->default_dictionary);
866 #endif
867
868         if (account->auto_sig)
869                 compose_insert_sig(compose, FALSE);
870         gtk_text_buffer_get_start_iter(textbuf, &iter);
871         gtk_text_buffer_place_cursor(textbuf, &iter);
872
873         if (account->protocol != A_NNTP) {
874                 if (mailto && *mailto != '\0') {
875                         compose_entries_set(compose, mailto);
876
877                 } else if (item && item->prefs->enable_default_to) {
878                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
879                         compose_entry_mark_default_to(compose, item->prefs->default_to);
880                 }
881                 if (item && item->ret_rcpt) {
882                         menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
883                 }
884         } else {
885                 if (mailto) {
886                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
887                 }
888                 /*
889                  * CLAWS: just don't allow return receipt request, even if the user
890                  * may want to send an email. simple but foolproof.
891                  */
892                 menu_set_sensitive(ifactory, "/Options/Request Return Receipt", FALSE); 
893         }
894         compose_add_field_list( compose, listAddress );
895
896         if (attach_files) {
897                 gint i;
898                 gchar *file;
899
900                 for (i = 0; i < attach_files->len; i++) {
901                         file = g_ptr_array_index(attach_files, i);
902                         compose_attach_append(compose, file, file, NULL);
903                 }
904         }
905
906         compose_show_first_last_header(compose, TRUE);
907
908         /* Set save folder */
909         if (item && item->prefs && item->prefs->save_copy_to_folder) {
910                 gchar *folderidentifier;
911
912                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
913                 folderidentifier = folder_item_get_identifier(item);
914                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
915                 g_free(folderidentifier);
916         }
917         
918         gtk_widget_grab_focus(compose->header_last->entry);
919
920         undo_unblock(compose->undostruct);
921
922         if (prefs_common.auto_exteditor)
923                 compose_exec_ext_editor(compose);
924
925         return compose;
926 }
927
928 static void compose_force_encryption(Compose *compose, PrefsAccount *account,
929                 gboolean override_pref)
930 {
931         gchar *privacy = NULL;
932
933         if (override_pref == FALSE && account->default_encrypt_reply == FALSE)
934                 return;
935
936         if (account->default_privacy_system
937         &&  strlen(account->default_privacy_system)) {
938                 privacy = account->default_privacy_system;
939         } else {
940                 GSList *privacy_avail = privacy_get_system_ids();
941                 if (privacy_avail && g_slist_length(privacy_avail)) {
942                         privacy = (gchar *)(privacy_avail->data);
943                 }
944         }
945         if (privacy != NULL) {
946                 compose->privacy_system = g_strdup(privacy);
947                 compose_update_privacy_system_menu_item(compose);
948                 compose_use_encryption(compose, TRUE);
949         }
950 }       
951
952 static void compose_force_signing(Compose *compose, PrefsAccount *account)
953 {
954         gchar *privacy = NULL;
955
956         if (account->default_privacy_system
957         &&  strlen(account->default_privacy_system)) {
958                 privacy = account->default_privacy_system;
959         } else {
960                 GSList *privacy_avail = privacy_get_system_ids();
961                 if (privacy_avail && g_slist_length(privacy_avail)) {
962                         privacy = (gchar *)(privacy_avail->data);
963                 }
964         }
965         if (privacy != NULL) {
966                 compose->privacy_system = g_strdup(privacy);
967                 compose_update_privacy_system_menu_item(compose);
968                 compose_use_signing(compose, TRUE);
969         }
970 }       
971
972 void compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
973 {
974         MsgInfo *msginfo;
975         guint list_len;
976
977         g_return_if_fail(msginfo_list != NULL);
978
979         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
980         g_return_if_fail(msginfo != NULL);
981
982         list_len = g_slist_length(msginfo_list);
983
984         switch (mode) {
985         case COMPOSE_REPLY:
986                 compose_reply(msginfo, prefs_common.reply_with_quote,
987                               FALSE, prefs_common.default_reply_list, FALSE, body);
988                 break;
989         case COMPOSE_REPLY_WITH_QUOTE:
990                 compose_reply(msginfo, TRUE, FALSE, prefs_common.default_reply_list, FALSE, body);
991                 break;
992         case COMPOSE_REPLY_WITHOUT_QUOTE:
993                 compose_reply(msginfo, FALSE, FALSE, prefs_common.default_reply_list, FALSE, NULL);
994                 break;
995         case COMPOSE_REPLY_TO_SENDER:
996                 compose_reply(msginfo, prefs_common.reply_with_quote,
997                               FALSE, FALSE, TRUE, body);
998                 break;
999         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
1000                 compose_followup_and_reply_to(msginfo,
1001                                               prefs_common.reply_with_quote,
1002                                               FALSE, FALSE, body);
1003                 break;
1004         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
1005                 compose_reply(msginfo, TRUE, FALSE, FALSE, TRUE, body);
1006                 break;
1007         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
1008                 compose_reply(msginfo, FALSE, FALSE, FALSE, TRUE, NULL);
1009                 break;
1010         case COMPOSE_REPLY_TO_ALL:
1011                 compose_reply(msginfo, prefs_common.reply_with_quote,
1012                               TRUE, FALSE, FALSE, body);
1013                 break;
1014         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
1015                 compose_reply(msginfo, TRUE, TRUE, FALSE, FALSE, body);
1016                 break;
1017         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
1018                 compose_reply(msginfo, FALSE, TRUE, FALSE, FALSE, NULL);
1019                 break;
1020         case COMPOSE_REPLY_TO_LIST:
1021                 compose_reply(msginfo, prefs_common.reply_with_quote,
1022                               FALSE, TRUE, FALSE, body);
1023                 break;
1024         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
1025                 compose_reply(msginfo, TRUE, FALSE, TRUE, FALSE, body);
1026                 break;
1027         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
1028                 compose_reply(msginfo, FALSE, FALSE, TRUE, FALSE, NULL);
1029                 break;
1030         case COMPOSE_FORWARD:
1031                 if (prefs_common.forward_as_attachment) {
1032                         compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
1033                         return;
1034                 } else {
1035                         compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
1036                         return;
1037                 }
1038                 break;
1039         case COMPOSE_FORWARD_INLINE:
1040                 /* check if we reply to more than one Message */
1041                 if (list_len == 1) {
1042                         compose_forward(NULL, msginfo, FALSE, body, FALSE);
1043                         break;
1044                 } 
1045                 /* more messages FALL THROUGH */
1046         case COMPOSE_FORWARD_AS_ATTACH:
1047                 compose_forward_multiple(NULL, msginfo_list);
1048                 break;
1049         case COMPOSE_REDIRECT:
1050                 compose_redirect(NULL, msginfo);
1051                 break;
1052         default:
1053                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
1054         }
1055 }
1056
1057 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
1058                    gboolean to_ml, gboolean to_sender, 
1059                    const gchar *body)
1060 {
1061         compose_generic_reply(msginfo, quote, to_all, to_ml, 
1062                               to_sender, FALSE, body);
1063 }
1064
1065 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
1066                                    gboolean to_all,
1067                                    gboolean to_sender,
1068                                    const gchar *body)
1069 {
1070         compose_generic_reply(msginfo, quote, to_all, FALSE, 
1071                               to_sender, TRUE, body);
1072 }
1073
1074 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
1075                                   gboolean to_all, gboolean to_ml,
1076                                   gboolean to_sender,
1077                                   gboolean followup_and_reply_to,
1078                                   const gchar *body)
1079 {
1080         GtkItemFactory *ifactory;
1081         Compose *compose;
1082         PrefsAccount *account = NULL;
1083         PrefsAccount *reply_account;
1084         GtkTextView *textview;
1085         GtkTextBuffer *textbuf;
1086         GtkTextIter iter;
1087         int cursor_pos;
1088
1089         g_return_if_fail(msginfo != NULL);
1090         g_return_if_fail(msginfo->folder != NULL);
1091
1092         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
1093         
1094         g_return_if_fail(account != NULL);
1095
1096         if (to_sender && account->protocol == A_NNTP &&
1097             !followup_and_reply_to) {
1098                 reply_account =
1099                         account_find_from_address(account->address);
1100                 if (!reply_account)
1101                         reply_account = compose_current_mail_account();
1102                 if (!reply_account)
1103                         return;
1104         } else
1105                 reply_account = account;
1106
1107         compose = compose_create(account, COMPOSE_REPLY);
1108         ifactory = gtk_item_factory_from_widget(compose->menubar);
1109
1110         menu_set_active(ifactory, "/Options/Remove references", FALSE);
1111         menu_set_sensitive(ifactory, "/Options/Remove references", TRUE);
1112
1113         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
1114         if (!compose->replyinfo)
1115                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
1116
1117         if (msginfo->folder && msginfo->folder->ret_rcpt)
1118                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1119
1120         /* Set save folder */
1121         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1122                 gchar *folderidentifier;
1123
1124                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1125                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1126                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1127                 g_free(folderidentifier);
1128         }
1129
1130         if (compose_parse_header(compose, msginfo) < 0) return;
1131         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
1132                                 to_sender, followup_and_reply_to);
1133         compose_show_first_last_header(compose, TRUE);
1134
1135         textview = (GTK_TEXT_VIEW(compose->text));
1136         textbuf = gtk_text_view_get_buffer(textview);
1137         compose_create_tags(textview, compose);
1138
1139         undo_block(compose->undostruct);
1140 #ifdef USE_ASPELL
1141         if (msginfo->folder && msginfo->folder->prefs && 
1142             msginfo->folder->prefs && 
1143             msginfo->folder->prefs->enable_default_dictionary &&
1144             compose->gtkaspell)
1145                 gtkaspell_change_dict(compose->gtkaspell, 
1146                     msginfo->folder->prefs->default_dictionary);
1147 #endif
1148
1149         if (quote) {
1150                 gchar *qmark;
1151
1152                 if (prefs_common.quotemark && *prefs_common.quotemark)
1153                         qmark = prefs_common.quotemark;
1154                 else
1155                         qmark = "> ";
1156
1157                 compose_quote_fmt(compose, compose->replyinfo,
1158                                   prefs_common.quotefmt,
1159                                   qmark, body);
1160         }
1161         if (procmime_msginfo_is_encrypted(compose->replyinfo)) {
1162                 compose_force_encryption(compose, account, FALSE);
1163         }
1164
1165         if (account->auto_sig)
1166                 compose_insert_sig(compose, FALSE);
1167
1168         cursor_pos = quote_fmt_get_cursor_pos();
1169         gtk_text_buffer_get_start_iter(textbuf, &iter);
1170         gtk_text_buffer_get_iter_at_offset(textbuf, &iter, cursor_pos);
1171         gtk_text_buffer_place_cursor(textbuf, &iter);
1172         
1173         compose_wrap_all(compose);
1174
1175         gtk_widget_grab_focus(compose->text);
1176
1177         undo_unblock(compose->undostruct);
1178
1179         if (prefs_common.auto_exteditor)
1180                 compose_exec_ext_editor(compose);
1181 }
1182
1183 #define INSERT_FW_HEADER(var, hdr) \
1184 if (msginfo->var && *msginfo->var) { \
1185         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1186         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1187         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1188 }
1189
1190 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1191                          gboolean as_attach, const gchar *body,
1192                          gboolean no_extedit)
1193 {
1194         Compose *compose;
1195         GtkTextView *textview;
1196         GtkTextBuffer *textbuf;
1197         GtkTextIter iter;
1198
1199         g_return_val_if_fail(msginfo != NULL, NULL);
1200         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1201
1202         if (!account && 
1203             !(account = compose_guess_forward_account_from_msginfo
1204                                 (msginfo)))
1205                 account = cur_account;
1206
1207         compose = compose_create(account, COMPOSE_FORWARD);
1208
1209         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1210         if (!compose->fwdinfo)
1211                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1212
1213         if (msginfo->subject && *msginfo->subject) {
1214                 gchar *buf, *buf2, *p;
1215
1216                 buf = p = g_strdup(msginfo->subject);
1217                 p += subject_get_prefix_length(p);
1218                 memmove(buf, p, strlen(p) + 1);
1219
1220                 buf2 = g_strdup_printf("Fw: %s", buf);
1221                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1222                 
1223                 g_free(buf);
1224                 g_free(buf2);
1225         }
1226
1227         textview = GTK_TEXT_VIEW(compose->text);
1228         textbuf = gtk_text_view_get_buffer(textview);
1229         compose_create_tags(textview, compose);
1230
1231         if (as_attach) {
1232                 gchar *msgfile;
1233
1234                 msgfile = procmsg_get_message_file_path(msginfo);
1235                 if (!is_file_exist(msgfile))
1236                         g_warning("%s: file not exist\n", msgfile);
1237                 else
1238                         compose_attach_append(compose, msgfile, msgfile,
1239                                               "message/rfc822");
1240
1241                 g_free(msgfile);
1242         } else {
1243                 gchar *qmark;
1244                 MsgInfo *full_msginfo;
1245
1246                 full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1247                 if (!full_msginfo)
1248                         full_msginfo = procmsg_msginfo_copy(msginfo);
1249
1250                 if (prefs_common.fw_quotemark &&
1251                     *prefs_common.fw_quotemark)
1252                         qmark = prefs_common.fw_quotemark;
1253                 else
1254                         qmark = "> ";
1255
1256                 compose_quote_fmt(compose, full_msginfo,
1257                                   prefs_common.fw_quotefmt,
1258                                   qmark, body);
1259                 compose_attach_parts(compose, msginfo);
1260
1261                 procmsg_msginfo_free(full_msginfo);
1262         }
1263
1264         if (account->auto_sig)
1265                 compose_insert_sig(compose, FALSE);
1266
1267         compose_wrap_all(compose);
1268
1269         gtk_text_buffer_get_start_iter(textbuf, &iter);
1270         gtk_text_buffer_place_cursor(textbuf, &iter);
1271
1272         gtk_widget_grab_focus(compose->header_last->entry);
1273
1274         if (!no_extedit && prefs_common.auto_exteditor)
1275                 compose_exec_ext_editor(compose);
1276         
1277         /*save folder*/
1278         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1279                 gchar *folderidentifier;
1280
1281                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1282                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1283                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1284                 g_free(folderidentifier);
1285         }
1286
1287         return compose;
1288 }
1289
1290 #undef INSERT_FW_HEADER
1291
1292 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1293 {
1294         Compose *compose;
1295         GtkTextView *textview;
1296         GtkTextBuffer *textbuf;
1297         GtkTextIter iter;
1298         GSList *msginfo;
1299         gchar *msgfile;
1300
1301         g_return_val_if_fail(msginfo_list != NULL, NULL);
1302
1303         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next)
1304                 if (((MsgInfo *)msginfo->data)->folder == NULL)
1305                         return NULL;
1306
1307         /* guess account from first selected message */
1308         if (!account && 
1309             !(account = compose_guess_forward_account_from_msginfo
1310                                 (msginfo_list->data)))
1311                 account = cur_account;
1312
1313         g_return_val_if_fail(account != NULL, NULL);
1314
1315         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1316                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1317                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1318         }
1319
1320         compose = compose_create(account, COMPOSE_FORWARD);
1321
1322         textview = GTK_TEXT_VIEW(compose->text);
1323         textbuf = gtk_text_view_get_buffer(textview);
1324         compose_create_tags(textview, compose);
1325
1326         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1327                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1328                 if (!is_file_exist(msgfile))
1329                         g_warning("%s: file not exist\n", msgfile);
1330                 else
1331                         compose_attach_append(compose, msgfile, msgfile,
1332                                 "message/rfc822");
1333                 g_free(msgfile);
1334         }
1335
1336         if (account->auto_sig)
1337                 compose_insert_sig(compose, FALSE);
1338
1339         compose_wrap_all(compose);
1340
1341         gtk_text_buffer_get_start_iter(textbuf, &iter);
1342         gtk_text_buffer_place_cursor(textbuf, &iter);
1343
1344         gtk_widget_grab_focus(compose->header_last->entry);
1345         
1346         return compose;
1347 }
1348
1349 static gboolean compose_is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, GtkTextIter *iter) 
1350 {
1351         GtkTextIter start = *iter;
1352         GtkTextIter end_iter;
1353         int start_pos = gtk_text_iter_get_offset(&start);
1354
1355         if (!compose->account->sig_sep)
1356                 return FALSE;
1357         
1358         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1359                 start_pos+strlen(compose->account->sig_sep));
1360
1361         /* check sig separator */
1362         if (!strcmp(gtk_text_iter_get_text(&start, &end_iter),
1363                         compose->account->sig_sep)) {
1364                 /* check end of line (\n) */
1365                 gtk_text_buffer_get_iter_at_offset(textbuf, &start,
1366                         start_pos+strlen(compose->account->sig_sep));
1367                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1368                         start_pos+strlen(compose->account->sig_sep)+1);
1369
1370                 if (!strcmp(gtk_text_iter_get_text(&start, &end_iter),"\n"));
1371                         return TRUE;
1372                 
1373
1374         }
1375
1376         return FALSE;
1377 }
1378
1379 static void compose_colorize_signature(Compose *compose)
1380 {
1381         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
1382         GtkTextIter iter;
1383         GtkTextIter end_iter;
1384         gtk_text_buffer_get_start_iter(buffer, &iter);
1385         while (gtk_text_iter_forward_line(&iter))
1386                 if (compose_is_sig_separator(compose, buffer, &iter)) {
1387                         gtk_text_buffer_get_end_iter(buffer, &end_iter);
1388                         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &end_iter);
1389                 }
1390 }
1391
1392 void compose_reedit(MsgInfo *msginfo)
1393 {
1394         Compose *compose = NULL;
1395         PrefsAccount *account = NULL;
1396         GtkTextView *textview;
1397         GtkTextBuffer *textbuf;
1398         GtkTextMark *mark;
1399         GtkTextIter iter;
1400         FILE *fp;
1401         gchar buf[BUFFSIZE];
1402         gboolean use_signing = FALSE;
1403         gboolean use_encryption = FALSE;
1404         gchar *privacy_system = NULL;
1405
1406         g_return_if_fail(msginfo != NULL);
1407         g_return_if_fail(msginfo->folder != NULL);
1408
1409         if (compose_put_existing_to_front(msginfo)) 
1410                 return;
1411
1412         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1413             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1414                 gchar queueheader_buf[BUFFSIZE];
1415                 gint id, param;
1416
1417                 /* Select Account from queue headers */
1418                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1419                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1420                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1421                         account = account_find_from_id(id);
1422                 }
1423                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1424                                              sizeof(queueheader_buf), "NAID:")) {
1425                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1426                         account = account_find_from_id(id);
1427                 }
1428                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1429                                                     sizeof(queueheader_buf), "MAID:")) {
1430                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1431                         account = account_find_from_id(id);
1432                 }
1433                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1434                                                                 sizeof(queueheader_buf), "S:")) {
1435                         account = account_find_from_address(queueheader_buf);
1436                 }
1437                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1438                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1439                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1440                         use_signing = param;
1441                         
1442                 }
1443                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1444                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1445                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1446                         use_encryption = param;
1447                 }
1448                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1449                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1450                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1451                 }
1452                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1453                                              sizeof(queueheader_buf), "X-Priority: ")) {
1454                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1455                         compose->priority = param;
1456                 }
1457         } else 
1458                 account = msginfo->folder->folder->account;
1459
1460         if (!account && prefs_common.reedit_account_autosel) {
1461                 gchar from[BUFFSIZE];
1462                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1463                         extract_address(from);
1464                         account = account_find_from_address(from);
1465                 }
1466         }
1467         if (!account) account = cur_account;
1468         g_return_if_fail(account != NULL);
1469
1470         compose = compose_create(account, COMPOSE_REEDIT);
1471         if (privacy_system != NULL) {
1472                 compose->privacy_system = privacy_system;
1473                 compose_use_signing(compose, use_signing);
1474                 compose_use_encryption(compose, use_encryption);
1475                 compose_update_privacy_system_menu_item(compose);
1476         } else {
1477                 activate_privacy_system(compose, account);
1478         }
1479         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1480
1481         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1482             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1483                 gchar queueheader_buf[BUFFSIZE];
1484
1485                 /* Set message save folder */
1486                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1487                         gint startpos = 0;
1488
1489                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1490                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1491                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1492                 }
1493         }
1494         
1495         if (compose_parse_header(compose, msginfo) < 0) return;
1496         compose_reedit_set_entry(compose, msginfo);
1497
1498         textview = GTK_TEXT_VIEW(compose->text);
1499         textbuf = gtk_text_view_get_buffer(textview);
1500         compose_create_tags(textview, compose);
1501
1502         mark = gtk_text_buffer_get_insert(textbuf);
1503         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1504
1505         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1506                                         G_CALLBACK(compose_changed_cb),
1507                                         compose);
1508         
1509         if (procmime_msginfo_is_encrypted(msginfo)) {
1510                 fp = procmime_get_first_encrypted_text_content(msginfo);
1511                 if (fp) 
1512                         compose_force_encryption(compose, account, TRUE);
1513         } else
1514                 fp = procmime_get_first_text_content(msginfo);
1515         if (fp == NULL)
1516                 g_warning("Can't get text part\n");
1517
1518         if (fp != NULL) {
1519                 gboolean prev_autowrap = compose->autowrap;
1520
1521                 compose->autowrap = FALSE;
1522                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1523                         strcrchomp(buf);
1524                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1525                 }
1526                 compose_wrap_all_full(compose, FALSE);
1527                 compose->autowrap = prev_autowrap;
1528                 fclose(fp);
1529         }
1530         
1531         compose_attach_parts(compose, msginfo);
1532
1533         compose_colorize_signature(compose);
1534
1535         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1536                                         G_CALLBACK(compose_changed_cb),
1537                                         compose);
1538
1539         gtk_widget_grab_focus(compose->text);
1540
1541         if (prefs_common.auto_exteditor)
1542                 compose_exec_ext_editor(compose);
1543 }
1544
1545 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1546 {
1547         Compose *compose;
1548         gchar *filename;
1549         GtkItemFactory *ifactory;
1550         FolderItem *item;
1551
1552         g_return_val_if_fail(msginfo != NULL, NULL);
1553
1554         if (!account)
1555                 account = account_get_reply_account(msginfo,
1556                                         prefs_common.reply_account_autosel);
1557         g_return_val_if_fail(account != NULL, NULL);
1558
1559         compose = compose_create(account, COMPOSE_REDIRECT);
1560         ifactory = gtk_item_factory_from_widget(compose->menubar);
1561         compose_create_tags(GTK_TEXT_VIEW(compose->text), compose);
1562         compose->replyinfo = NULL;
1563         compose->fwdinfo = NULL;
1564
1565         compose_show_first_last_header(compose, TRUE);
1566
1567         gtk_widget_grab_focus(compose->header_last->entry);
1568
1569         filename = procmsg_get_message_file_path(msginfo);
1570         if (filename == NULL)
1571                 return NULL;
1572
1573         compose->redirect_filename = filename;
1574         
1575         /* Set save folder */
1576         item = msginfo->folder;
1577         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1578                 gchar *folderidentifier;
1579
1580                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1581                 folderidentifier = folder_item_get_identifier(item);
1582                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1583                 g_free(folderidentifier);
1584         }
1585
1586         compose_attach_parts(compose, msginfo);
1587
1588         if (msginfo->subject)
1589                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1590                                    msginfo->subject);
1591         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1592
1593         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL);
1594         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1595
1596         compose_colorize_signature(compose);
1597
1598         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1599         menu_set_sensitive(ifactory, "/Add...", FALSE);
1600         menu_set_sensitive(ifactory, "/Remove", FALSE);
1601         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1602
1603         ifactory = gtk_item_factory_from_widget(compose->menubar);
1604         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1605         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1606         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1607         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1608         menu_set_sensitive(ifactory, "/Edit", FALSE);
1609         menu_set_sensitive(ifactory, "/Options", FALSE);
1610         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1611         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1612         
1613         gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1614         gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1615         gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1616         gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1617         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1618         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1619         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1620
1621         return compose;
1622 }
1623
1624 GList *compose_get_compose_list(void)
1625 {
1626         return compose_list;
1627 }
1628
1629 void compose_entry_append(Compose *compose, const gchar *address,
1630                           ComposeEntryType type)
1631 {
1632         gchar *header;
1633         gchar *cur, *begin;
1634         gboolean in_quote = FALSE;
1635         if (!address || *address == '\0') return;
1636
1637         switch (type) {
1638         case COMPOSE_CC:
1639                 header = N_("Cc:");
1640                 break;
1641         case COMPOSE_BCC:
1642                 header = N_("Bcc:");
1643                 break;
1644         case COMPOSE_REPLYTO:
1645                 header = N_("Reply-To:");
1646                 break;
1647         case COMPOSE_NEWSGROUPS:
1648                 header = N_("Newsgroups:");
1649                 break;
1650         case COMPOSE_FOLLOWUPTO:
1651                 header = N_( "Followup-To:");
1652                 break;
1653         case COMPOSE_TO:
1654         default:
1655                 header = N_("To:");
1656                 break;
1657         }
1658         header = prefs_common.trans_hdr ? gettext(header) : header;
1659         
1660         cur = begin = (gchar *)address;
1661         
1662         /* we separate the line by commas, but not if we're inside a quoted
1663          * string */
1664         while (*cur != '\0') {
1665                 if (*cur == '"') 
1666                         in_quote = !in_quote;
1667                 if (*cur == ',' && !in_quote) {
1668                         gchar *tmp = g_strdup(begin);
1669                         gchar *o_tmp = tmp;
1670                         tmp[cur-begin]='\0';
1671                         cur++;
1672                         begin = cur;
1673                         while (*tmp == ' ')
1674                                 tmp++;
1675                         compose_add_header_entry(compose, header, tmp);
1676                         g_free(o_tmp);
1677                         continue;
1678                 }
1679                 cur++;
1680         }
1681         if (begin < cur) {
1682                 gchar *tmp = g_strdup(begin);
1683                 gchar *o_tmp = tmp;
1684                 tmp[cur-begin]='\0';
1685                 cur++;
1686                 begin = cur;
1687                 while (*tmp == ' ')
1688                         tmp++;
1689                 compose_add_header_entry(compose, header, tmp);
1690                 g_free(o_tmp);          
1691         }
1692 }
1693
1694 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1695 {
1696         static GtkStyle *bold_style = NULL;
1697         static GdkColor bold_color;
1698         GSList *h_list;
1699         GtkEntry *entry;
1700                 
1701         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1702                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1703                 if (gtk_entry_get_text(entry) && 
1704                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1705                         gtk_widget_ensure_style(GTK_WIDGET(entry));
1706                         if (!bold_style) {
1707                                 gtkut_convert_int_to_gdk_color
1708                                         (prefs_common.color_new, &bold_color);
1709                                 bold_style = gtk_style_copy(gtk_widget_get_style
1710                                         (GTK_WIDGET(entry)));
1711                                 pango_font_description_set_weight
1712                                         (bold_style->font_desc, PANGO_WEIGHT_BOLD);
1713                                 bold_style->fg[GTK_STATE_NORMAL] = bold_color;
1714                         }
1715                         gtk_widget_set_style(GTK_WIDGET(entry), bold_style);
1716                 }
1717         }
1718 }
1719
1720 void compose_toolbar_cb(gint action, gpointer data)
1721 {
1722         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1723         Compose *compose = (Compose*)toolbar_item->parent;
1724         
1725         g_return_if_fail(compose != NULL);
1726
1727         switch(action) {
1728         case A_SEND:
1729                 compose_send_cb(compose, 0, NULL);
1730                 break;
1731         case A_SENDL:
1732                 compose_send_later_cb(compose, 0, NULL);
1733                 break;
1734         case A_DRAFT:
1735                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1736                 break;
1737         case A_INSERT:
1738                 compose_insert_file_cb(compose, 0, NULL);
1739                 break;
1740         case A_ATTACH:
1741                 compose_attach_cb(compose, 0, NULL);
1742                 break;
1743         case A_SIG:
1744                 compose_insert_sig(compose, FALSE);
1745                 break;
1746         case A_EXTEDITOR:
1747                 compose_ext_editor_cb(compose, 0, NULL);
1748                 break;
1749         case A_LINEWRAP_CURRENT:
1750                 compose_beautify_paragraph(compose, NULL, TRUE);
1751                 break;
1752         case A_LINEWRAP_ALL:
1753                 compose_wrap_all_full(compose, TRUE);
1754                 break;
1755         case A_ADDRBOOK:
1756                 compose_address_cb(compose, 0, NULL);
1757                 break;
1758 #ifdef USE_ASPELL
1759         case A_CHECK_SPELLING:
1760                 compose_check_all(compose);
1761                 break;
1762 #endif
1763         default:
1764                 break;
1765         }
1766 }
1767
1768 static void compose_entries_set(Compose *compose, const gchar *mailto)
1769 {
1770         gchar *to = NULL;
1771         gchar *cc = NULL;
1772         gchar *subject = NULL;
1773         gchar *body = NULL;
1774         gchar *temp = NULL;
1775         gint  len = 0;
1776
1777         scan_mailto_url(mailto, &to, &cc, NULL, &subject, &body);
1778
1779         if (to)
1780                 compose_entry_append(compose, to, COMPOSE_TO);
1781         if (cc)
1782                 compose_entry_append(compose, cc, COMPOSE_CC);
1783         if (subject) {
1784                 if (!g_utf8_validate (subject, -1, NULL)) {
1785                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1786                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1787                         g_free(temp);
1788                 } else {
1789                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1790                 }
1791         }
1792         if (body) {
1793                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1794                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1795                 GtkTextMark *mark;
1796                 GtkTextIter iter;
1797                 gboolean prev_autowrap = compose->autowrap;
1798
1799                 compose->autowrap = FALSE;
1800
1801                 mark = gtk_text_buffer_get_insert(buffer);
1802                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1803
1804                 if (!g_utf8_validate (body, -1, NULL)) {
1805                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1806                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1807                         g_free(temp);
1808                 } else {
1809                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1810                 }
1811                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1812
1813                 compose->autowrap = prev_autowrap;
1814                 if (compose->autowrap)
1815                         compose_wrap_all(compose);
1816         }
1817
1818         g_free(to);
1819         g_free(cc);
1820         g_free(subject);
1821         g_free(body);
1822 }
1823
1824 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1825 {
1826         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1827                                        {"Cc:",          NULL, TRUE},
1828                                        {"References:",  NULL, FALSE},
1829                                        {"Bcc:",         NULL, TRUE},
1830                                        {"Newsgroups:",  NULL, TRUE},
1831                                        {"Followup-To:", NULL, TRUE},
1832                                        {"List-Post:",   NULL, FALSE},
1833                                        {"X-Priority:",  NULL, FALSE},
1834                                        {NULL,           NULL, FALSE}};
1835
1836         enum
1837         {
1838                 H_REPLY_TO      = 0,
1839                 H_CC            = 1,
1840                 H_REFERENCES    = 2,
1841                 H_BCC           = 3,
1842                 H_NEWSGROUPS    = 4,
1843                 H_FOLLOWUP_TO   = 5,
1844                 H_LIST_POST     = 6,
1845                 H_X_PRIORITY    = 7
1846         };
1847
1848         FILE *fp;
1849
1850         g_return_val_if_fail(msginfo != NULL, -1);
1851
1852         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1853         procheader_get_header_fields(fp, hentry);
1854         fclose(fp);
1855
1856         if (hentry[H_REPLY_TO].body != NULL) {
1857                 if (hentry[H_REPLY_TO].body[0] != '\0') {
1858                         compose->replyto =
1859                                 conv_unmime_header(hentry[H_REPLY_TO].body,
1860                                                    NULL);
1861                 }
1862                 g_free(hentry[H_REPLY_TO].body);
1863                 hentry[H_REPLY_TO].body = NULL;
1864         }
1865         if (hentry[H_CC].body != NULL) {
1866                 compose->cc = conv_unmime_header(hentry[H_CC].body, NULL);
1867                 g_free(hentry[H_CC].body);
1868                 hentry[H_CC].body = NULL;
1869         }
1870         if (hentry[H_REFERENCES].body != NULL) {
1871                 if (compose->mode == COMPOSE_REEDIT)
1872                         compose->references = hentry[H_REFERENCES].body;
1873                 else {
1874                         compose->references = compose_parse_references
1875                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1876                         g_free(hentry[H_REFERENCES].body);
1877                 }
1878                 hentry[H_REFERENCES].body = NULL;
1879         }
1880         if (hentry[H_BCC].body != NULL) {
1881                 if (compose->mode == COMPOSE_REEDIT)
1882                         compose->bcc =
1883                                 conv_unmime_header(hentry[H_BCC].body, NULL);
1884                 g_free(hentry[H_BCC].body);
1885                 hentry[H_BCC].body = NULL;
1886         }
1887         if (hentry[H_NEWSGROUPS].body != NULL) {
1888                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1889                 hentry[H_NEWSGROUPS].body = NULL;
1890         }
1891         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1892                 if (hentry[H_FOLLOWUP_TO].body[0] != '\0') {
1893                         compose->followup_to =
1894                                 conv_unmime_header(hentry[H_FOLLOWUP_TO].body,
1895                                                    NULL);
1896                 }
1897                 g_free(hentry[H_FOLLOWUP_TO].body);
1898                 hentry[H_FOLLOWUP_TO].body = NULL;
1899         }
1900         if (hentry[H_LIST_POST].body != NULL) {
1901                 gchar *to = NULL;
1902
1903                 extract_address(hentry[H_LIST_POST].body);
1904                 if (hentry[H_LIST_POST].body[0] != '\0') {
1905                         scan_mailto_url(hentry[H_LIST_POST].body,
1906                                         &to, NULL, NULL, NULL, NULL);
1907                         if (to) {
1908                                 g_free(compose->ml_post);
1909                                 compose->ml_post = to;
1910                         }
1911                 }
1912                 g_free(hentry[H_LIST_POST].body);
1913                 hentry[H_LIST_POST].body = NULL;
1914         }
1915
1916         /* CLAWS - X-Priority */
1917         if (compose->mode == COMPOSE_REEDIT)
1918                 if (hentry[H_X_PRIORITY].body != NULL) {
1919                         gint priority;
1920                         
1921                         priority = atoi(hentry[H_X_PRIORITY].body);
1922                         g_free(hentry[H_X_PRIORITY].body);
1923                         
1924                         hentry[H_X_PRIORITY].body = NULL;
1925                         
1926                         if (priority < PRIORITY_HIGHEST || 
1927                             priority > PRIORITY_LOWEST)
1928                                 priority = PRIORITY_NORMAL;
1929                         
1930                         compose->priority =  priority;
1931                 }
1932  
1933         if (compose->mode == COMPOSE_REEDIT) {
1934                 if (msginfo->inreplyto && *msginfo->inreplyto)
1935                         compose->inreplyto = g_strdup(msginfo->inreplyto);
1936                 return 0;
1937         }
1938
1939         if (msginfo->msgid && *msginfo->msgid)
1940                 compose->inreplyto = g_strdup(msginfo->msgid);
1941
1942         if (!compose->references) {
1943                 if (msginfo->msgid && *msginfo->msgid) {
1944                         if (msginfo->inreplyto && *msginfo->inreplyto)
1945                                 compose->references =
1946                                         g_strdup_printf("<%s>\n\t<%s>",
1947                                                         msginfo->inreplyto,
1948                                                         msginfo->msgid);
1949                         else
1950                                 compose->references =
1951                                         g_strconcat("<", msginfo->msgid, ">",
1952                                                     NULL);
1953                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
1954                         compose->references =
1955                                 g_strconcat("<", msginfo->inreplyto, ">",
1956                                             NULL);
1957                 }
1958         }
1959
1960         return 0;
1961 }
1962
1963 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1964 {
1965         GSList *ref_id_list, *cur;
1966         GString *new_ref;
1967         gchar *new_ref_str;
1968
1969         ref_id_list = references_list_append(NULL, ref);
1970         if (!ref_id_list) return NULL;
1971         if (msgid && *msgid)
1972                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1973
1974         for (;;) {
1975                 gint len = 0;
1976
1977                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1978                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1979                         len += strlen((gchar *)cur->data) + 5;
1980
1981                 if (len > MAX_REFERENCES_LEN) {
1982                         /* remove second message-ID */
1983                         if (ref_id_list && ref_id_list->next &&
1984                             ref_id_list->next->next) {
1985                                 g_free(ref_id_list->next->data);
1986                                 ref_id_list = g_slist_remove
1987                                         (ref_id_list, ref_id_list->next->data);
1988                         } else {
1989                                 slist_free_strings(ref_id_list);
1990                                 g_slist_free(ref_id_list);
1991                                 return NULL;
1992                         }
1993                 } else
1994                         break;
1995         }
1996
1997         new_ref = g_string_new("");
1998         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1999                 if (new_ref->len > 0)
2000                         g_string_append(new_ref, "\n\t");
2001                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
2002         }
2003
2004         slist_free_strings(ref_id_list);
2005         g_slist_free(ref_id_list);
2006
2007         new_ref_str = new_ref->str;
2008         g_string_free(new_ref, FALSE);
2009
2010         return new_ref_str;
2011 }
2012
2013 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
2014                                 const gchar *fmt, const gchar *qmark,
2015                                 const gchar *body)
2016 {
2017         static MsgInfo dummyinfo;
2018         gchar *quote_str = NULL;
2019         gchar *buf;
2020         gchar *p, *lastp;
2021         gint len;
2022         gboolean prev_autowrap;
2023         const gchar *trimmed_body = body;
2024         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2025         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2026         
2027         if (!msginfo)
2028                 msginfo = &dummyinfo;
2029
2030         if (qmark != NULL) {
2031                 quote_fmt_init(msginfo, NULL, NULL);
2032                 quote_fmt_scan_string(qmark);
2033                 quote_fmt_parse();
2034
2035                 buf = quote_fmt_get_buffer();
2036                 if (buf == NULL)
2037                         alertpanel_error(_("Quote mark format error."));
2038                 else
2039                         Xstrdup_a(quote_str, buf, return NULL)
2040         }
2041
2042         if (fmt && *fmt != '\0') {
2043                 while (trimmed_body && strlen(trimmed_body) > 1
2044                         && trimmed_body[0]=='\n')
2045                         *trimmed_body++;
2046
2047                 quote_fmt_init(msginfo, quote_str, trimmed_body);
2048                 quote_fmt_scan_string(fmt);
2049                 quote_fmt_parse();
2050
2051                 buf = quote_fmt_get_buffer();
2052                 if (buf == NULL) {
2053                         alertpanel_error(_("Message reply/forward format error."));
2054                         return NULL;
2055                 }
2056         } else
2057                 buf = "";
2058
2059         prev_autowrap = compose->autowrap;
2060         compose->autowrap = FALSE;
2061
2062         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2063                                 G_CALLBACK(compose_changed_cb),
2064                                 compose);
2065         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2066                                 G_CALLBACK(text_inserted),
2067                                 compose);
2068         for (p = buf; *p != '\0'; ) {
2069                 GtkTextMark *mark;
2070                 GtkTextIter iter;
2071
2072                 
2073                 mark = gtk_text_buffer_get_insert(buffer);
2074                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2075
2076                 lastp = strchr(p, '\n');
2077                 len = lastp ? lastp - p + 1 : -1;
2078
2079                 if (g_utf8_validate(p, -1, NULL)) { 
2080                         gtk_text_buffer_insert(buffer, &iter, p, len);
2081                 } else {
2082                         gchar *tmpin = g_strdup(p);
2083                         gchar *tmpout = NULL;
2084                         tmpin[len] = '\0';
2085                         tmpout = conv_codeset_strdup
2086                                 (tmpin, conv_get_locale_charset_str(),
2087                                  CS_INTERNAL);
2088                         gtk_text_buffer_insert(buffer, &iter, tmpout, -1);
2089                         g_free(tmpin);
2090                         g_free(tmpout);
2091                 }
2092
2093                 if (lastp)
2094                         p = lastp + 1;
2095                 else
2096                         break;
2097         }
2098
2099         compose->autowrap = prev_autowrap;
2100         if (compose->autowrap)
2101                 compose_wrap_all(compose);
2102
2103         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2104                                 G_CALLBACK(compose_changed_cb),
2105                                 compose);
2106         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2107                                 G_CALLBACK(text_inserted),
2108                                 compose);
2109
2110
2111         return buf;
2112 }
2113
2114 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
2115                                     gboolean to_all, gboolean to_ml,
2116                                     gboolean to_sender,
2117                                     gboolean followup_and_reply_to)
2118 {
2119         GSList *cc_list = NULL;
2120         GSList *cur;
2121         gchar *from = NULL;
2122         gchar *replyto = NULL;
2123         GHashTable *to_table;
2124
2125         g_return_if_fail(compose->account != NULL);
2126         g_return_if_fail(msginfo != NULL);
2127
2128         if (compose->account->protocol != A_NNTP) {
2129                 if (!compose->replyto && to_ml && compose->ml_post
2130                     && !(msginfo->folder && msginfo->folder->prefs->enable_default_reply_to))
2131                         compose_entry_append(compose,
2132                                            compose->ml_post,
2133                                            COMPOSE_TO);
2134                 else if (!(to_all || to_sender)
2135                          && msginfo->folder
2136                          && msginfo->folder->prefs->enable_default_reply_to) {
2137                         compose_entry_append(compose,
2138                             msginfo->folder->prefs->default_reply_to,
2139                             COMPOSE_TO);
2140                 } else
2141                         compose_entry_append(compose,
2142                                  (compose->replyto && !to_sender)
2143                                   ? compose->replyto :
2144                                   msginfo->from ? msginfo->from : "",
2145                                   COMPOSE_TO);
2146         } else {
2147                 if (to_sender || (compose->followup_to && 
2148                         !strncmp(compose->followup_to, "poster", 6)))
2149                         compose_entry_append
2150                                 (compose, 
2151                                  (compose->replyto ? compose->replyto :
2152                                         msginfo->from ? msginfo->from : ""),
2153                                  COMPOSE_TO);
2154                                  
2155                 else if (followup_and_reply_to || to_all) {
2156                         compose_entry_append
2157                                 (compose,
2158                                  (compose->replyto ? compose->replyto :
2159                                  msginfo->from ? msginfo->from : ""),
2160                                  COMPOSE_TO);                           
2161                 
2162                         compose_entry_append
2163                                 (compose,
2164                                  compose->followup_to ? compose->followup_to :
2165                                  compose->newsgroups ? compose->newsgroups : "",
2166                                  COMPOSE_NEWSGROUPS);
2167                 } 
2168                 else 
2169                         compose_entry_append
2170                                 (compose,
2171                                  compose->followup_to ? compose->followup_to :
2172                                  compose->newsgroups ? compose->newsgroups : "",
2173                                  COMPOSE_NEWSGROUPS);
2174         }
2175
2176         if (msginfo->subject && *msginfo->subject) {
2177                 gchar *buf, *buf2;
2178                 guchar *p;
2179
2180                 buf = p = g_strdup(msginfo->subject);
2181                 p += subject_get_prefix_length(p);
2182                 memmove(buf, p, strlen(p) + 1);
2183
2184                 buf2 = g_strdup_printf("Re: %s", buf);
2185                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
2186
2187                 g_free(buf2);
2188                 g_free(buf);
2189         } else
2190                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
2191
2192         if (to_ml && compose->ml_post) return;
2193         if (!to_all || compose->account->protocol == A_NNTP) return;
2194
2195         if (compose->replyto) {
2196                 Xstrdup_a(replyto, compose->replyto, return);
2197                 extract_address(replyto);
2198         }
2199         if (msginfo->from) {
2200                 Xstrdup_a(from, msginfo->from, return);
2201                 extract_address(from);
2202         }
2203
2204         if (replyto && from)
2205                 cc_list = address_list_append_with_comments(cc_list, from);
2206         if (to_all && msginfo->folder && 
2207             msginfo->folder->prefs->enable_default_reply_to)
2208                 cc_list = address_list_append_with_comments(cc_list,
2209                                 msginfo->folder->prefs->default_reply_to);
2210         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
2211         cc_list = address_list_append_with_comments(cc_list, compose->cc);
2212
2213         to_table = g_hash_table_new(g_str_hash, g_str_equal);
2214         if (replyto)
2215                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
2216         if (compose->account)
2217                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
2218                                     GINT_TO_POINTER(1));
2219
2220         /* remove address on To: and that of current account */
2221         for (cur = cc_list; cur != NULL; ) {
2222                 GSList *next = cur->next;
2223                 gchar *addr;
2224
2225                 addr = g_strdup(cur->data);
2226                 extract_address(addr);
2227
2228                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2229                         cc_list = g_slist_remove(cc_list, cur->data);
2230                 else
2231                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2232
2233                 cur = next;
2234         }
2235         hash_free_strings(to_table);
2236         g_hash_table_destroy(to_table);
2237
2238         if (cc_list) {
2239                 for (cur = cc_list; cur != NULL; cur = cur->next)
2240                         compose_entry_append(compose, (gchar *)cur->data,
2241                                              COMPOSE_CC);
2242                 slist_free_strings(cc_list);
2243                 g_slist_free(cc_list);
2244         }
2245
2246 }
2247
2248 #define SET_ENTRY(entry, str) \
2249 { \
2250         if (str && *str) \
2251                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2252 }
2253
2254 #define SET_ADDRESS(type, str) \
2255 { \
2256         if (str && *str) \
2257                 compose_entry_append(compose, str, type); \
2258 }
2259
2260 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2261 {
2262         g_return_if_fail(msginfo != NULL);
2263
2264         SET_ENTRY(subject_entry, msginfo->subject);
2265         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2266         SET_ADDRESS(COMPOSE_CC, compose->cc);
2267         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2268         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2269         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2270         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2271
2272         compose_update_priority_menu_item(compose);
2273         compose_update_privacy_system_menu_item(compose);
2274         compose_show_first_last_header(compose, TRUE);
2275 }
2276
2277 #undef SET_ENTRY
2278 #undef SET_ADDRESS
2279
2280 static void compose_insert_sig(Compose *compose, gboolean replace)
2281 {
2282         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2283         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2284         GtkTextMark *mark;
2285         GtkTextIter iter, iter_end;
2286         gint cur_pos;
2287         gboolean prev_autowrap;
2288
2289         
2290         g_return_if_fail(compose->account != NULL);
2291
2292         prev_autowrap = compose->autowrap;
2293         compose->autowrap = FALSE;
2294
2295         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2296                                         G_CALLBACK(compose_changed_cb),
2297                                         compose);
2298         
2299         mark = gtk_text_buffer_get_insert(buffer);
2300         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2301         cur_pos = gtk_text_iter_get_offset (&iter);
2302
2303         gtk_text_buffer_get_end_iter(buffer, &iter);
2304
2305         if (replace && compose->sig_str) {
2306                 gboolean found;
2307                 GtkTextIter first_iter, start_iter, end_iter;
2308
2309                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2310
2311                 if (compose->sig_str[0] == '\0')
2312                         found = FALSE;
2313                 else
2314                         found = gtk_text_iter_forward_search(&first_iter,
2315                                                              compose->sig_str,
2316                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2317                                                              &start_iter, &end_iter,
2318                                                              NULL);
2319
2320                 if (found) {
2321                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2322                         iter = start_iter;
2323                 }
2324         }
2325
2326         g_free(compose->sig_str);
2327         compose->sig_str = compose_get_signature_str(compose);
2328         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2329                 compose->sig_str = g_strdup("");
2330
2331         cur_pos = gtk_text_iter_get_offset(&iter);
2332         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2333         /* skip \n\n */
2334         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2335         gtk_text_iter_forward_char(&iter);
2336         gtk_text_iter_forward_char(&iter);
2337         gtk_text_buffer_get_end_iter(buffer, &iter_end);
2338         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &iter_end);
2339
2340         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2341                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2342
2343         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2344         gtk_text_buffer_place_cursor(buffer, &iter);
2345
2346         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2347                                         G_CALLBACK(compose_changed_cb),
2348                                         compose);
2349                 
2350         compose->autowrap = prev_autowrap;
2351         if (compose->autowrap)
2352                 compose_wrap_all(compose);
2353 }
2354
2355 static gchar *compose_get_signature_str(Compose *compose)
2356 {
2357         gchar *sig_body = NULL;
2358         gchar *sig_str = NULL;
2359         gchar *utf8_sig_str = NULL;
2360
2361         g_return_val_if_fail(compose->account != NULL, NULL);
2362
2363         if (!compose->account->sig_path)
2364                 return NULL;
2365
2366         if (compose->account->sig_type == SIG_FILE) {
2367                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2368                         g_warning("can't open signature file: %s\n",
2369                                   compose->account->sig_path);
2370                         return NULL;
2371                 }
2372         }
2373
2374         if (compose->account->sig_type == SIG_COMMAND)
2375                 sig_body = get_command_output(compose->account->sig_path);
2376         else {
2377                 gchar *tmp;
2378
2379                 tmp = file_read_to_str(compose->account->sig_path);
2380                 if (!tmp)
2381                         return NULL;
2382                 sig_body = normalize_newlines(tmp);
2383                 g_free(tmp);
2384         }
2385
2386         if (compose->account->sig_sep) {
2387                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2388                                       NULL);
2389                 g_free(sig_body);
2390         } else
2391                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2392
2393         if (sig_str) {
2394                 if (g_utf8_validate(sig_str, -1, NULL) == TRUE)
2395                         utf8_sig_str = sig_str;
2396                 else {
2397                         utf8_sig_str = conv_codeset_strdup
2398                                 (sig_str, conv_get_locale_charset_str(),
2399                                  CS_INTERNAL);
2400                         g_free(sig_str);
2401                 }
2402         }
2403
2404         return utf8_sig_str;
2405 }
2406
2407 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2408 {
2409         GtkTextView *text;
2410         GtkTextBuffer *buffer;
2411         GtkTextMark *mark;
2412         GtkTextIter iter;
2413         const gchar *cur_encoding;
2414         gchar buf[BUFFSIZE];
2415         gint len;
2416         FILE *fp;
2417         gboolean prev_autowrap;
2418         gboolean badtxt = FALSE;
2419
2420         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2421
2422         if ((fp = g_fopen(file, "rb")) == NULL) {
2423                 FILE_OP_ERROR(file, "fopen");
2424                 return COMPOSE_INSERT_READ_ERROR;
2425         }
2426
2427         prev_autowrap = compose->autowrap;
2428         compose->autowrap = FALSE;
2429
2430         text = GTK_TEXT_VIEW(compose->text);
2431         buffer = gtk_text_view_get_buffer(text);
2432         mark = gtk_text_buffer_get_insert(buffer);
2433         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2434
2435         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2436                                         G_CALLBACK(text_inserted),
2437                                         compose);
2438
2439         cur_encoding = conv_get_locale_charset_str();
2440
2441         while (fgets(buf, sizeof(buf), fp) != NULL) {
2442                 gchar *str;
2443
2444                 if (g_utf8_validate(buf, -1, NULL) == TRUE)
2445                         str = g_strdup(buf);
2446                 else
2447                         str = conv_codeset_strdup
2448                                 (buf, cur_encoding, CS_INTERNAL);
2449                 if (!str) continue;
2450
2451                 /* strip <CR> if DOS/Windows file,
2452                    replace <CR> with <LF> if Macintosh file. */
2453                 strcrchomp(str);
2454                 len = strlen(str);
2455                 if (len > 0 && str[len - 1] != '\n') {
2456                         while (--len >= 0)
2457                                 if (str[len] == '\r') str[len] = '\n';
2458                 }
2459
2460                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2461                 g_free(str);
2462         }
2463
2464         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2465                                           G_CALLBACK(text_inserted),
2466                                           compose);
2467         compose->autowrap = prev_autowrap;
2468         if (compose->autowrap)
2469                 compose_wrap_all(compose);
2470
2471         fclose(fp);
2472
2473         if (badtxt)
2474                 return COMPOSE_INSERT_INVALID_CHARACTER;
2475         else 
2476                 return COMPOSE_INSERT_SUCCESS;
2477 }
2478
2479 static void compose_attach_append(Compose *compose, const gchar *file,
2480                                   const gchar *filename,
2481                                   const gchar *content_type)
2482 {
2483         AttachInfo *ainfo;
2484         GtkTreeIter iter;
2485         FILE *fp;
2486         off_t size;
2487         GAuto *auto_ainfo;
2488         gchar *size_text;
2489         GtkListStore *store;
2490         gchar *name;
2491
2492         if (!is_file_exist(file)) {
2493                 g_warning("File %s doesn't exist\n", filename);
2494                 return;
2495         }
2496         if ((size = get_file_size(file)) < 0) {
2497                 g_warning("Can't get file size of %s\n", filename);
2498                 return;
2499         }
2500         if (size == 0) {
2501                 alertpanel_notice(_("File %s is empty."), filename);
2502                 return;
2503         }
2504         if ((fp = g_fopen(file, "rb")) == NULL) {
2505                 alertpanel_error(_("Can't read %s."), filename);
2506                 return;
2507         }
2508         fclose(fp);
2509
2510         ainfo = g_new0(AttachInfo, 1);
2511         auto_ainfo = g_auto_pointer_new_with_free
2512                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2513         ainfo->file = g_strdup(file);
2514
2515         if (content_type) {
2516                 ainfo->content_type = g_strdup(content_type);
2517                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2518                         MsgInfo *msginfo;
2519                         MsgFlags flags = {0, 0};
2520
2521                         if (procmime_get_encoding_for_text_file(file) == ENC_7BIT)
2522                                 ainfo->encoding = ENC_7BIT;
2523                         else
2524                                 ainfo->encoding = ENC_8BIT;
2525
2526                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2527                         if (msginfo && msginfo->subject)
2528                                 name = g_strdup(msginfo->subject);
2529                         else
2530                                 name = g_path_get_basename(filename ? filename : file);
2531
2532                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2533
2534                         procmsg_msginfo_free(msginfo);
2535                 } else {
2536                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2537                                 ainfo->encoding = procmime_get_encoding_for_text_file(file);
2538                         else
2539                                 ainfo->encoding = ENC_BASE64;
2540                         name = g_path_get_basename(filename ? filename : file);
2541                         ainfo->name = g_strdup(name);
2542                 }
2543                 g_free(name);
2544         } else {
2545                 ainfo->content_type = procmime_get_mime_type(file);
2546                 if (!ainfo->content_type) {
2547                         ainfo->content_type =
2548                                 g_strdup("application/octet-stream");
2549                         ainfo->encoding = ENC_BASE64;
2550                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2551                         ainfo->encoding =
2552                                 procmime_get_encoding_for_text_file(file);
2553                 else
2554                         ainfo->encoding = ENC_BASE64;
2555                 name = g_path_get_basename(filename ? filename : file);
2556                 ainfo->name = g_strdup(name);   
2557                 g_free(name);
2558         }
2559
2560         if (!strcmp(ainfo->content_type, "unknown")) {
2561                 g_free(ainfo->content_type);
2562                 ainfo->content_type = g_strdup("application/octet-stream");
2563         }
2564
2565         ainfo->size = size;
2566         size_text = to_human_readable(size);
2567
2568         store = GTK_LIST_STORE(gtk_tree_view_get_model
2569                         (GTK_TREE_VIEW(compose->attach_clist)));
2570                 
2571         gtk_list_store_append(store, &iter);
2572         gtk_list_store_set(store, &iter, 
2573                            COL_MIMETYPE, ainfo->content_type,
2574                            COL_SIZE, size_text,
2575                            COL_NAME, ainfo->name,
2576                            COL_DATA, ainfo,
2577                            COL_AUTODATA, auto_ainfo,
2578                            -1);
2579         
2580         g_auto_pointer_free(auto_ainfo);
2581 }
2582
2583 static void compose_use_signing(Compose *compose, gboolean use_signing)
2584 {
2585         GtkItemFactory *ifactory;
2586         GtkWidget *menuitem = NULL;
2587
2588         compose->use_signing = use_signing;
2589         ifactory = gtk_item_factory_from_widget(compose->menubar);
2590         menuitem = gtk_item_factory_get_item
2591                 (ifactory, "/Options/Sign");
2592         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2593                                        use_signing);
2594 }
2595
2596 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2597 {
2598         GtkItemFactory *ifactory;
2599         GtkWidget *menuitem = NULL;
2600
2601         compose->use_encryption = use_encryption;
2602         ifactory = gtk_item_factory_from_widget(compose->menubar);
2603         menuitem = gtk_item_factory_get_item
2604                 (ifactory, "/Options/Encrypt");
2605
2606         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2607                                        use_encryption);
2608 }
2609
2610 #define NEXT_PART_NOT_CHILD(info)  \
2611 {  \
2612         node = info->node;  \
2613         while (node->children)  \
2614                 node = g_node_last_child(node);  \
2615         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2616 }
2617
2618 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2619 {
2620         MimeInfo *mimeinfo;
2621         MimeInfo *child;
2622         MimeInfo *firsttext = NULL;
2623         MimeInfo *encrypted = NULL;
2624         GNode    *node;
2625         gchar *outfile;
2626         const gchar *partname = NULL;
2627
2628         mimeinfo = procmime_scan_message(msginfo);
2629         if (!mimeinfo) return;
2630
2631         if (mimeinfo->node->children == NULL) {
2632                 procmime_mimeinfo_free_all(mimeinfo);
2633                 return;
2634         }
2635
2636         /* find first content part */
2637         child = (MimeInfo *) mimeinfo->node->children->data;
2638         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2639                 child = (MimeInfo *)child->node->children->data;
2640
2641         if (child->type == MIMETYPE_TEXT) {
2642                 firsttext = child;
2643                 debug_print("First text part found\n");
2644         } else if (compose->mode == COMPOSE_REEDIT &&
2645                  child->type == MIMETYPE_APPLICATION &&
2646                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2647                 encrypted = (MimeInfo *)child->node->parent->data;
2648         }
2649      
2650         child = (MimeInfo *) mimeinfo->node->children->data;
2651         while (child != NULL) {
2652                 if (child == encrypted) {
2653                         /* skip this part of tree */
2654                         NEXT_PART_NOT_CHILD(child);
2655                         continue;
2656                 }
2657
2658                 if (child->type == MIMETYPE_MULTIPART) {
2659                         /* get the actual content */
2660                         child = procmime_mimeinfo_next(child);
2661                         continue;
2662                 }
2663                     
2664                 if (child == firsttext) {
2665                         child = procmime_mimeinfo_next(child);
2666                         continue;
2667                 }
2668
2669                 outfile = procmime_get_tmp_file_name(child);
2670                 if (procmime_get_part(outfile, child) < 0)
2671                         g_warning("Can't get the part of multipart message.");
2672                 else {
2673                         gchar *content_type;
2674
2675                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2676
2677                         /* if we meet a pgp signature, we don't attach it, but
2678                          * we force signing. */
2679                         if (strcmp(content_type, "application/pgp-signature")) {
2680                                 partname = procmime_mimeinfo_get_parameter(child, "filename");
2681                                 if (partname == NULL)
2682                                         partname = procmime_mimeinfo_get_parameter(child, "name");
2683                                 if (partname == NULL)
2684                                         partname = "";
2685                                 compose_attach_append(compose, outfile, 
2686                                                       partname, content_type);
2687                         } else {
2688                                 compose_force_signing(compose, compose->account);
2689                         }
2690                         g_free(content_type);
2691                 }
2692                 g_free(outfile);
2693                 NEXT_PART_NOT_CHILD(child);
2694         }
2695         procmime_mimeinfo_free_all(mimeinfo);
2696 }
2697
2698 #undef NEXT_PART_NOT_CHILD
2699
2700
2701
2702 typedef enum {
2703         WAIT_FOR_INDENT_CHAR,
2704         WAIT_FOR_INDENT_CHAR_OR_SPACE,
2705 } IndentState;
2706
2707 /* return indent length, we allow:
2708    indent characters followed by indent characters or spaces/tabs,
2709    alphabets and numbers immediately followed by indent characters,
2710    and the repeating sequences of the above
2711    If quote ends with multiple spaces, only the first one is included. */
2712 static gchar *compose_get_quote_str(GtkTextBuffer *buffer,
2713                                     const GtkTextIter *start, gint *len)
2714 {
2715         GtkTextIter iter = *start;
2716         gunichar wc;
2717         gchar ch[6];
2718         gint clen;
2719         IndentState state = WAIT_FOR_INDENT_CHAR;
2720         gboolean is_space;
2721         gboolean is_indent;
2722         gint alnum_count = 0;
2723         gint space_count = 0;
2724         gint quote_len = 0;
2725
2726         if (prefs_common.quote_chars == NULL) {
2727                 return 0 ;
2728         }
2729
2730         while (!gtk_text_iter_ends_line(&iter)) {
2731                 wc = gtk_text_iter_get_char(&iter);
2732                 if (g_unichar_iswide(wc))
2733                         break;
2734                 clen = g_unichar_to_utf8(wc, ch);
2735                 if (clen != 1)
2736                         break;
2737
2738                 is_indent = strchr(prefs_common.quote_chars, ch[0]) ? TRUE : FALSE;
2739                 is_space = g_unichar_isspace(wc);
2740
2741                 if (state == WAIT_FOR_INDENT_CHAR) {
2742                         if (!is_indent && !g_unichar_isalnum(wc))
2743                                 break;
2744                         if (is_indent) {
2745                                 quote_len += alnum_count + space_count + 1;
2746                                 alnum_count = space_count = 0;
2747                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2748                         } else
2749                                 alnum_count++;
2750                 } else if (state == WAIT_FOR_INDENT_CHAR_OR_SPACE) {
2751                         if (!is_indent && !is_space && !g_unichar_isalnum(wc))
2752                                 break;
2753                         if (is_space)
2754                                 space_count++;
2755                         else if (is_indent) {
2756                                 quote_len += alnum_count + space_count + 1;
2757                                 alnum_count = space_count = 0;
2758                         } else {
2759                                 alnum_count++;
2760                                 state = WAIT_FOR_INDENT_CHAR;
2761                         }
2762                 }
2763
2764                 gtk_text_iter_forward_char(&iter);
2765         }
2766
2767         if (quote_len > 0 && space_count > 0)
2768                 quote_len++;
2769
2770         if (len)
2771                 *len = quote_len;
2772
2773         if (quote_len > 0) {
2774                 iter = *start;
2775                 gtk_text_iter_forward_chars(&iter, quote_len);
2776                 return gtk_text_buffer_get_text(buffer, start, &iter, FALSE);
2777         }
2778
2779         return NULL;
2780 }
2781
2782 /* return TRUE if the line is itemized */
2783 static gboolean compose_is_itemized(GtkTextBuffer *buffer,
2784                                     const GtkTextIter *start)
2785 {
2786         GtkTextIter iter = *start;
2787         gunichar wc;
2788         gchar ch[6];
2789         gint clen;
2790
2791         if (gtk_text_iter_ends_line(&iter))
2792                 return FALSE;
2793
2794         while (1) {
2795                 wc = gtk_text_iter_get_char(&iter);
2796                 if (!g_unichar_isspace(wc))
2797                         break;
2798                 gtk_text_iter_forward_char(&iter);
2799                 if (gtk_text_iter_ends_line(&iter))
2800                         return FALSE;
2801         }
2802
2803         clen = g_unichar_to_utf8(wc, ch);
2804         if (clen != 1)
2805                 return FALSE;
2806
2807         if (!strchr("*-+", ch[0]))
2808                 return FALSE;
2809
2810         gtk_text_iter_forward_char(&iter);
2811         if (gtk_text_iter_ends_line(&iter))
2812                 return FALSE;
2813         wc = gtk_text_iter_get_char(&iter);
2814         if (g_unichar_isspace(wc))
2815                 return TRUE;
2816
2817         return FALSE;
2818 }
2819
2820 static gboolean compose_get_line_break_pos(GtkTextBuffer *buffer,
2821                                            const GtkTextIter *start,
2822                                            GtkTextIter *break_pos,
2823                                            gint max_col,
2824                                            gint quote_len)
2825 {
2826         GtkTextIter iter = *start, line_end = *start;
2827         PangoLogAttr *attrs;
2828         gchar *str;
2829         gchar *p;
2830         gint len;
2831         gint i;
2832         gint col = 0;
2833         gint pos = 0;
2834         gboolean can_break = FALSE;
2835         gboolean do_break = FALSE;
2836         gboolean was_white = FALSE;
2837         gboolean prev_dont_break = FALSE;
2838
2839         gtk_text_iter_forward_to_line_end(&line_end);
2840         str = gtk_text_buffer_get_text(buffer, &iter, &line_end, FALSE);
2841         len = g_utf8_strlen(str, -1);
2842         /* g_print("breaking line: %d: %s (len = %d)\n",
2843                 gtk_text_iter_get_line(&iter), str, len); */
2844         attrs = g_new(PangoLogAttr, len + 1);
2845
2846         pango_default_break(str, -1, NULL, attrs, len + 1);
2847
2848         p = str;
2849
2850         /* skip quote and leading spaces */
2851         for (i = 0; *p != '\0' && i < len; i++) {
2852                 gunichar wc;
2853
2854                 wc = g_utf8_get_char(p);
2855                 if (i >= quote_len && !g_unichar_isspace(wc))
2856                         break;
2857                 if (g_unichar_iswide(wc))
2858                         col += 2;
2859                 else if (*p == '\t')
2860                         col += 8;
2861                 else
2862                         col++;
2863                 p = g_utf8_next_char(p);
2864         }
2865
2866         for (; *p != '\0' && i < len; i++) {
2867                 PangoLogAttr *attr = attrs + i;
2868                 gunichar wc;
2869                 gint uri_len;
2870
2871                 if (attr->is_line_break && can_break && was_white && !prev_dont_break)
2872                         pos = i;
2873                 
2874                 was_white = attr->is_white;
2875
2876                 /* don't wrap URI */
2877                 if ((uri_len = get_uri_len(p)) > 0) {
2878                         col += uri_len;
2879                         if (pos > 0 && col > max_col) {
2880                                 do_break = TRUE;
2881                                 break;
2882                         }
2883                         i += uri_len - 1;
2884                         p += uri_len;
2885                         can_break = TRUE;
2886                         continue;
2887                 }
2888
2889                 wc = g_utf8_get_char(p);
2890                 if (g_unichar_iswide(wc)) {
2891                         col += 2;
2892                         if (prev_dont_break && can_break && attr->is_line_break)
2893                                 pos = i;
2894                 } else if (*p == '\t')
2895                         col += 8;
2896                 else
2897                         col++;
2898                 if (pos > 0 && col > max_col) {
2899                         do_break = TRUE;
2900                         break;
2901                 }
2902
2903                 if (*p == '-' || *p == '/')
2904                         prev_dont_break = TRUE;
2905                 else
2906                         prev_dont_break = FALSE;
2907
2908                 p = g_utf8_next_char(p);
2909                 can_break = TRUE;
2910         }
2911
2912         debug_print("compose_get_line_break_pos(): do_break = %d, pos = %d, col = %d\n", do_break, pos, col);
2913
2914         g_free(attrs);
2915         g_free(str);
2916
2917         *break_pos = *start;
2918         gtk_text_iter_set_line_offset(break_pos, pos);
2919
2920         return do_break;
2921 }
2922
2923 static gboolean compose_join_next_line(Compose *compose,
2924                                        GtkTextBuffer *buffer,
2925                                        GtkTextIter *iter,
2926                                        const gchar *quote_str)
2927 {
2928         GtkTextIter iter_ = *iter, cur, prev, next, end;
2929         PangoLogAttr attrs[3];
2930         gchar *str;
2931         gchar *next_quote_str;
2932         gunichar wc1, wc2;
2933         gint quote_len;
2934         gboolean keep_cursor = FALSE;
2935
2936         if (!gtk_text_iter_forward_line(&iter_) ||
2937             gtk_text_iter_ends_line(&iter_))
2938                 return FALSE;
2939
2940         next_quote_str = compose_get_quote_str(buffer, &iter_, &quote_len);
2941
2942         if ((quote_str || next_quote_str) &&
2943             strcmp2(quote_str, next_quote_str) != 0) {
2944                 g_free(next_quote_str);
2945                 return FALSE;
2946         }
2947         g_free(next_quote_str);
2948
2949         end = iter_;
2950         if (quote_len > 0) {
2951                 gtk_text_iter_forward_chars(&end, quote_len);
2952                 if (gtk_text_iter_ends_line(&end))
2953                         return FALSE;
2954         }
2955
2956         /* don't join itemized lines */
2957         if (compose_is_itemized(buffer, &end))
2958                 return FALSE;
2959
2960         /* don't join signature separator */
2961         if (compose_is_sig_separator(compose, buffer, &iter_))
2962                 return FALSE;
2963
2964         /* delete quote str */
2965         if (quote_len > 0)
2966                 gtk_text_buffer_delete(buffer, &iter_, &end);
2967
2968         /* delete linebreak and extra spaces */
2969         prev = cur = iter_;
2970         while (gtk_text_iter_backward_char(&cur)) {
2971                 wc1 = gtk_text_iter_get_char(&cur);
2972                 if (!g_unichar_isspace(wc1))
2973                         break;
2974                 prev = cur;
2975         }
2976         next = cur = iter_;
2977         while (!gtk_text_iter_ends_line(&cur)) {
2978                 wc1 = gtk_text_iter_get_char(&cur);
2979                 if (!g_unichar_isspace(wc1))
2980                         break;
2981                 gtk_text_iter_forward_char(&cur);
2982                 next = cur;
2983         }
2984         if (!gtk_text_iter_equal(&prev, &next)) {
2985                 GtkTextMark *mark;
2986
2987                 mark = gtk_text_buffer_get_insert(buffer);
2988                 gtk_text_buffer_get_iter_at_mark(buffer, &cur, mark);
2989                 if (gtk_text_iter_equal(&prev, &cur))
2990                         keep_cursor = TRUE;
2991                 gtk_text_buffer_delete(buffer, &prev, &next);
2992         }
2993         iter_ = prev;
2994
2995         /* insert space if required */
2996         gtk_text_iter_backward_char(&prev);
2997         wc1 = gtk_text_iter_get_char(&prev);
2998         wc2 = gtk_text_iter_get_char(&next);
2999         gtk_text_iter_forward_char(&next);
3000         str = gtk_text_buffer_get_text(buffer, &prev, &next, FALSE);
3001         pango_default_break(str, -1, NULL, attrs, 3);
3002         if (!attrs[1].is_line_break ||
3003             (!g_unichar_iswide(wc1) || !g_unichar_iswide(wc2))) {
3004                 gtk_text_buffer_insert(buffer, &iter_, " ", 1);
3005                 if (keep_cursor) {
3006                         gtk_text_iter_backward_char(&iter_);
3007                         gtk_text_buffer_place_cursor(buffer, &iter_);
3008                 }
3009         }
3010         g_free(str);
3011
3012         *iter = iter_;
3013         return TRUE;
3014 }
3015
3016 #define ADD_TXT_POS(bp_, ep_, pti_) \
3017         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
3018                 last = last->next; \
3019                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
3020                 last->next = NULL; \
3021         } else { \
3022                 g_warning("alloc error scanning URIs\n"); \
3023         }
3024
3025 static void compose_beautify_paragraph(Compose *compose, GtkTextIter *par_iter, gboolean force)
3026 {
3027         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3028         GtkTextBuffer *buffer;
3029         GtkTextIter iter, break_pos, end_of_line;
3030         gchar *quote_str = NULL;
3031         gint quote_len;
3032         gboolean wrap_quote = prefs_common.linewrap_quote;
3033         gboolean prev_autowrap = compose->autowrap;
3034         gint startq_offset = -1, noq_offset = -1;
3035         gint uri_start = -1, uri_stop = -1;
3036         gint nouri_start = -1, nouri_stop = -1;
3037
3038         compose->autowrap = FALSE;
3039
3040         buffer = gtk_text_view_get_buffer(text);
3041
3042         undo_block(compose->undostruct);
3043         
3044         if (par_iter) {
3045                 iter = *par_iter;
3046         } else {
3047                 GtkTextMark *mark;
3048                 mark = gtk_text_buffer_get_insert(buffer);
3049                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
3050         }
3051
3052         /* move to paragraph start */
3053         gtk_text_iter_set_line_offset(&iter, 0);
3054         if (gtk_text_iter_ends_line(&iter)) {
3055                 while (gtk_text_iter_ends_line(&iter) &&
3056                        gtk_text_iter_forward_line(&iter))
3057                         ;
3058         } else {
3059                 while (gtk_text_iter_backward_line(&iter)) {
3060                         if (gtk_text_iter_ends_line(&iter)) {
3061                                 gtk_text_iter_forward_line(&iter);
3062                                 break;
3063                         }
3064                 }
3065         }
3066
3067         /* go until paragraph end (empty line) */
3068         while (!gtk_text_iter_ends_line(&iter)) {
3069                 gchar *scanpos = NULL;
3070                 /* parse table - in order of priority */
3071                 struct table {
3072                         const gchar *needle; /* token */
3073
3074                         /* token search function */
3075                         gchar    *(*search)     (const gchar *haystack,
3076                                                  const gchar *needle);
3077                         /* part parsing function */
3078                         gboolean  (*parse)      (const gchar *start,
3079                                                  const gchar *scanpos,
3080                                                  const gchar **bp_,
3081                                                  const gchar **ep_);
3082                         /* part to URI function */
3083                         gchar    *(*build_uri)  (const gchar *bp,
3084                                                  const gchar *ep);
3085                 };
3086
3087                 static struct table parser[] = {
3088                         {"http://",  strcasestr, get_uri_part,   make_uri_string},
3089                         {"https://", strcasestr, get_uri_part,   make_uri_string},
3090                         {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
3091                         {"www.",     strcasestr, get_uri_part,   make_http_string},
3092                         {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
3093                         {"@",        strcasestr, get_email_part, make_email_string}
3094                 };
3095                 const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
3096                 gint last_index = PARSE_ELEMS;
3097                 gint  n;
3098                 gchar *o_walk = NULL, *walk = NULL, *bp = NULL, *ep = NULL;
3099                 gint walk_pos;
3100                 
3101                 if (gtk_text_iter_has_tag(&iter, compose->no_wrap_tag) && !force)
3102                         goto colorize;
3103
3104                 uri_start = uri_stop = -1;
3105                 quote_str = compose_get_quote_str(buffer, &iter, &quote_len);
3106
3107                 if (quote_str) {
3108                         if (!wrap_quote) {
3109                                 if (startq_offset == -1) {
3110                                         startq_offset = gtk_text_iter_get_offset(&iter);
3111                                 }
3112                                 goto colorize;
3113                         }
3114                         debug_print("compose_beautify_paragraph(): quote_str = '%s'\n", quote_str);
3115                         if (startq_offset == -1) 
3116                                 startq_offset = gtk_text_iter_get_offset(&iter);
3117                 } else {
3118                         if (startq_offset == -1)
3119                                 noq_offset = gtk_text_iter_get_offset(&iter);
3120                 }
3121
3122                 if (prev_autowrap == FALSE && !force && !wrap_quote) {
3123                         goto colorize;
3124                 }
3125                 if (compose_get_line_break_pos(buffer, &iter, &break_pos,
3126                                                prefs_common.linewrap_len,
3127                                                quote_len)) {
3128                         GtkTextIter prev, next, cur;
3129                         
3130                         if (prev_autowrap != FALSE || force)
3131                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3132                         else if (quote_str && wrap_quote)
3133                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3134                         else 
3135                                 goto colorize;
3136                         /* remove trailing spaces */
3137                         cur = break_pos;
3138                         gtk_text_iter_backward_char(&cur);
3139                         prev = next = cur;
3140                         while (!gtk_text_iter_starts_line(&cur)) {
3141                                 gunichar wc;
3142
3143                                 gtk_text_iter_backward_char(&cur);
3144                                 wc = gtk_text_iter_get_char(&cur);
3145                                 if (!g_unichar_isspace(wc))
3146                                         break;
3147                                 prev = cur;
3148                         }
3149                         if (!gtk_text_iter_equal(&prev, &next)) {
3150                                 gtk_text_buffer_delete(buffer, &prev, &next);
3151                                 break_pos = next;
3152                                 gtk_text_iter_forward_char(&break_pos);
3153                         }
3154
3155                         if (quote_str)
3156                                 gtk_text_buffer_insert(buffer, &break_pos,
3157                                                        quote_str, -1);
3158
3159                         iter = break_pos;
3160                         compose_join_next_line(compose, buffer, &iter, quote_str);
3161
3162                         /* move iter to current line start */
3163                         gtk_text_iter_set_line_offset(&iter, 0);
3164                         continue;
3165                 } else {
3166                         /* move iter to next line start */
3167                         iter = break_pos;
3168                 }
3169
3170 colorize:
3171                 end_of_line = iter;
3172                 while (!gtk_text_iter_ends_line(&end_of_line)) {
3173                         gtk_text_iter_forward_char(&end_of_line);
3174                 }
3175                 o_walk = walk = gtk_text_buffer_get_text(buffer, &iter, &end_of_line, FALSE);
3176
3177                 nouri_start = gtk_text_iter_get_offset(&iter);
3178                 nouri_stop = gtk_text_iter_get_offset(&end_of_line);
3179
3180                 walk_pos = gtk_text_iter_get_offset(&iter);
3181                 /* FIXME: this looks phony. scanning for anything in the parse table */
3182                 for (n = 0; n < PARSE_ELEMS; n++) {
3183                         gchar *tmp;
3184
3185                         tmp = parser[n].search(walk, parser[n].needle);
3186                         if (tmp) {
3187                                 if (scanpos == NULL || tmp < scanpos) {
3188                                         scanpos = tmp;
3189                                         last_index = n;
3190                                 }
3191                         }                                       
3192                 }
3193
3194                 bp = ep = 0;
3195                 if (scanpos) {
3196                         /* check if URI can be parsed */
3197                         if (parser[last_index].parse(walk, scanpos, (const gchar **)&bp,(const gchar **)&ep)
3198                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
3199                                         walk = ep;
3200                         } else
3201                                 walk = scanpos +
3202                                         strlen(parser[last_index].needle);
3203                 } 
3204                 if (bp && ep) {
3205                         uri_start = walk_pos + (bp - o_walk);
3206                         uri_stop  = walk_pos + (ep - o_walk);
3207                 }
3208                 g_free(o_walk);
3209                 o_walk = NULL;
3210                 gtk_text_iter_forward_line(&iter);
3211                 g_free(quote_str);
3212                 quote_str = NULL;
3213                 if (startq_offset != -1) {
3214                         GtkTextIter startquote, endquote;
3215                         gtk_text_buffer_get_iter_at_offset(
3216                                 buffer, &startquote, startq_offset);
3217                         endquote = iter;
3218                         gtk_text_buffer_apply_tag_by_name(
3219                                 buffer, "quote", &startquote, &endquote);
3220                         startq_offset = -1;
3221                 } else if (noq_offset != -1) {
3222                         GtkTextIter startnoquote, endnoquote;
3223                         gtk_text_buffer_get_iter_at_offset(
3224                                 buffer, &startnoquote, noq_offset);
3225                         endnoquote = iter;
3226                         gtk_text_buffer_remove_tag_by_name(
3227                                 buffer, "quote", &startnoquote, &endnoquote);
3228                         noq_offset = -1;
3229                 }
3230                 
3231                 /* always */ {
3232                         GtkTextIter nouri_start_iter, nouri_end_iter;
3233                         gtk_text_buffer_get_iter_at_offset(
3234                                 buffer, &nouri_start_iter, nouri_start);
3235                         gtk_text_buffer_get_iter_at_offset(
3236                                 buffer, &nouri_end_iter, nouri_stop);
3237                         gtk_text_buffer_remove_tag_by_name(
3238