2005-08-18 [martin] 1.9.13cvs36
[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 (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1340             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1341                 gchar queueheader_buf[BUFFSIZE];
1342                 gint id, param;
1343
1344                 /* Select Account from queue headers */
1345                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1346                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1347                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1348                         account = account_find_from_id(id);
1349                 }
1350                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1351                                              sizeof(queueheader_buf), "NAID:")) {
1352                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1353                         account = account_find_from_id(id);
1354                 }
1355                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1356                                                     sizeof(queueheader_buf), "MAID:")) {
1357                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1358                         account = account_find_from_id(id);
1359                 }
1360                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1361                                                                 sizeof(queueheader_buf), "S:")) {
1362                         account = account_find_from_address(queueheader_buf);
1363                 }
1364                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1365                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1366                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1367                         use_signing = param;
1368                         
1369                 }
1370                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1371                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1372                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1373                         use_encryption = param;
1374                 }
1375                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1376                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1377                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1378                 }
1379                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1380                                              sizeof(queueheader_buf), "X-Priority: ")) {
1381                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1382                         compose->priority = param;
1383                 }
1384         } else 
1385                 account = msginfo->folder->folder->account;
1386
1387         if (!account && prefs_common.reedit_account_autosel) {
1388                 gchar from[BUFFSIZE];
1389                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1390                         extract_address(from);
1391                         account = account_find_from_address(from);
1392                 }
1393         }
1394         if (!account) account = cur_account;
1395         g_return_if_fail(account != NULL);
1396
1397         compose = compose_create(account, COMPOSE_REEDIT);
1398         compose->privacy_system = privacy_system;
1399         compose_use_signing(compose, use_signing);
1400         compose_use_encryption(compose, use_encryption);
1401         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1402
1403         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1404             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1405                 gchar queueheader_buf[BUFFSIZE];
1406
1407                 /* Set message save folder */
1408                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1409                         gint startpos = 0;
1410
1411                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1412                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1413                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1414                 }
1415         }
1416         
1417         if (compose_parse_header(compose, msginfo) < 0) return;
1418         compose_reedit_set_entry(compose, msginfo);
1419
1420         textview = GTK_TEXT_VIEW(compose->text);
1421         textbuf = gtk_text_view_get_buffer(textview);
1422         compose_create_tags(textview, compose);
1423
1424         mark = gtk_text_buffer_get_insert(textbuf);
1425         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1426
1427         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1428                                         G_CALLBACK(compose_changed_cb),
1429                                         compose);
1430         
1431         if (procmime_msginfo_is_encrypted(msginfo)) {
1432                 fp = procmime_get_first_encrypted_text_content(msginfo);
1433                 if (fp) 
1434                         compose_force_encryption(compose, account, TRUE);
1435         } else
1436                 fp = procmime_get_first_text_content(msginfo);
1437         if (fp == NULL)
1438                 g_warning("Can't get text part\n");
1439
1440         if (fp != NULL) {
1441                 gboolean prev_autowrap = compose->autowrap;
1442
1443                 compose->autowrap = FALSE;
1444                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1445                         strcrchomp(buf);
1446                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1447                 }
1448                 compose->autowrap = prev_autowrap;
1449                 fclose(fp);
1450         }
1451         
1452         compose_attach_parts(compose, msginfo);
1453
1454         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1455                                         G_CALLBACK(compose_changed_cb),
1456                                         compose);
1457
1458         gtk_widget_grab_focus(compose->text);
1459
1460         if (prefs_common.auto_exteditor)
1461                 compose_exec_ext_editor(compose);
1462 }
1463
1464 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1465 {
1466         Compose *compose;
1467         gchar *filename;
1468         GtkItemFactory *ifactory;
1469         FolderItem *item;
1470
1471         g_return_val_if_fail(msginfo != NULL, NULL);
1472
1473         if (!account)
1474                 account = account_get_reply_account(msginfo,
1475                                         prefs_common.reply_account_autosel);
1476         g_return_val_if_fail(account != NULL, NULL);
1477
1478         compose = compose_create(account, COMPOSE_REDIRECT);
1479         ifactory = gtk_item_factory_from_widget(compose->menubar);
1480         compose_create_tags(GTK_TEXT_VIEW(compose->text), compose);
1481         compose->replyinfo = NULL;
1482         compose->fwdinfo = NULL;
1483
1484         compose_show_first_last_header(compose, TRUE);
1485
1486         gtk_widget_grab_focus(compose->header_last->entry);
1487
1488         filename = procmsg_get_message_file_path(msginfo);
1489         if (filename == NULL)
1490                 return NULL;
1491
1492         compose->redirect_filename = filename;
1493         
1494         /* Set save folder */
1495         item = msginfo->folder;
1496         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1497                 gchar *folderidentifier;
1498
1499                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1500                 folderidentifier = folder_item_get_identifier(item);
1501                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1502                 g_free(folderidentifier);
1503         }
1504
1505         compose_attach_parts(compose, msginfo);
1506
1507         if (msginfo->subject)
1508                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1509                                    msginfo->subject);
1510         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1511
1512         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL);
1513         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1514
1515         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1516         menu_set_sensitive(ifactory, "/Add...", FALSE);
1517         menu_set_sensitive(ifactory, "/Remove", FALSE);
1518         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1519
1520         ifactory = gtk_item_factory_from_widget(compose->menubar);
1521         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1522         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1523         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1524         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1525         menu_set_sensitive(ifactory, "/Edit", FALSE);
1526         menu_set_sensitive(ifactory, "/Options", FALSE);
1527         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1528         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1529         
1530         gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1531         gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1532         gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1533         gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1534         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1535         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1536         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1537
1538         return compose;
1539 }
1540
1541 GList *compose_get_compose_list(void)
1542 {
1543         return compose_list;
1544 }
1545
1546 void compose_entry_append(Compose *compose, const gchar *address,
1547                           ComposeEntryType type)
1548 {
1549         gchar *header;
1550         gchar *cur, *begin;
1551         gboolean in_quote = FALSE;
1552         if (!address || *address == '\0') return;
1553
1554         switch (type) {
1555         case COMPOSE_CC:
1556                 header = N_("Cc:");
1557                 break;
1558         case COMPOSE_BCC:
1559                 header = N_("Bcc:");
1560                 break;
1561         case COMPOSE_REPLYTO:
1562                 header = N_("Reply-To:");
1563                 break;
1564         case COMPOSE_NEWSGROUPS:
1565                 header = N_("Newsgroups:");
1566                 break;
1567         case COMPOSE_FOLLOWUPTO:
1568                 header = N_( "Followup-To:");
1569                 break;
1570         case COMPOSE_TO:
1571         default:
1572                 header = N_("To:");
1573                 break;
1574         }
1575         header = prefs_common.trans_hdr ? gettext(header) : header;
1576         
1577         cur = begin = (gchar *)address;
1578         
1579         /* we separate the line by commas, but not if we're inside a quoted
1580          * string */
1581         while (*cur != '\0') {
1582                 if (*cur == '"') 
1583                         in_quote = !in_quote;
1584                 if (*cur == ',' && !in_quote) {
1585                         gchar *tmp = g_strdup(begin);
1586                         gchar *o_tmp = tmp;
1587                         tmp[cur-begin]='\0';
1588                         cur++;
1589                         begin = cur;
1590                         while (*tmp == ' ')
1591                                 tmp++;
1592                         compose_add_header_entry(compose, header, tmp);
1593                         g_free(o_tmp);
1594                         continue;
1595                 }
1596                 cur++;
1597         }
1598         if (begin < cur) {
1599                 gchar *tmp = g_strdup(begin);
1600                 gchar *o_tmp = tmp;
1601                 tmp[cur-begin]='\0';
1602                 cur++;
1603                 begin = cur;
1604                 while (*tmp == ' ')
1605                         tmp++;
1606                 compose_add_header_entry(compose, header, tmp);
1607                 g_free(o_tmp);          
1608         }
1609 }
1610
1611 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1612 {
1613         static GtkStyle *bold_style = NULL;
1614         static GdkColor bold_color;
1615         GSList *h_list;
1616         GtkEntry *entry;
1617                 
1618         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1619                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1620                 if (gtk_entry_get_text(entry) && 
1621                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1622                         gtk_widget_ensure_style(GTK_WIDGET(entry));
1623                         if (!bold_style) {
1624                                 PangoFontDescription *font_desc = NULL;
1625                                 gtkut_convert_int_to_gdk_color
1626                                         (prefs_common.color_new, &bold_color);
1627                                 bold_style = gtk_style_copy(gtk_widget_get_style
1628                                         (GTK_WIDGET(entry)));
1629                                 if (BOLD_FONT)
1630                                         font_desc = pango_font_description_from_string
1631                                                         (BOLD_FONT);
1632                                 if (font_desc) {
1633                                         if (bold_style->font_desc)
1634                                                 pango_font_description_free
1635                                                         (bold_style->font_desc);
1636                                         bold_style->font_desc = font_desc;
1637                                 }
1638                                 bold_style->fg[GTK_STATE_NORMAL] = bold_color;
1639                         }
1640                         gtk_widget_set_style(GTK_WIDGET(entry), bold_style);
1641                 }
1642         }
1643 }
1644
1645 void compose_toolbar_cb(gint action, gpointer data)
1646 {
1647         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1648         Compose *compose = (Compose*)toolbar_item->parent;
1649         
1650         g_return_if_fail(compose != NULL);
1651
1652         switch(action) {
1653         case A_SEND:
1654                 compose_send_cb(compose, 0, NULL);
1655                 break;
1656         case A_SENDL:
1657                 compose_send_later_cb(compose, 0, NULL);
1658                 break;
1659         case A_DRAFT:
1660                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1661                 break;
1662         case A_INSERT:
1663                 compose_insert_file_cb(compose, 0, NULL);
1664                 break;
1665         case A_ATTACH:
1666                 compose_attach_cb(compose, 0, NULL);
1667                 break;
1668         case A_SIG:
1669                 compose_insert_sig(compose, FALSE);
1670                 break;
1671         case A_EXTEDITOR:
1672                 compose_ext_editor_cb(compose, 0, NULL);
1673                 break;
1674         case A_LINEWRAP_CURRENT:
1675                 compose_wrap_paragraph(compose, NULL, TRUE);
1676                 break;
1677         case A_LINEWRAP_ALL:
1678                 compose_wrap_all_full(compose, TRUE);
1679                 break;
1680         case A_ADDRBOOK:
1681                 compose_address_cb(compose, 0, NULL);
1682                 break;
1683 #ifdef USE_ASPELL
1684         case A_CHECK_SPELLING:
1685                 compose_check_all(compose);
1686                 break;
1687 #endif
1688         default:
1689                 break;
1690         }
1691 }
1692
1693 static void compose_entries_set(Compose *compose, const gchar *mailto)
1694 {
1695         gchar *to = NULL;
1696         gchar *cc = NULL;
1697         gchar *subject = NULL;
1698         gchar *body = NULL;
1699         gchar *temp = NULL;
1700         gint  len = 0;
1701
1702         scan_mailto_url(mailto, &to, &cc, NULL, &subject, &body);
1703
1704         if (to)
1705                 compose_entry_append(compose, to, COMPOSE_TO);
1706         if (cc)
1707                 compose_entry_append(compose, cc, COMPOSE_CC);
1708         if (subject) {
1709                 if (!g_utf8_validate (subject, -1, NULL)) {
1710                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1711                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1712                         g_free(temp);
1713                 } else {
1714                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1715                 }
1716         }
1717         if (body) {
1718                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1719                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1720                 GtkTextMark *mark;
1721                 GtkTextIter iter;
1722                 gboolean prev_autowrap = compose->autowrap;
1723
1724                 compose->autowrap = FALSE;
1725
1726                 mark = gtk_text_buffer_get_insert(buffer);
1727                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1728
1729                 if (!g_utf8_validate (body, -1, NULL)) {
1730                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1731                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1732                         g_free(temp);
1733                 } else {
1734                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1735                 }
1736                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1737
1738                 compose->autowrap = prev_autowrap;
1739                 if (compose->autowrap)
1740                         compose_wrap_all(compose);
1741         }
1742
1743         g_free(to);
1744         g_free(cc);
1745         g_free(subject);
1746         g_free(body);
1747 }
1748
1749 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1750 {
1751         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1752                                        {"Cc:",          NULL, TRUE},
1753                                        {"References:",  NULL, FALSE},
1754                                        {"Bcc:",         NULL, TRUE},
1755                                        {"Newsgroups:",  NULL, TRUE},
1756                                        {"Followup-To:", NULL, TRUE},
1757                                        {"List-Post:",   NULL, FALSE},
1758                                        {"X-Priority:",  NULL, FALSE},
1759                                        {NULL,           NULL, FALSE}};
1760
1761         enum
1762         {
1763                 H_REPLY_TO      = 0,
1764                 H_CC            = 1,
1765                 H_REFERENCES    = 2,
1766                 H_BCC           = 3,
1767                 H_NEWSGROUPS    = 4,
1768                 H_FOLLOWUP_TO   = 5,
1769                 H_LIST_POST     = 6,
1770                 H_X_PRIORITY    = 7
1771         };
1772
1773         FILE *fp;
1774
1775         g_return_val_if_fail(msginfo != NULL, -1);
1776
1777         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1778         procheader_get_header_fields(fp, hentry);
1779         fclose(fp);
1780
1781         if (hentry[H_REPLY_TO].body != NULL) {
1782                 if (hentry[H_REPLY_TO].body[0] != '\0') {
1783                         compose->replyto =
1784                                 conv_unmime_header(hentry[H_REPLY_TO].body,
1785                                                    NULL);
1786                 }
1787                 g_free(hentry[H_REPLY_TO].body);
1788                 hentry[H_REPLY_TO].body = NULL;
1789         }
1790         if (hentry[H_CC].body != NULL) {
1791                 compose->cc = conv_unmime_header(hentry[H_CC].body, NULL);
1792                 g_free(hentry[H_CC].body);
1793                 hentry[H_CC].body = NULL;
1794         }
1795         if (hentry[H_REFERENCES].body != NULL) {
1796                 if (compose->mode == COMPOSE_REEDIT)
1797                         compose->references = hentry[H_REFERENCES].body;
1798                 else {
1799                         compose->references = compose_parse_references
1800                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1801                         g_free(hentry[H_REFERENCES].body);
1802                 }
1803                 hentry[H_REFERENCES].body = NULL;
1804         }
1805         if (hentry[H_BCC].body != NULL) {
1806                 if (compose->mode == COMPOSE_REEDIT)
1807                         compose->bcc =
1808                                 conv_unmime_header(hentry[H_BCC].body, NULL);
1809                 g_free(hentry[H_BCC].body);
1810                 hentry[H_BCC].body = NULL;
1811         }
1812         if (hentry[H_NEWSGROUPS].body != NULL) {
1813                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1814                 hentry[H_NEWSGROUPS].body = NULL;
1815         }
1816         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1817                 if (hentry[H_FOLLOWUP_TO].body[0] != '\0') {
1818                         compose->followup_to =
1819                                 conv_unmime_header(hentry[H_FOLLOWUP_TO].body,
1820                                                    NULL);
1821                 }
1822                 g_free(hentry[H_FOLLOWUP_TO].body);
1823                 hentry[H_FOLLOWUP_TO].body = NULL;
1824         }
1825         if (hentry[H_LIST_POST].body != NULL) {
1826                 gchar *to = NULL;
1827
1828                 extract_address(hentry[H_LIST_POST].body);
1829                 if (hentry[H_LIST_POST].body[0] != '\0') {
1830                         scan_mailto_url(hentry[H_LIST_POST].body,
1831                                         &to, NULL, NULL, NULL, NULL);
1832                         if (to) {
1833                                 g_free(compose->ml_post);
1834                                 compose->ml_post = to;
1835                         }
1836                 }
1837                 g_free(hentry[H_LIST_POST].body);
1838                 hentry[H_LIST_POST].body = NULL;
1839         }
1840
1841         /* CLAWS - X-Priority */
1842         if (compose->mode == COMPOSE_REEDIT)
1843                 if (hentry[H_X_PRIORITY].body != NULL) {
1844                         gint priority;
1845                         
1846                         priority = atoi(hentry[H_X_PRIORITY].body);
1847                         g_free(hentry[H_X_PRIORITY].body);
1848                         
1849                         hentry[H_X_PRIORITY].body = NULL;
1850                         
1851                         if (priority < PRIORITY_HIGHEST || 
1852                             priority > PRIORITY_LOWEST)
1853                                 priority = PRIORITY_NORMAL;
1854                         
1855                         compose->priority =  priority;
1856                 }
1857  
1858         if (compose->mode == COMPOSE_REEDIT) {
1859                 if (msginfo->inreplyto && *msginfo->inreplyto)
1860                         compose->inreplyto = g_strdup(msginfo->inreplyto);
1861                 return 0;
1862         }
1863
1864         if (msginfo->msgid && *msginfo->msgid)
1865                 compose->inreplyto = g_strdup(msginfo->msgid);
1866
1867         if (!compose->references) {
1868                 if (msginfo->msgid && *msginfo->msgid) {
1869                         if (msginfo->inreplyto && *msginfo->inreplyto)
1870                                 compose->references =
1871                                         g_strdup_printf("<%s>\n\t<%s>",
1872                                                         msginfo->inreplyto,
1873                                                         msginfo->msgid);
1874                         else
1875                                 compose->references =
1876                                         g_strconcat("<", msginfo->msgid, ">",
1877                                                     NULL);
1878                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
1879                         compose->references =
1880                                 g_strconcat("<", msginfo->inreplyto, ">",
1881                                             NULL);
1882                 }
1883         }
1884
1885         return 0;
1886 }
1887
1888 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1889 {
1890         GSList *ref_id_list, *cur;
1891         GString *new_ref;
1892         gchar *new_ref_str;
1893
1894         ref_id_list = references_list_append(NULL, ref);
1895         if (!ref_id_list) return NULL;
1896         if (msgid && *msgid)
1897                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1898
1899         for (;;) {
1900                 gint len = 0;
1901
1902                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1903                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1904                         len += strlen((gchar *)cur->data) + 5;
1905
1906                 if (len > MAX_REFERENCES_LEN) {
1907                         /* remove second message-ID */
1908                         if (ref_id_list && ref_id_list->next &&
1909                             ref_id_list->next->next) {
1910                                 g_free(ref_id_list->next->data);
1911                                 ref_id_list = g_slist_remove
1912                                         (ref_id_list, ref_id_list->next->data);
1913                         } else {
1914                                 slist_free_strings(ref_id_list);
1915                                 g_slist_free(ref_id_list);
1916                                 return NULL;
1917                         }
1918                 } else
1919                         break;
1920         }
1921
1922         new_ref = g_string_new("");
1923         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1924                 if (new_ref->len > 0)
1925                         g_string_append(new_ref, "\n\t");
1926                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
1927         }
1928
1929         slist_free_strings(ref_id_list);
1930         g_slist_free(ref_id_list);
1931
1932         new_ref_str = new_ref->str;
1933         g_string_free(new_ref, FALSE);
1934
1935         return new_ref_str;
1936 }
1937
1938 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1939                                 const gchar *fmt, const gchar *qmark,
1940                                 const gchar *body)
1941 {
1942         static MsgInfo dummyinfo;
1943         gchar *quote_str = NULL;
1944         gchar *buf;
1945         gchar *p, *lastp;
1946         gint len;
1947         gboolean prev_autowrap;
1948         const gchar *trimmed_body = body;
1949         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1950         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1951         
1952         if (!msginfo)
1953                 msginfo = &dummyinfo;
1954
1955         if (qmark != NULL) {
1956                 quote_fmt_init(msginfo, NULL, NULL);
1957                 quote_fmt_scan_string(qmark);
1958                 quote_fmt_parse();
1959
1960                 buf = quote_fmt_get_buffer();
1961                 if (buf == NULL)
1962                         alertpanel_error(_("Quote mark format error."));
1963                 else
1964                         Xstrdup_a(quote_str, buf, return NULL)
1965         }
1966
1967         if (fmt && *fmt != '\0') {
1968                 while (trimmed_body && strlen(trimmed_body) > 1
1969                         && trimmed_body[0]=='\n')
1970                         *trimmed_body++;
1971
1972                 quote_fmt_init(msginfo, quote_str, trimmed_body);
1973                 quote_fmt_scan_string(fmt);
1974                 quote_fmt_parse();
1975
1976                 buf = quote_fmt_get_buffer();
1977                 if (buf == NULL) {
1978                         alertpanel_error(_("Message reply/forward format error."));
1979                         return NULL;
1980                 }
1981         } else
1982                 buf = "";
1983
1984         prev_autowrap = compose->autowrap;
1985         compose->autowrap = FALSE;
1986
1987         g_signal_handlers_block_by_func(G_OBJECT(buffer),
1988                                 G_CALLBACK(compose_changed_cb),
1989                                 compose);
1990         g_signal_handlers_block_by_func(G_OBJECT(buffer),
1991                                 G_CALLBACK(text_inserted),
1992                                 compose);
1993         for (p = buf; *p != '\0'; ) {
1994                 GtkTextMark *mark;
1995                 GtkTextIter iter;
1996
1997                 
1998                 mark = gtk_text_buffer_get_insert(buffer);
1999                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2000
2001                 lastp = strchr(p, '\n');
2002                 len = lastp ? lastp - p + 1 : -1;
2003
2004                 gtk_text_buffer_insert(buffer, &iter, p, len);
2005
2006                 if (lastp)
2007                         p = lastp + 1;
2008                 else
2009                         break;
2010         }
2011
2012         compose->autowrap = prev_autowrap;
2013         if (compose->autowrap)
2014                 compose_wrap_all(compose);
2015
2016         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2017                                 G_CALLBACK(compose_changed_cb),
2018                                 compose);
2019         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2020                                 G_CALLBACK(text_inserted),
2021                                 compose);
2022
2023
2024         return buf;
2025 }
2026
2027 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
2028                                     gboolean to_all, gboolean to_ml,
2029                                     gboolean to_sender,
2030                                     gboolean followup_and_reply_to)
2031 {
2032         GSList *cc_list = NULL;
2033         GSList *cur;
2034         gchar *from = NULL;
2035         gchar *replyto = NULL;
2036         GHashTable *to_table;
2037
2038         g_return_if_fail(compose->account != NULL);
2039         g_return_if_fail(msginfo != NULL);
2040
2041         if (compose->account->protocol != A_NNTP) {
2042                 if (!compose->replyto && to_ml && compose->ml_post
2043                     && !(msginfo->folder && msginfo->folder->prefs->enable_default_reply_to))
2044                         compose_entry_append(compose,
2045                                            compose->ml_post,
2046                                            COMPOSE_TO);
2047                 else if (!(to_all || to_sender)
2048                          && msginfo->folder
2049                          && msginfo->folder->prefs->enable_default_reply_to) {
2050                         compose_entry_append(compose,
2051                             msginfo->folder->prefs->default_reply_to,
2052                             COMPOSE_TO);
2053                 } else
2054                         compose_entry_append(compose,
2055                                  (compose->replyto && !to_sender)
2056                                   ? compose->replyto :
2057                                   msginfo->from ? msginfo->from : "",
2058                                   COMPOSE_TO);
2059         } else {
2060                 if (to_sender || (compose->followup_to && 
2061                         !strncmp(compose->followup_to, "poster", 6)))
2062                         compose_entry_append
2063                                 (compose, 
2064                                  (compose->replyto ? compose->replyto :
2065                                         msginfo->from ? msginfo->from : ""),
2066                                  COMPOSE_TO);
2067                                  
2068                 else if (followup_and_reply_to || to_all) {
2069                         compose_entry_append
2070                                 (compose,
2071                                  (compose->replyto ? compose->replyto :
2072                                  msginfo->from ? msginfo->from : ""),
2073                                  COMPOSE_TO);                           
2074                 
2075                         compose_entry_append
2076                                 (compose,
2077                                  compose->followup_to ? compose->followup_to :
2078                                  compose->newsgroups ? compose->newsgroups : "",
2079                                  COMPOSE_NEWSGROUPS);
2080                 } 
2081                 else 
2082                         compose_entry_append
2083                                 (compose,
2084                                  compose->followup_to ? compose->followup_to :
2085                                  compose->newsgroups ? compose->newsgroups : "",
2086                                  COMPOSE_NEWSGROUPS);
2087         }
2088
2089         if (msginfo->subject && *msginfo->subject) {
2090                 gchar *buf, *buf2;
2091                 guchar *p;
2092
2093                 buf = p = g_strdup(msginfo->subject);
2094                 p += subject_get_prefix_length(p);
2095                 memmove(buf, p, strlen(p) + 1);
2096
2097                 buf2 = g_strdup_printf("Re: %s", buf);
2098                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
2099
2100                 g_free(buf2);
2101                 g_free(buf);
2102         } else
2103                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
2104
2105         if (to_ml && compose->ml_post) return;
2106         if (!to_all || compose->account->protocol == A_NNTP) return;
2107
2108         if (compose->replyto) {
2109                 Xstrdup_a(replyto, compose->replyto, return);
2110                 extract_address(replyto);
2111         }
2112         if (msginfo->from) {
2113                 Xstrdup_a(from, msginfo->from, return);
2114                 extract_address(from);
2115         }
2116
2117         if (replyto && from)
2118                 cc_list = address_list_append_with_comments(cc_list, from);
2119         if (to_all && msginfo->folder && 
2120             msginfo->folder->prefs->enable_default_reply_to)
2121                 cc_list = address_list_append_with_comments(cc_list,
2122                                 msginfo->folder->prefs->default_reply_to);
2123         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
2124         cc_list = address_list_append_with_comments(cc_list, compose->cc);
2125
2126         to_table = g_hash_table_new(g_str_hash, g_str_equal);
2127         if (replyto)
2128                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
2129         if (compose->account)
2130                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
2131                                     GINT_TO_POINTER(1));
2132
2133         /* remove address on To: and that of current account */
2134         for (cur = cc_list; cur != NULL; ) {
2135                 GSList *next = cur->next;
2136                 gchar *addr;
2137
2138                 addr = g_strdup(cur->data);
2139                 extract_address(addr);
2140
2141                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2142                         cc_list = g_slist_remove(cc_list, cur->data);
2143                 else
2144                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2145
2146                 cur = next;
2147         }
2148         hash_free_strings(to_table);
2149         g_hash_table_destroy(to_table);
2150
2151         if (cc_list) {
2152                 for (cur = cc_list; cur != NULL; cur = cur->next)
2153                         compose_entry_append(compose, (gchar *)cur->data,
2154                                              COMPOSE_CC);
2155                 slist_free_strings(cc_list);
2156                 g_slist_free(cc_list);
2157         }
2158
2159 }
2160
2161 #define SET_ENTRY(entry, str) \
2162 { \
2163         if (str && *str) \
2164                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2165 }
2166
2167 #define SET_ADDRESS(type, str) \
2168 { \
2169         if (str && *str) \
2170                 compose_entry_append(compose, str, type); \
2171 }
2172
2173 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2174 {
2175         g_return_if_fail(msginfo != NULL);
2176
2177         SET_ENTRY(subject_entry, msginfo->subject);
2178         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2179         SET_ADDRESS(COMPOSE_CC, compose->cc);
2180         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2181         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2182         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2183         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2184
2185         compose_update_priority_menu_item(compose);
2186         compose_update_privacy_system_menu_item(compose);
2187         compose_show_first_last_header(compose, TRUE);
2188 }
2189
2190 #undef SET_ENTRY
2191 #undef SET_ADDRESS
2192
2193 static void compose_insert_sig(Compose *compose, gboolean replace)
2194 {
2195         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2196         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2197         GtkTextMark *mark;
2198         GtkTextIter iter, iter_end;
2199         gint cur_pos;
2200         gboolean prev_autowrap;
2201
2202         
2203         g_return_if_fail(compose->account != NULL);
2204
2205         prev_autowrap = compose->autowrap;
2206         compose->autowrap = FALSE;
2207
2208         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2209                                         G_CALLBACK(compose_changed_cb),
2210                                         compose);
2211         
2212         mark = gtk_text_buffer_get_insert(buffer);
2213         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2214         cur_pos = gtk_text_iter_get_offset (&iter);
2215
2216         gtk_text_buffer_get_end_iter(buffer, &iter);
2217
2218         if (replace && compose->sig_str) {
2219                 gboolean found;
2220                 GtkTextIter first_iter, start_iter, end_iter;
2221
2222                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2223
2224                 if (compose->sig_str[0] == '\0')
2225                         found = FALSE;
2226                 else
2227                         found = gtk_text_iter_forward_search(&first_iter,
2228                                                              compose->sig_str,
2229                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2230                                                              &start_iter, &end_iter,
2231                                                              NULL);
2232
2233                 if (found) {
2234                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2235                         iter = start_iter;
2236                 }
2237         }
2238
2239         g_free(compose->sig_str);
2240         compose->sig_str = compose_get_signature_str(compose);
2241         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2242                 compose->sig_str = g_strdup("");
2243
2244         cur_pos = gtk_text_iter_get_offset(&iter);
2245         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2246         /* skip \n\n */
2247         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2248         gtk_text_iter_forward_char(&iter);
2249         gtk_text_iter_forward_char(&iter);
2250         gtk_text_buffer_get_end_iter(buffer, &iter_end);
2251         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &iter_end);
2252
2253         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2254                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2255
2256         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2257         gtk_text_buffer_place_cursor(buffer, &iter);
2258
2259         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2260                                         G_CALLBACK(compose_changed_cb),
2261                                         compose);
2262                 
2263         compose->autowrap = prev_autowrap;
2264         if (compose->autowrap)
2265                 compose_wrap_all(compose);
2266 }
2267
2268 static gchar *compose_get_signature_str(Compose *compose)
2269 {
2270         gchar *sig_body = NULL;
2271         gchar *sig_str = NULL;
2272         gchar *utf8_sig_str = NULL;
2273
2274         g_return_val_if_fail(compose->account != NULL, NULL);
2275
2276         if (!compose->account->sig_path)
2277                 return NULL;
2278
2279         if (compose->account->sig_type == SIG_FILE) {
2280                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2281                         g_warning("can't open signature file: %s\n",
2282                                   compose->account->sig_path);
2283                         return NULL;
2284                 }
2285         }
2286
2287         if (compose->account->sig_type == SIG_COMMAND)
2288                 sig_body = get_command_output(compose->account->sig_path);
2289         else {
2290                 gchar *tmp;
2291
2292                 tmp = file_read_to_str(compose->account->sig_path);
2293                 if (!tmp)
2294                         return NULL;
2295                 sig_body = normalize_newlines(tmp);
2296                 g_free(tmp);
2297         }
2298
2299         if (compose->account->sig_sep) {
2300                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2301                                       NULL);
2302                 g_free(sig_body);
2303         } else
2304                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2305
2306         if (sig_str) {
2307                 if (g_utf8_validate(sig_str, -1, NULL) == TRUE)
2308                         utf8_sig_str = sig_str;
2309                 else {
2310                         utf8_sig_str = conv_codeset_strdup
2311                                 (sig_str, conv_get_locale_charset_str(),
2312                                  CS_INTERNAL);
2313                         g_free(sig_str);
2314                 }
2315         }
2316
2317         return utf8_sig_str;
2318 }
2319
2320 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2321 {
2322         GtkTextView *text;
2323         GtkTextBuffer *buffer;
2324         GtkTextMark *mark;
2325         GtkTextIter iter;
2326         const gchar *cur_encoding;
2327         gchar buf[BUFFSIZE];
2328         gint len;
2329         FILE *fp;
2330         gboolean prev_autowrap;
2331         gboolean badtxt = FALSE;
2332
2333         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2334
2335         if ((fp = fopen(file, "rb")) == NULL) {
2336                 FILE_OP_ERROR(file, "fopen");
2337                 return COMPOSE_INSERT_READ_ERROR;
2338         }
2339
2340         prev_autowrap = compose->autowrap;
2341         compose->autowrap = FALSE;
2342
2343         text = GTK_TEXT_VIEW(compose->text);
2344         buffer = gtk_text_view_get_buffer(text);
2345         mark = gtk_text_buffer_get_insert(buffer);
2346         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2347
2348         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2349                                         G_CALLBACK(text_inserted),
2350                                         compose);
2351
2352         cur_encoding = conv_get_locale_charset_str();
2353
2354         while (fgets(buf, sizeof(buf), fp) != NULL) {
2355                 gchar *str;
2356
2357                 if (g_utf8_validate(buf, -1, NULL) == TRUE)
2358                         str = g_strdup(buf);
2359                 else
2360                         str = conv_codeset_strdup
2361                                 (buf, cur_encoding, CS_INTERNAL);
2362                 if (!str) continue;
2363
2364                 /* strip <CR> if DOS/Windows file,
2365                    replace <CR> with <LF> if Macintosh file. */
2366                 strcrchomp(str);
2367                 len = strlen(str);
2368                 if (len > 0 && str[len - 1] != '\n') {
2369                         while (--len >= 0)
2370                                 if (str[len] == '\r') str[len] = '\n';
2371                 }
2372
2373                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2374                 g_free(str);
2375         }
2376
2377         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2378                                           G_CALLBACK(text_inserted),
2379                                           compose);
2380         compose->autowrap = prev_autowrap;
2381         if (compose->autowrap)
2382                 compose_wrap_all(compose);
2383
2384         fclose(fp);
2385
2386         if (badtxt)
2387                 return COMPOSE_INSERT_INVALID_CHARACTER;
2388         else 
2389                 return COMPOSE_INSERT_SUCCESS;
2390 }
2391
2392 static void compose_attach_append(Compose *compose, const gchar *file,
2393                                   const gchar *filename,
2394                                   const gchar *content_type)
2395 {
2396         AttachInfo *ainfo;
2397         GtkTreeIter iter;
2398         FILE *fp;
2399         off_t size;
2400         GAuto *auto_ainfo;
2401         gchar *size_text;
2402         GtkListStore *store;
2403         gchar *name;
2404
2405         if (!is_file_exist(file)) {
2406                 g_warning("File %s doesn't exist\n", filename);
2407                 return;
2408         }
2409         if ((size = get_file_size(file)) < 0) {
2410                 g_warning("Can't get file size of %s\n", filename);
2411                 return;
2412         }
2413         if (size == 0) {
2414                 alertpanel_notice(_("File %s is empty."), filename);
2415                 return;
2416         }
2417         if ((fp = fopen(file, "rb")) == NULL) {
2418                 alertpanel_error(_("Can't read %s."), filename);
2419                 return;
2420         }
2421         fclose(fp);
2422
2423         ainfo = g_new0(AttachInfo, 1);
2424         auto_ainfo = g_auto_pointer_new_with_free
2425                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2426         ainfo->file = g_strdup(file);
2427
2428         if (content_type) {
2429                 ainfo->content_type = g_strdup(content_type);
2430                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2431                         MsgInfo *msginfo;
2432                         MsgFlags flags = {0, 0};
2433
2434                         if (procmime_get_encoding_for_text_file(file) == ENC_7BIT)
2435                                 ainfo->encoding = ENC_7BIT;
2436                         else
2437                                 ainfo->encoding = ENC_8BIT;
2438
2439                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2440                         if (msginfo && msginfo->subject)
2441                                 name = g_strdup(msginfo->subject);
2442                         else
2443                                 name = g_path_get_basename(filename ? filename : file);
2444
2445                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2446
2447                         procmsg_msginfo_free(msginfo);
2448                 } else {
2449                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2450                                 ainfo->encoding = procmime_get_encoding_for_text_file(file);
2451                         else
2452                                 ainfo->encoding = ENC_BASE64;
2453                         name = g_path_get_basename(filename ? filename : file);
2454                         ainfo->name = g_strdup(name);
2455                 }
2456                 g_free(name);
2457         } else {
2458                 ainfo->content_type = procmime_get_mime_type(file);
2459                 if (!ainfo->content_type) {
2460                         ainfo->content_type =
2461                                 g_strdup("application/octet-stream");
2462                         ainfo->encoding = ENC_BASE64;
2463                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2464                         ainfo->encoding =
2465                                 procmime_get_encoding_for_text_file(file);
2466                 else
2467                         ainfo->encoding = ENC_BASE64;
2468                 name = g_path_get_basename(filename ? filename : file);
2469                 ainfo->name = g_strdup(name);   
2470                 g_free(name);
2471         }
2472
2473         if (!strcmp(ainfo->content_type, "unknown")) {
2474                 g_free(ainfo->content_type);
2475                 ainfo->content_type = g_strdup("application/octet-stream");
2476         }
2477
2478         ainfo->size = size;
2479         size_text = to_human_readable(size);
2480
2481         store = GTK_LIST_STORE(gtk_tree_view_get_model
2482                         (GTK_TREE_VIEW(compose->attach_clist)));
2483                 
2484         gtk_list_store_append(store, &iter);
2485         gtk_list_store_set(store, &iter, 
2486                            COL_MIMETYPE, ainfo->content_type,
2487                            COL_SIZE, size_text,
2488                            COL_NAME, ainfo->name,
2489                            COL_DATA, ainfo,
2490                            COL_AUTODATA, auto_ainfo,
2491                            -1);
2492         
2493         g_auto_pointer_free(auto_ainfo);
2494 }
2495
2496 static void compose_use_signing(Compose *compose, gboolean use_signing)
2497 {
2498         GtkItemFactory *ifactory;
2499         GtkWidget *menuitem = NULL;
2500
2501         compose->use_signing = use_signing;
2502         ifactory = gtk_item_factory_from_widget(compose->menubar);
2503         menuitem = gtk_item_factory_get_item
2504                 (ifactory, "/Options/Sign");
2505         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2506                                        use_signing);
2507 }
2508
2509 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2510 {
2511         GtkItemFactory *ifactory;
2512         GtkWidget *menuitem = NULL;
2513
2514         compose->use_encryption = use_encryption;
2515         ifactory = gtk_item_factory_from_widget(compose->menubar);
2516         menuitem = gtk_item_factory_get_item
2517                 (ifactory, "/Options/Encrypt");
2518
2519         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2520                                        use_encryption);
2521 }
2522
2523 #define NEXT_PART_NOT_CHILD(info)  \
2524 {  \
2525         node = info->node;  \
2526         while (node->children)  \
2527                 node = g_node_last_child(node);  \
2528         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2529 }
2530
2531 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2532 {
2533         MimeInfo *mimeinfo;
2534         MimeInfo *child;
2535         MimeInfo *firsttext = NULL;
2536         MimeInfo *encrypted = NULL;
2537         GNode    *node;
2538         gchar *outfile;
2539         const gchar *partname = NULL;
2540
2541         mimeinfo = procmime_scan_message(msginfo);
2542         if (!mimeinfo) return;
2543
2544         if (mimeinfo->node->children == NULL) {
2545                 procmime_mimeinfo_free_all(mimeinfo);
2546                 return;
2547         }
2548
2549         /* find first content part */
2550         child = (MimeInfo *) mimeinfo->node->children->data;
2551         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2552                 child = (MimeInfo *)child->node->children->data;
2553
2554         if (child->type == MIMETYPE_TEXT) {
2555                 firsttext = child;
2556                 debug_print("First text part found\n");
2557         } else if (compose->mode == COMPOSE_REEDIT &&
2558                  child->type == MIMETYPE_APPLICATION &&
2559                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2560                 encrypted = (MimeInfo *)child->node->parent->data;
2561         }
2562      
2563         child = (MimeInfo *) mimeinfo->node->children->data;
2564         while (child != NULL) {
2565                 if (child == encrypted) {
2566                         /* skip this part of tree */
2567                         NEXT_PART_NOT_CHILD(child);
2568                         continue;
2569                 }
2570
2571                 if (child->type == MIMETYPE_MULTIPART) {
2572                         /* get the actual content */
2573                         child = procmime_mimeinfo_next(child);
2574                         continue;
2575                 }
2576                     
2577                 if (child == firsttext) {
2578                         child = procmime_mimeinfo_next(child);
2579                         continue;
2580                 }
2581
2582                 outfile = procmime_get_tmp_file_name(child);
2583                 if (procmime_get_part(outfile, child) < 0)
2584                         g_warning("Can't get the part of multipart message.");
2585                 else {
2586                         gchar *content_type;
2587
2588                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2589                         partname = procmime_mimeinfo_get_parameter(child, "name");
2590                         if (partname == NULL)
2591                                 partname = "";
2592                         compose_attach_append(compose, outfile, 
2593                                               partname, content_type);
2594                         g_free(content_type);
2595                 }
2596                 g_free(outfile);
2597                 NEXT_PART_NOT_CHILD(child);
2598         }
2599         procmime_mimeinfo_free_all(mimeinfo);
2600 }
2601
2602 #undef NEXT_PART_NOT_CHILD
2603
2604
2605
2606 typedef enum {
2607         WAIT_FOR_INDENT_CHAR,
2608         WAIT_FOR_INDENT_CHAR_OR_SPACE,
2609 } IndentState;
2610
2611 /* return indent length, we allow:
2612    indent characters followed by indent characters or spaces/tabs,
2613    alphabets and numbers immediately followed by indent characters,
2614    and the repeating sequences of the above
2615    If quote ends with multiple spaces, only the first one is included. */
2616 static gchar *compose_get_quote_str(GtkTextBuffer *buffer,
2617                                     const GtkTextIter *start, gint *len)
2618 {
2619         GtkTextIter iter = *start;
2620         gunichar wc;
2621         gchar ch[6];
2622         gint clen;
2623         IndentState state = WAIT_FOR_INDENT_CHAR;
2624         gboolean is_space;
2625         gboolean is_indent;
2626         gint alnum_count = 0;
2627         gint space_count = 0;
2628         gint quote_len = 0;
2629
2630         if (prefs_common.quote_chars == NULL) {
2631                 return 0 ;
2632         }
2633
2634         while (!gtk_text_iter_ends_line(&iter)) {
2635                 wc = gtk_text_iter_get_char(&iter);
2636                 if (g_unichar_iswide(wc))
2637                         break;
2638                 clen = g_unichar_to_utf8(wc, ch);
2639                 if (clen != 1)
2640                         break;
2641
2642                 is_indent = strchr(prefs_common.quote_chars, ch[0]) ? TRUE : FALSE;
2643                 is_space = g_unichar_isspace(wc);
2644
2645                 if (state == WAIT_FOR_INDENT_CHAR) {
2646                         if (!is_indent && !g_unichar_isalnum(wc))
2647                                 break;
2648                         if (is_indent) {
2649                                 quote_len += alnum_count + space_count + 1;
2650                                 alnum_count = space_count = 0;
2651                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2652                         } else
2653                                 alnum_count++;
2654                 } else if (state == WAIT_FOR_INDENT_CHAR_OR_SPACE) {
2655                         if (!is_indent && !is_space && !g_unichar_isalnum(wc))
2656                                 break;
2657                         if (is_space)
2658                                 space_count++;
2659                         else if (is_indent) {
2660                                 quote_len += alnum_count + space_count + 1;
2661                                 alnum_count = space_count = 0;
2662                         } else {
2663                                 alnum_count++;
2664                                 state = WAIT_FOR_INDENT_CHAR;
2665                         }
2666                 }
2667
2668                 gtk_text_iter_forward_char(&iter);
2669         }
2670
2671         if (quote_len > 0 && space_count > 0)
2672                 quote_len++;
2673
2674         if (len)
2675                 *len = quote_len;
2676
2677         if (quote_len > 0) {
2678                 iter = *start;
2679                 gtk_text_iter_forward_chars(&iter, quote_len);
2680                 return gtk_text_buffer_get_text(buffer, start, &iter, FALSE);
2681         }
2682
2683         return NULL;
2684 }
2685
2686 /* return TRUE if the line is itemized */
2687 static gboolean compose_is_itemized(GtkTextBuffer *buffer,
2688                                     const GtkTextIter *start)
2689 {
2690         GtkTextIter iter = *start;
2691         gunichar wc;
2692         gchar ch[6];
2693         gint clen;
2694
2695         if (gtk_text_iter_ends_line(&iter))
2696                 return FALSE;
2697
2698         while (1) {
2699                 wc = gtk_text_iter_get_char(&iter);
2700                 if (!g_unichar_isspace(wc))
2701                         break;
2702                 gtk_text_iter_forward_char(&iter);
2703                 if (gtk_text_iter_ends_line(&iter))
2704                         return FALSE;
2705         }
2706
2707         clen = g_unichar_to_utf8(wc, ch);
2708         if (clen != 1)
2709                 return FALSE;
2710
2711         if (!strchr("*-+", ch[0]))
2712                 return FALSE;
2713
2714         gtk_text_iter_forward_char(&iter);
2715         if (gtk_text_iter_ends_line(&iter))
2716                 return FALSE;
2717         wc = gtk_text_iter_get_char(&iter);
2718         if (g_unichar_isspace(wc))
2719                 return TRUE;
2720
2721         return FALSE;
2722 }
2723
2724 static gboolean compose_get_line_break_pos(GtkTextBuffer *buffer,
2725                                            const GtkTextIter *start,
2726                                            GtkTextIter *break_pos,
2727                                            gint max_col,
2728                                            gint quote_len)
2729 {
2730         GtkTextIter iter = *start, line_end = *start;
2731         PangoLogAttr *attrs;
2732         gchar *str;
2733         gchar *p;
2734         gint len;
2735         gint i;
2736         gint col = 0;
2737         gint pos = 0;
2738         gboolean can_break = FALSE;
2739         gboolean do_break = FALSE;
2740         gboolean was_white = FALSE;
2741         gboolean prev_dont_break = FALSE;
2742
2743         gtk_text_iter_forward_to_line_end(&line_end);
2744         str = gtk_text_buffer_get_text(buffer, &iter, &line_end, FALSE);
2745         len = g_utf8_strlen(str, -1);
2746         /* g_print("breaking line: %d: %s (len = %d)\n",
2747                 gtk_text_iter_get_line(&iter), str, len); */
2748         attrs = g_new(PangoLogAttr, len + 1);
2749
2750         pango_default_break(str, -1, NULL, attrs, len + 1);
2751
2752         p = str;
2753
2754         /* skip quote and leading spaces */
2755         for (i = 0; *p != '\0' && i < len; i++) {
2756                 gunichar wc;
2757
2758                 wc = g_utf8_get_char(p);
2759                 if (i >= quote_len && !g_unichar_isspace(wc))
2760                         break;
2761                 if (g_unichar_iswide(wc))
2762                         col += 2;
2763                 else if (*p == '\t')
2764                         col += 8;
2765                 else
2766                         col++;
2767                 p = g_utf8_next_char(p);
2768         }
2769
2770         for (; *p != '\0' && i < len; i++) {
2771                 PangoLogAttr *attr = attrs + i;
2772                 gunichar wc;
2773                 gint uri_len;
2774
2775                 if (attr->is_line_break && can_break && was_white && !prev_dont_break)
2776                         pos = i;
2777                 
2778                 was_white = attr->is_white;
2779
2780                 /* don't wrap URI */
2781                 if ((uri_len = get_uri_len(p)) > 0) {
2782                         col += uri_len;
2783                         if (pos > 0 && col > max_col) {
2784                                 do_break = TRUE;
2785                                 break;
2786                         }
2787                         i += uri_len - 1;
2788                         p += uri_len;
2789                         can_break = TRUE;
2790                         continue;
2791                 }
2792
2793                 wc = g_utf8_get_char(p);
2794                 if (g_unichar_iswide(wc)) {
2795                         col += 2;
2796                         if (prev_dont_break && can_break && attr->is_line_break)
2797                                 pos = i;
2798                 } else if (*p == '\t')
2799                         col += 8;
2800                 else
2801                         col++;
2802                 if (pos > 0 && col > max_col) {
2803                         do_break = TRUE;
2804                         break;
2805                 }
2806
2807                 if (*p == '-' || *p == '/')
2808                         prev_dont_break = TRUE;
2809                 else
2810                         prev_dont_break = FALSE;
2811
2812                 p = g_utf8_next_char(p);
2813                 can_break = TRUE;
2814         }
2815
2816         debug_print("compose_get_line_break_pos(): do_break = %d, pos = %d, col = %d\n", do_break, pos, col);
2817
2818         g_free(attrs);
2819         g_free(str);
2820
2821         *break_pos = *start;
2822         gtk_text_iter_set_line_offset(break_pos, pos);
2823
2824         return do_break;
2825 }
2826
2827 static gboolean compose_is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, GtkTextIter *iter) 
2828 {
2829         GtkTextIter start = *iter;
2830         GtkTextIter end_iter;
2831         int start_pos = gtk_text_iter_get_offset(&start);
2832
2833         if (!compose->account->sig_sep)
2834                 return FALSE;
2835         
2836         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
2837                 start_pos+strlen(compose->account->sig_sep));
2838
2839         /* check sig separator */
2840         if (!strcmp(gtk_text_iter_get_text(&start, &end_iter),
2841                         compose->account->sig_sep)) {
2842                 /* check end of line (\n) */
2843                 gtk_text_buffer_get_iter_at_offset(textbuf, &start,
2844                         start_pos+strlen(compose->account->sig_sep));
2845                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
2846                         start_pos+strlen(compose->account->sig_sep)+1);
2847
2848                 if (!strcmp(gtk_text_iter_get_text(&start, &end_iter),"\n"));
2849                         return TRUE;
2850                 
2851
2852         }
2853
2854         return FALSE;
2855 }
2856
2857 static gboolean compose_join_next_line(Compose *compose,
2858                                        GtkTextBuffer *buffer,
2859                                        GtkTextIter *iter,
2860                                        const gchar *quote_str)
2861 {
2862         GtkTextIter iter_ = *iter, cur, prev, next, end;
2863         PangoLogAttr attrs[3];
2864         gchar *str;
2865         gchar *next_quote_str;
2866         gunichar wc1, wc2;
2867         gint quote_len;
2868         gboolean keep_cursor = FALSE;
2869
2870         if (!gtk_text_iter_forward_line(&iter_) ||
2871             gtk_text_iter_ends_line(&iter_))
2872                 return FALSE;
2873
2874         next_quote_str = compose_get_quote_str(buffer, &iter_, &quote_len);
2875
2876         if ((quote_str || next_quote_str) &&
2877             strcmp2(quote_str, next_quote_str) != 0) {
2878                 g_free(next_quote_str);
2879                 return FALSE;
2880         }
2881         g_free(next_quote_str);
2882
2883         end = iter_;
2884         if (quote_len > 0) {
2885                 gtk_text_iter_forward_chars(&end, quote_len);
2886                 if (gtk_text_iter_ends_line(&end))
2887                         return FALSE;
2888         }
2889
2890         /* don't join itemized lines */
2891         if (compose_is_itemized(buffer, &end))
2892                 return FALSE;
2893
2894         /* don't join signature separator */
2895         if (compose_is_sig_separator(compose, buffer, &iter_))
2896                 return FALSE;
2897
2898         /* delete quote str */
2899         if (quote_len > 0)
2900                 gtk_text_buffer_delete(buffer, &iter_, &end);
2901
2902         /* delete linebreak and extra spaces */
2903         prev = cur = iter_;
2904         while (gtk_text_iter_backward_char(&cur)) {
2905                 wc1 = gtk_text_iter_get_char(&cur);
2906                 if (!g_unichar_isspace(wc1))
2907                         break;
2908                 prev = cur;
2909         }
2910         next = cur = iter_;
2911         while (!gtk_text_iter_ends_line(&cur)) {
2912                 wc1 = gtk_text_iter_get_char(&cur);
2913                 if (!g_unichar_isspace(wc1))
2914                         break;
2915                 gtk_text_iter_forward_char(&cur);
2916                 next = cur;
2917         }
2918         if (!gtk_text_iter_equal(&prev, &next)) {
2919                 GtkTextMark *mark;
2920
2921                 mark = gtk_text_buffer_get_insert(buffer);
2922                 gtk_text_buffer_get_iter_at_mark(buffer, &cur, mark);
2923                 if (gtk_text_iter_equal(&prev, &cur))
2924                         keep_cursor = TRUE;
2925                 gtk_text_buffer_delete(buffer, &prev, &next);
2926         }
2927         iter_ = prev;
2928
2929         /* insert space if required */
2930         gtk_text_iter_backward_char(&prev);
2931         wc1 = gtk_text_iter_get_char(&prev);
2932         wc2 = gtk_text_iter_get_char(&next);
2933         gtk_text_iter_forward_char(&next);
2934         str = gtk_text_buffer_get_text(buffer, &prev, &next, FALSE);
2935         pango_default_break(str, -1, NULL, attrs, 3);
2936         if (!attrs[1].is_line_break ||
2937             (!g_unichar_iswide(wc1) || !g_unichar_iswide(wc2))) {
2938                 gtk_text_buffer_insert(buffer, &iter_, " ", 1);
2939                 if (keep_cursor) {
2940                         gtk_text_iter_backward_char(&iter_);
2941                         gtk_text_buffer_place_cursor(buffer, &iter_);
2942                 }
2943         }
2944         g_free(str);
2945
2946         *iter = iter_;
2947         return TRUE;
2948 }
2949
2950 #define ADD_TXT_POS(bp_, ep_, pti_) \
2951         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
2952                 last = last->next; \
2953                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
2954                 last->next = NULL; \
2955         } else { \
2956                 g_warning("alloc error scanning URIs\n"); \
2957         }
2958
2959 static void compose_wrap_paragraph(Compose *compose, GtkTextIter *par_iter, gboolean force)
2960 {
2961         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2962         GtkTextBuffer *buffer;
2963         GtkTextIter iter, break_pos, end_of_line;
2964         gchar *quote_str = NULL;
2965         gint quote_len;
2966         gboolean wrap_quote = prefs_common.linewrap_quote;
2967         gboolean prev_autowrap = compose->autowrap;
2968         gint startq_offset = -1, noq_offset = -1;
2969         gint uri_start = -1, uri_stop = -1;
2970         gint nouri_start = -1, nouri_stop = -1;
2971
2972         compose->autowrap = FALSE;
2973
2974         buffer = gtk_text_view_get_buffer(text);
2975
2976         undo_block(compose->undostruct);
2977         
2978         if (par_iter) {
2979                 iter = *par_iter;
2980         } else {
2981                 GtkTextMark *mark;
2982                 mark = gtk_text_buffer_get_insert(buffer);
2983                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2984         }
2985
2986         /* move to paragraph start */
2987         gtk_text_iter_set_line_offset(&iter, 0);
2988         if (gtk_text_iter_ends_line(&iter)) {
2989                 while (gtk_text_iter_ends_line(&iter) &&
2990                        gtk_text_iter_forward_line(&iter))
2991                         ;
2992         } else {
2993                 while (gtk_text_iter_backward_line(&iter)) {
2994                         if (gtk_text_iter_ends_line(&iter)) {
2995                                 gtk_text_iter_forward_line(&iter);
2996                                 break;
2997                         }
2998                 }
2999         }
3000
3001         /* go until paragraph end (empty line) */
3002         while (!gtk_text_iter_ends_line(&iter)) {
3003                 gchar *scanpos = NULL;
3004                 /* parse table - in order of priority */
3005                 struct table {
3006                         const gchar *needle; /* token */
3007
3008                         /* token search function */
3009                         gchar    *(*search)     (const gchar *haystack,
3010                                                  const gchar *needle);
3011                         /* part parsing function */
3012                         gboolean  (*parse)      (const gchar *start,
3013                                                  const gchar *scanpos,
3014                                                  const gchar **bp_,
3015                                                  const gchar **ep_);
3016                         /* part to URI function */
3017                         gchar    *(*build_uri)  (const gchar *bp,
3018                                                  const gchar *ep);
3019                 };
3020
3021                 static struct table parser[] = {
3022                         {"http://",  strcasestr, get_uri_part,   make_uri_string},
3023                         {"https://", strcasestr, get_uri_part,   make_uri_string},
3024                         {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
3025                         {"www.",     strcasestr, get_uri_part,   make_http_string},
3026                         {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
3027                         {"@",        strcasestr, get_email_part, make_email_string}
3028                 };
3029                 const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
3030                 gint last_index = PARSE_ELEMS;
3031                 gint  n;
3032                 gchar *o_walk, *walk, *bp, *ep;
3033                 gint walk_pos;
3034
3035                 uri_start = uri_stop = -1;
3036                 quote_str = compose_get_quote_str(buffer, &iter, &quote_len);
3037
3038                 if (quote_str) {
3039                         if (!wrap_quote) {
3040                                 if (startq_offset == -1) {
3041                                         startq_offset = gtk_text_iter_get_offset(&iter);
3042                                 }
3043                                 goto colorize;
3044                         }
3045                         debug_print("compose_wrap_paragraph(): quote_str = '%s'\n", quote_str);
3046                         startq_offset = gtk_text_iter_get_offset(&iter);
3047                 } else {
3048                         if (startq_offset == -1)
3049                                 noq_offset = gtk_text_iter_get_offset(&iter);
3050                 }
3051
3052                 if (prev_autowrap == FALSE && !force) {
3053                         goto colorize;
3054                 }
3055                 if (compose_get_line_break_pos(buffer, &iter, &break_pos,
3056                                                prefs_common.linewrap_len,
3057                                                quote_len)) {
3058                         GtkTextIter prev, next, cur;
3059
3060                         gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3061                         
3062                         /* remove trailing spaces */
3063                         cur = break_pos;
3064                         gtk_text_iter_backward_char(&cur);
3065                         prev = next = cur;
3066                         while (!gtk_text_iter_starts_line(&cur)) {
3067                                 gunichar wc;
3068
3069                                 gtk_text_iter_backward_char(&cur);
3070                                 wc = gtk_text_iter_get_char(&cur);
3071                                 if (!g_unichar_isspace(wc))
3072                                         break;
3073                                 prev = cur;
3074                         }
3075                         if (!gtk_text_iter_equal(&prev, &next)) {
3076                                 gtk_text_buffer_delete(buffer, &prev, &next);
3077                                 break_pos = next;
3078                                 gtk_text_iter_forward_char(&break_pos);
3079                         }
3080
3081                         if (quote_str)
3082                                 gtk_text_buffer_insert(buffer, &break_pos,
3083                                                        quote_str, -1);
3084
3085                         iter = break_pos;
3086                         compose_join_next_line(compose, buffer, &iter, quote_str);
3087
3088                         /* move iter to current line start */
3089                         gtk_text_iter_set_line_offset(&iter, 0);
3090                         continue;
3091                 } else {
3092                         /* move iter to next line start */
3093                         iter = break_pos;
3094                 }
3095
3096 colorize:
3097                 end_of_line = iter;
3098                 while (!gtk_text_iter_ends_line(&end_of_line)) {
3099                         gtk_text_iter_forward_char(&end_of_line);
3100                 }
3101                 o_walk = walk = gtk_text_buffer_get_text(buffer, &iter, &end_of_line, FALSE);
3102
3103                 nouri_start = gtk_text_iter_get_offset(&iter);
3104                 nouri_stop = gtk_text_iter_get_offset(&end_of_line);
3105
3106                 walk_pos = gtk_text_iter_get_offset(&iter);
3107                 /* FIXME: this looks phony. scanning for anything in the parse table */
3108                 for (n = 0; n < PARSE_ELEMS; n++) {
3109                         gchar *tmp;
3110
3111                         tmp = parser[n].search(walk, parser[n].needle);
3112                         if (tmp) {
3113                                 if (scanpos == NULL || tmp < scanpos) {
3114                                         scanpos = tmp;
3115                                         last_index = n;
3116                                 }
3117                         }                                       
3118                 }
3119
3120                 bp = ep = 0;
3121                 if (scanpos) {
3122                         /* check if URI can be parsed */
3123                         if (parser[last_index].parse(walk, scanpos, (const gchar **)&bp,(const gchar **)&ep)
3124                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
3125                                         walk = ep;
3126                         } else
3127                                 walk = scanpos +
3128                                         strlen(parser[last_index].needle);
3129                 } 
3130                 if (bp && ep) {
3131                         uri_start = walk_pos + (bp - o_walk);
3132                         uri_stop  = walk_pos + (ep - o_walk);
3133                 }
3134                 g_free(o_walk);
3135                 gtk_text_iter_forward_line(&iter);
3136                 g_free(quote_str);
3137                 if (startq_offset != -1) {
3138                         GtkTextIter startquote, endquote;
3139                         gtk_text_buffer_get_iter_at_offset(
3140                                 buffer, &startquote, startq_offset);
3141                         endquote = iter;
3142                         gtk_text_buffer_apply_tag_by_name(
3143                                 buffer, "quote", &startquote, &endquote);
3144                         startq_offset = -1;
3145                 } else if (noq_offset != -1) {
3146                         GtkTextIter startnoquote, endnoquote;
3147                         gtk_text_buffer_get_iter_at_offset(
3148                                 buffer, &startnoquote, noq_offset);
3149                         endnoquote = iter;
3150                         gtk_text_buffer_remove_tag_by_name(
3151                                 buffer, "quote", &startnoquote, &endnoquote);
3152                         noq_offset = -1;
3153                 }
3154                 
3155                 /* always */ {
3156                         GtkTextIter nouri_start_iter, nouri_end_iter;
3157                         gtk_text_buffer_get_iter_at_offset(
3158                                 buffer, &nouri_start_iter, nouri_start);
3159                         gtk_text_buffer_get_iter_at_offset(
3160                                 buffer, &nouri_end_iter, nouri_stop);
3161                         gtk_text_buffer_remove_tag_by_name(
3162                                 buffer, "link", &nouri_start_iter, &nouri_end_iter);
3163                 }
3164                 if (uri_start > 0 && uri_stop > 0) {
3165                         GtkTextIter uri_start_iter, uri_end_iter;
3166                         gtk_text_buffer_get_iter_at_offset(
3167                                 buffer, &uri_start_iter, uri_start);
3168                         gtk_text_buffer_get_iter_at_offset(
3169                                 buffer, &uri_end_iter, uri_stop);
3170                         gtk_text_buffer_apply_tag_by_name(
3171                                 buffer, "link", &uri_start_iter, &uri_end_iter);
3172                 }
3173         }
3174
3175         if (par_iter)
3176                 *par_iter = iter;
3177
3178         undo_unblock(compose->undostruct);
3179         compose->autowrap = prev_autowrap;
3180 }
3181
3182 static void compose_wrap_all(Compose *compose)
3183 {
3184         compose_wrap_all_full(compose, FALSE);
3185 }
3186
3187 static void compose_wrap_all_full(Compose *compose, gboolean force)
3188 {
3189         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3190         GtkTextBuffer *buffer;
3191         GtkTextIter iter;
3192
3193         buffer = gtk_text_view_get_buffer(text);
3194
3195         undo_block(compose->undostruct);
3196
3197         gtk_text_buffer_get_start_iter(buffer, &iter);
3198         while (!gtk_text_iter_is_end(&iter))
3199                 compose_wrap_paragraph(compose, &iter, force);
3200
3201         undo_unblock(compose->undostruct);
3202 }
3203
3204 static void compose_set_title(Compose *compose)
3205 {
3206         gchar *str;
3207         gchar *edited;
3208
3209         edited = compose->modified ? _(" [Edited]") : "";
3210         if (compose->account && compose->account->address)
3211                 str = g_strdup_printf(_("%s - Compose message%s"),
3212                                       compose->account->address, edited);
3213         else
3214                 str = g_strdup_printf(_("Compose message%s"), edited);
3215         gtk_window_set_title(GTK_WINDOW(compose->window), str);
3216         g_free(str);
3217 }
3218
3219 /**
3220  * compose_current_mail_account:
3221  * 
3222  * Find a current mail account (the currently selected account, or the
3223  * default account, if a news account is currently selected).  If a
3224  * mail account cannot be found, display an error message.
3225  * 
3226  * Return value: Mail account, or NULL if not found.
3227  **/
3228 static PrefsAccount *
3229 compose_current_mail_account(void)
3230 {
3231         PrefsAccount *ac;
3232
3233         if (cur_account && cur_account->protocol != A_NNTP)
3234                 ac = cur_account;
3235         else {
3236                 ac = account_get_default();
3237                 if (!ac || ac->protocol == A_NNTP) {
3238                         alertpanel_error(_("Account for sending mail is not specified.\n"
3239                                            "Please select a mail account before sending."));
3240                         return NULL;
3241                 }
3242         }
3243         return ac;
3244 }
3245
3246 static void compose_select_account(Compose *compose, PrefsAccount *account,
3247                                    gboolean init)