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