2006-03-07 [paul] 2.0.0cvs118
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #ifndef PANGO_ENABLE_ENGINE
27 #  define PANGO_ENABLE_ENGINE
28 #endif
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32 #include <gdk/gdkkeysyms.h>
33 #include <gtk/gtkmain.h>
34 #include <gtk/gtkmenu.h>
35 #include <gtk/gtkmenuitem.h>
36 #include <gtk/gtkitemfactory.h>
37 #include <gtk/gtkcheckmenuitem.h>
38 #include <gtk/gtkoptionmenu.h>
39 #include <gtk/gtkwidget.h>
40 #include <gtk/gtkvpaned.h>
41 #include <gtk/gtkentry.h>
42 #include <gtk/gtkeditable.h>
43 #include <gtk/gtkwindow.h>
44 #include <gtk/gtksignal.h>
45 #include <gtk/gtkvbox.h>
46 #include <gtk/gtkcontainer.h>
47 #include <gtk/gtkhandlebox.h>
48 #include <gtk/gtktoolbar.h>
49 #include <gtk/gtktable.h>
50 #include <gtk/gtkhbox.h>
51 #include <gtk/gtklabel.h>
52 #include <gtk/gtkscrolledwindow.h>
53 #include <gtk/gtktreeview.h>
54 #include <gtk/gtkliststore.h>
55 #include <gtk/gtktreeselection.h>
56 #include <gtk/gtktreemodel.h>
57
58 #include <gtk/gtkdnd.h>
59 #include <gtk/gtkclipboard.h>
60 #include <pango/pango-break.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <ctype.h>
65 #include <sys/types.h>
66 #include <sys/stat.h>
67 #include <unistd.h>
68 #include <time.h>
69 #include <stdlib.h>
70 #if HAVE_SYS_WAIT_H
71 #  include <sys/wait.h>
72 #endif
73 #include <signal.h>
74 #include <errno.h>
75 #ifndef G_OS_WIN32  /* fixme we should have a configure test. */
76 #include <libgen.h>
77 #endif
78
79 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
80 #  include <wchar.h>
81 #  include <wctype.h>
82 #endif
83
84 #include "sylpheed.h"
85 #include "main.h"
86 #include "mainwindow.h"
87 #include "compose.h"
88 #include "addressbook.h"
89 #include "folderview.h"
90 #include "procmsg.h"
91 #include "menu.h"
92 #include "stock_pixmap.h"
93 #include "send_message.h"
94 #include "imap.h"
95 #include "news.h"
96 #include "customheader.h"
97 #include "prefs_common.h"
98 #include "prefs_account.h"
99 #include "action.h"
100 #include "account.h"
101 #include "filesel.h"
102 #include "procheader.h"
103 #include "procmime.h"
104 #include "statusbar.h"
105 #include "about.h"
106 #include "base64.h"
107 #include "quoted-printable.h"
108 #include "codeconv.h"
109 #include "utils.h"
110 #include "gtkutils.h"
111 #include "socket.h"
112 #include "alertpanel.h"
113 #include "manage_window.h"
114 #include "gtkshruler.h"
115 #include "folder.h"
116 #include "addr_compl.h"
117 #include "quote_fmt.h"
118 #include "undo.h"
119 #include "foldersel.h"
120 #include "toolbar.h"
121 #include "inc.h"
122 #include "message_search.h"
123
124 enum
125 {
126         COL_MIMETYPE = 0,
127         COL_SIZE     = 1,
128         COL_NAME     = 2,
129         COL_DATA     = 3,
130         COL_AUTODATA = 4,
131         N_COL_COLUMNS
132 };
133
134 #define N_ATTACH_COLS   (N_COL_COLUMNS)
135
136 typedef enum
137 {
138         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
139         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
140         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
141         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
142         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
143         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
144         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
145         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
146         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
147         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
148         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
149         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
150         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
151         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
152         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END
153 } ComposeCallAdvancedAction;
154
155 typedef enum
156 {
157         PRIORITY_HIGHEST = 1,
158         PRIORITY_HIGH,
159         PRIORITY_NORMAL,
160         PRIORITY_LOW,
161         PRIORITY_LOWEST
162 } PriorityLevel;
163
164 typedef enum
165 {
166         COMPOSE_INSERT_SUCCESS,
167         COMPOSE_INSERT_READ_ERROR,
168         COMPOSE_INSERT_INVALID_CHARACTER,
169         COMPOSE_INSERT_NO_FILE
170 } ComposeInsertResult;
171
172 typedef enum
173 {
174         COMPOSE_QUIT_EDITING,
175         COMPOSE_KEEP_EDITING,
176         COMPOSE_AUTO_SAVE
177 } ComposeDraftAction;
178
179 typedef enum
180 {
181         COMPOSE_WRITE_FOR_SEND,
182         COMPOSE_WRITE_FOR_STORE
183 } ComposeWriteType;
184
185 #define B64_LINE_SIZE           57
186 #define B64_BUFFSIZE            77
187
188 #define MAX_REFERENCES_LEN      999
189
190 static GList *compose_list = NULL;
191
192 Compose *compose_generic_new                    (PrefsAccount   *account,
193                                                  const gchar    *to,
194                                                  FolderItem     *item,
195                                                  GPtrArray      *attach_files,
196                                                  GList          *listAddress );
197
198 static Compose *compose_create                  (PrefsAccount   *account,
199                                                  ComposeMode     mode,
200                                                  gboolean batch);
201
202 static GtkWidget *compose_account_option_menu_create
203                                                 (Compose        *compose);
204 static void compose_set_out_encoding            (Compose        *compose);
205 static void compose_set_template_menu           (Compose        *compose);
206 static void compose_template_apply              (Compose        *compose,
207                                                  Template       *tmpl,
208                                                  gboolean        replace);
209 static void compose_destroy                     (Compose        *compose);
210
211 static void compose_entries_set                 (Compose        *compose,
212                                                  const gchar    *mailto);
213 static gint compose_parse_header                (Compose        *compose,
214                                                  MsgInfo        *msginfo);
215 static gchar *compose_parse_references          (const gchar    *ref,
216                                                  const gchar    *msgid);
217
218 static gchar *compose_quote_fmt                 (Compose        *compose,
219                                                  MsgInfo        *msginfo,
220                                                  const gchar    *fmt,
221                                                  const gchar    *qmark,
222                                                  const gchar    *body,
223                                                  gboolean        rewrap);
224
225 static void compose_reply_set_entry             (Compose        *compose,
226                                                  MsgInfo        *msginfo,
227                                                  gboolean        to_all,
228                                                  gboolean        to_ml,
229                                                  gboolean        to_sender,
230                                                  gboolean
231                                                  followup_and_reply_to);
232 static void compose_reedit_set_entry            (Compose        *compose,
233                                                  MsgInfo        *msginfo);
234
235 static void compose_insert_sig                  (Compose        *compose,
236                                                  gboolean        replace);
237 static gchar *compose_get_signature_str         (Compose        *compose);
238 static ComposeInsertResult compose_insert_file  (Compose        *compose,
239                                                  const gchar    *file);
240
241 static void compose_attach_append               (Compose        *compose,
242                                                  const gchar    *file,
243                                                  const gchar    *type,
244                                                  const gchar    *content_type);
245 static void compose_attach_parts                (Compose        *compose,
246                                                  MsgInfo        *msginfo);
247
248 static void compose_beautify_paragraph          (Compose        *compose,
249                                                  GtkTextIter    *par_iter,
250                                                  gboolean        force);
251 static void compose_wrap_all                    (Compose        *compose);
252 static void compose_wrap_all_full               (Compose        *compose,
253                                                  gboolean        autowrap);
254
255 static void compose_set_title                   (Compose        *compose);
256 static void compose_select_account              (Compose        *compose,
257                                                  PrefsAccount   *account,
258                                                  gboolean        init);
259
260 static PrefsAccount *compose_current_mail_account(void);
261 /* static gint compose_send                     (Compose        *compose); */
262 static gboolean compose_check_for_valid_recipient
263                                                 (Compose        *compose);
264 static gboolean compose_check_entries           (Compose        *compose,
265                                                  gboolean       check_subject);
266 static gint compose_write_to_file               (Compose        *compose,
267                                                  FILE           *fp,
268                                                  gint            action);
269 static gint compose_write_body_to_file          (Compose        *compose,
270                                                  const gchar    *file);
271 static gint compose_remove_reedit_target        (Compose        *compose,
272                                                  gboolean        force);
273 void compose_remove_draft                       (Compose        *compose);
274 static gint compose_queue                       (Compose        *compose,
275                                                  gint           *msgnum,
276                                                  FolderItem     **item,
277                                                  gchar          **msgpath);
278 static gint compose_queue_sub                   (Compose        *compose,
279                                                  gint           *msgnum,
280                                                  FolderItem     **item,
281                                                  gchar          **msgpath,
282                                                  gboolean       check_subject);
283 static void compose_add_attachments             (Compose        *compose,
284                                                  MimeInfo       *parent);
285 static gchar *compose_get_header                (Compose        *compose);
286
287 static void compose_convert_header              (Compose        *compose,
288                                                  gchar          *dest,
289                                                  gint            len,
290                                                  gchar          *src,
291                                                  gint            header_len,
292                                                  gboolean        addr_field);
293
294 static void compose_attach_info_free            (AttachInfo     *ainfo);
295 static void compose_attach_remove_selected      (Compose        *compose);
296
297 static void compose_attach_property             (Compose        *compose);
298 static void compose_attach_property_create      (gboolean       *cancelled);
299 static void attach_property_ok                  (GtkWidget      *widget,
300                                                  gboolean       *cancelled);
301 static void attach_property_cancel              (GtkWidget      *widget,
302                                                  gboolean       *cancelled);
303 static gint attach_property_delete_event        (GtkWidget      *widget,
304                                                  GdkEventAny    *event,
305                                                  gboolean       *cancelled);
306 static gboolean attach_property_key_pressed     (GtkWidget      *widget,
307                                                  GdkEventKey    *event,
308                                                  gboolean       *cancelled);
309
310 static void compose_exec_ext_editor             (Compose        *compose);
311 #ifdef G_OS_UNIX
312 static gint compose_exec_ext_editor_real        (const gchar    *file);
313 static gboolean compose_ext_editor_kill         (Compose        *compose);
314 static gboolean compose_input_cb                (GIOChannel     *source,
315                                                  GIOCondition    condition,
316                                                  gpointer        data);
317 static void compose_set_ext_editor_sensitive    (Compose        *compose,
318                                                  gboolean        sensitive);
319 #endif /* G_OS_UNIX */
320
321 static void compose_undo_state_changed          (UndoMain       *undostruct,
322                                                  gint            undo_state,
323                                                  gint            redo_state,
324                                                  gpointer        data);
325
326 static void compose_create_header_entry (Compose *compose);
327 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
328 static void compose_update_priority_menu_item(Compose * compose);
329
330 static void compose_add_field_list      ( Compose *compose,
331                                           GList *listAddress );
332
333 /* callback functions */
334
335 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
336                                          GtkAllocation  *allocation,
337                                          GtkSHRuler     *shruler);
338 static void account_activated           (GtkMenuItem    *menuitem,
339                                          gpointer        data);
340 static void attach_selected             (GtkTreeView    *tree_view, 
341                                          GtkTreePath    *tree_path,
342                                          GtkTreeViewColumn *column, 
343                                          Compose *compose);
344 static gboolean attach_button_pressed   (GtkWidget      *widget,
345                                          GdkEventButton *event,
346                                          gpointer        data);
347 static gboolean attach_key_pressed      (GtkWidget      *widget,
348                                          GdkEventKey    *event,
349                                          gpointer        data);
350
351 static void compose_send_cb             (gpointer        data,
352                                          guint           action,
353                                          GtkWidget      *widget);
354 static void compose_send_later_cb       (gpointer        data,
355                                          guint           action,
356                                          GtkWidget      *widget);
357
358 static void compose_draft_cb            (gpointer        data,
359                                          guint           action,
360                                          GtkWidget      *widget);
361
362 static void compose_attach_cb           (gpointer        data,
363                                          guint           action,
364                                          GtkWidget      *widget);
365 static void compose_insert_file_cb      (gpointer        data,
366                                          guint           action,
367                                          GtkWidget      *widget);
368 static void compose_insert_sig_cb       (gpointer        data,
369                                          guint           action,
370                                          GtkWidget      *widget);
371
372 static void compose_close_cb            (gpointer        data,
373                                          guint           action,
374                                          GtkWidget      *widget);
375
376 static void compose_set_encoding_cb     (gpointer        data,
377                                          guint           action,
378                                          GtkWidget      *widget);
379
380 static void compose_address_cb          (gpointer        data,
381                                          guint           action,
382                                          GtkWidget      *widget);
383 static void compose_template_activate_cb(GtkWidget      *widget,
384                                          gpointer        data);
385
386 static void compose_ext_editor_cb       (gpointer        data,
387                                          guint           action,
388                                          GtkWidget      *widget);
389
390 static gint compose_delete_cb           (GtkWidget      *widget,
391                                          GdkEventAny    *event,
392                                          gpointer        data);
393
394 static void compose_undo_cb             (Compose        *compose);
395 static void compose_redo_cb             (Compose        *compose);
396 static void compose_cut_cb              (Compose        *compose);
397 static void compose_copy_cb             (Compose        *compose);
398 static void compose_paste_cb            (Compose        *compose);
399 static void compose_paste_as_quote_cb   (Compose        *compose);
400 static void compose_paste_no_wrap_cb    (Compose        *compose);
401 static void compose_paste_wrap_cb       (Compose        *compose);
402 static void compose_allsel_cb           (Compose        *compose);
403
404 static void compose_advanced_action_cb  (Compose                   *compose,
405                                          ComposeCallAdvancedAction  action);
406
407 static void compose_grab_focus_cb       (GtkWidget      *widget,
408                                          Compose        *compose);
409
410 static void compose_changed_cb          (GtkTextBuffer  *textbuf,
411                                          Compose        *compose);
412
413 static void compose_wrap_cb             (gpointer        data,
414                                          guint           action,
415                                          GtkWidget      *widget);
416 static void compose_find_cb             (gpointer        data,
417                                          guint           action,
418                                          GtkWidget      *widget);
419 static void compose_toggle_autowrap_cb  (gpointer        data,
420                                          guint           action,
421                                          GtkWidget      *widget);
422
423 static void compose_toggle_ruler_cb     (gpointer        data,
424                                          guint           action,
425                                          GtkWidget      *widget);
426 static void compose_toggle_sign_cb      (gpointer        data,
427                                          guint           action,
428                                          GtkWidget      *widget);
429 static void compose_toggle_encrypt_cb   (gpointer        data,
430                                          guint           action,
431                                          GtkWidget      *widget);
432 static void compose_set_privacy_system_cb(GtkWidget      *widget,
433                                           gpointer        data);
434 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn);
435 static void activate_privacy_system     (Compose *compose, 
436                                          PrefsAccount *account,
437                                          gboolean warn);
438 static void compose_use_signing(Compose *compose, gboolean use_signing);
439 static void compose_use_encryption(Compose *compose, gboolean use_encryption);
440 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
441                                              GtkWidget *widget);
442 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
443                                              GtkWidget *widget);
444 static void compose_set_priority_cb     (gpointer        data,
445                                          guint           action,
446                                          GtkWidget      *widget);
447
448 static void compose_attach_drag_received_cb (GtkWidget          *widget,
449                                              GdkDragContext     *drag_context,
450                                              gint                x,
451                                              gint                y,
452                                              GtkSelectionData   *data,
453                                              guint               info,
454                                              guint               time,
455                                              gpointer            user_data);
456 static void compose_insert_drag_received_cb (GtkWidget          *widget,
457                                              GdkDragContext     *drag_context,
458                                              gint                x,
459                                              gint                y,
460                                              GtkSelectionData   *data,
461                                              guint               info,
462                                              guint               time,
463                                              gpointer            user_data);
464 static void compose_header_drag_received_cb (GtkWidget          *widget,
465                                              GdkDragContext     *drag_context,
466                                              gint                x,
467                                              gint                y,
468                                              GtkSelectionData   *data,
469                                              guint               info,
470                                              guint               time,
471                                              gpointer            user_data);
472
473 static gboolean compose_drag_drop           (GtkWidget *widget,
474                                              GdkDragContext *drag_context,
475                                              gint x, gint y,
476                                              guint time, gpointer user_data);
477
478 static void text_inserted               (GtkTextBuffer  *buffer,
479                                          GtkTextIter    *iter,
480                                          const gchar    *text,
481                                          gint            len,
482                                          Compose        *compose);
483 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
484                                   gboolean to_all, gboolean to_ml,
485                                   gboolean to_sender,
486                                   gboolean followup_and_reply_to,
487                                   const gchar *body);
488
489 gboolean compose_headerentry_changed_cb    (GtkWidget          *entry,
490                                             ComposeHeaderEntry *headerentry);
491 gboolean compose_headerentry_key_press_event_cb(GtkWidget              *entry,
492                                             GdkEventKey        *event,
493                                             ComposeHeaderEntry *headerentry);
494
495 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
496
497 static void compose_allow_user_actions (Compose *compose, gboolean allow);
498
499 #if USE_ASPELL
500 static void compose_check_all              (Compose *compose);
501 static void compose_highlight_all          (Compose *compose);
502 static void compose_check_backwards        (Compose *compose);
503 static void compose_check_forwards_go      (Compose *compose);
504 #endif
505
506 static gint compose_defer_auto_save_draft       (Compose        *compose);
507 static PrefsAccount *compose_guess_forward_account_from_msginfo (MsgInfo *msginfo);
508
509 static gboolean compose_close   (Compose *compose);
510
511 static GtkItemFactoryEntry compose_popup_entries[] =
512 {
513         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
514         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
515         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
516         {N_("/_Properties..."), NULL, compose_attach_property, 0, NULL}
517 };
518
519 static GtkItemFactoryEntry compose_entries[] =
520 {
521         {N_("/_Message"),                               NULL, NULL, 0, "<Branch>"},
522         {N_("/_Message/_Send"),         "<control>Return",
523                                         compose_send_cb, 0, NULL},
524         {N_("/_Message/Send _later"),   "<shift><control>S",
525                                         compose_send_later_cb,  0, NULL},
526         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
527         {N_("/_Message/_Attach file"),          "<control>M", compose_attach_cb,      0, NULL},
528         {N_("/_Message/_Insert file"),          "<control>I", compose_insert_file_cb, 0, NULL},
529         {N_("/_Message/Insert si_gnature"),     "<control>G", compose_insert_sig_cb,  0, NULL},
530         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
531         {N_("/_Message/_Save"),
532                                                 "<control>S", compose_draft_cb, COMPOSE_KEEP_EDITING, NULL},
533         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
534         {N_("/_Message/_Close"),                        "<control>W", compose_close_cb, 0, NULL},
535
536         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
537         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
538         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
539         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
540         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
541         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
542         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
543         {N_("/_Edit/Special paste"),    NULL, NULL, 0, "<Branch>"},
544         {N_("/_Edit/Special paste/as _quotation"),
545                                         NULL, compose_paste_as_quote_cb, 0, NULL},
546         {N_("/_Edit/Special paste/_wrapped"),
547                                         NULL, compose_paste_wrap_cb, 0, NULL},
548         {N_("/_Edit/Special paste/_unwrapped"),
549                                         NULL, compose_paste_no_wrap_cb, 0, NULL},
550         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
551         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
552         {N_("/_Edit/A_dvanced/Move a character backward"),
553                                         "<shift><control>B",
554                                         compose_advanced_action_cb,
555                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
556                                         NULL},
557         {N_("/_Edit/A_dvanced/Move a character forward"),
558                                         "<shift><control>F",
559                                         compose_advanced_action_cb,
560                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
561                                         NULL},
562         {N_("/_Edit/A_dvanced/Move a word backward"),
563                                         NULL, /* "<alt>B" */
564                                         compose_advanced_action_cb,
565                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
566                                         NULL},
567         {N_("/_Edit/A_dvanced/Move a word forward"),
568                                         NULL, /* "<alt>F" */
569                                         compose_advanced_action_cb,
570                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
571                                         NULL},
572         {N_("/_Edit/A_dvanced/Move to beginning of line"),
573                                         NULL, /* "<control>A" */
574                                         compose_advanced_action_cb,
575                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
576                                         NULL},
577         {N_("/_Edit/A_dvanced/Move to end of line"),
578                                         "<control>E",
579                                         compose_advanced_action_cb,
580                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
581                                         NULL},
582         {N_("/_Edit/A_dvanced/Move to previous line"),
583                                         "<control>P",
584                                         compose_advanced_action_cb,
585                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
586                                         NULL},
587         {N_("/_Edit/A_dvanced/Move to next line"),
588                                         "<control>N",
589                                         compose_advanced_action_cb,
590                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
591                                         NULL},
592         {N_("/_Edit/A_dvanced/Delete a character backward"),
593                                         "<control>H",
594                                         compose_advanced_action_cb,
595                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
596                                         NULL},
597         {N_("/_Edit/A_dvanced/Delete a character forward"),
598                                         "<control>D",
599                                         compose_advanced_action_cb,
600                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
601                                         NULL},
602         {N_("/_Edit/A_dvanced/Delete a word backward"),
603                                         NULL, /* "<control>W" */
604                                         compose_advanced_action_cb,
605                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
606                                         NULL},
607         {N_("/_Edit/A_dvanced/Delete a word forward"),
608                                         NULL, /* "<alt>D", */
609                                         compose_advanced_action_cb,
610                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
611                                         NULL},
612         {N_("/_Edit/A_dvanced/Delete line"),
613                                         "<control>U",
614                                         compose_advanced_action_cb,
615                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
616                                         NULL},
617         {N_("/_Edit/A_dvanced/Delete entire line"),
618                                         NULL,
619                                         compose_advanced_action_cb,
620                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
621                                         NULL},
622         {N_("/_Edit/A_dvanced/Delete to end of line"),
623                                         "<control>K",
624                                         compose_advanced_action_cb,
625                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END,
626                                         NULL},
627         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
628         {N_("/_Edit/_Find"),
629                                         "<control>F", compose_find_cb, 0, NULL},
630         {N_("/_Edit/---"),                      NULL, NULL, 0, "<Separator>"},
631         {N_("/_Edit/_Wrap current paragraph"),
632                                         "<control>L", compose_wrap_cb, 0, NULL},
633         {N_("/_Edit/Wrap all long _lines"),
634                                         "<control><alt>L", compose_wrap_cb, 1, NULL},
635         {N_("/_Edit/Aut_o wrapping"),   "<shift><control>L", compose_toggle_autowrap_cb, 0, "<ToggleItem>"},
636         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
637         {N_("/_Edit/Edit with e_xternal editor"),
638                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
639 #if USE_ASPELL
640         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
641         {N_("/_Spelling/_Check all or check selection"),
642                                         NULL, compose_check_all, 0, NULL},
643         {N_("/_Spelling/_Highlight all misspelled words"),
644                                         NULL, compose_highlight_all, 0, NULL},
645         {N_("/_Spelling/Check _backwards misspelled word"),
646                                         NULL, compose_check_backwards , 0, NULL},
647         {N_("/_Spelling/_Forward to next misspelled word"),
648                                         NULL, compose_check_forwards_go, 0, NULL},
649 #endif
650         {N_("/_Options"),               NULL, NULL, 0, "<Branch>"},
651         {N_("/_Options/Privacy System"),                NULL, NULL,   0, "<Branch>"},
652         {N_("/_Options/Privacy System/None"),   NULL, NULL,   0, "<RadioItem>"},
653         {N_("/_Options/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
654         {N_("/_Options/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
655         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
656         {N_("/_Options/_Priority"),     NULL,           NULL,   0, "<Branch>"},
657         {N_("/_Options/Priority/_Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
658         {N_("/_Options/Priority/Hi_gh"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Options/Priority/Highest"},
659         {N_("/_Options/Priority/_Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Options/Priority/Highest"},
660         {N_("/_Options/Priority/Lo_w"),    NULL, compose_set_priority_cb, PRIORITY_LOW, "/Options/Priority/Highest"},
661         {N_("/_Options/Priority/_Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Options/Priority/Highest"},
662         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
663         {N_("/_Options/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
664         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
665         {N_("/_Options/Remo_ve references"),    NULL, compose_toggle_remove_refs_cb, 0, "<ToggleItem>"},
666         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
667
668 #define ENC_ACTION(action) \
669         NULL, compose_set_encoding_cb, action, \
670         "/Options/Character encoding/Automatic"
671
672         {N_("/_Options/Character _encoding"), NULL, NULL, 0, "<Branch>"},
673         {N_("/_Options/Character _encoding/_Automatic"),
674                         NULL, compose_set_encoding_cb, C_AUTO, "<RadioItem>"},
675         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
676
677         {N_("/_Options/Character _encoding/7bit ascii (US-ASC_II)"),
678          ENC_ACTION(C_US_ASCII)},
679         {N_("/_Options/Character _encoding/Unicode (_UTF-8)"),
680          ENC_ACTION(C_UTF_8)},
681         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
682
683         {N_("/_Options/Character _encoding/Western European (ISO-8859-_1)"),
684          ENC_ACTION(C_ISO_8859_1)},
685         {N_("/_Options/Character _encoding/Western European (ISO-8859-15)"),
686          ENC_ACTION(C_ISO_8859_15)},
687         {N_("/_Options/Character _encoding/Western European (Windows-1252)"),
688          ENC_ACTION(C_WINDOWS_1252)},
689         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
690
691         {N_("/_Options/Character _encoding/Central European (ISO-8859-_2)"),
692          ENC_ACTION(C_ISO_8859_2)},
693         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
694
695         {N_("/_Options/Character _encoding/_Baltic (ISO-8859-13)"),
696          ENC_ACTION(C_ISO_8859_13)},
697         {N_("/_Options/Character _encoding/Baltic (ISO-8859-_4)"),
698          ENC_ACTION(C_ISO_8859_4)},
699         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
700
701         {N_("/_Options/Character _encoding/Greek (ISO-8859-_7)"),
702          ENC_ACTION(C_ISO_8859_7)},
703         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
704
705         {N_("/_Options/Character _encoding/Hebrew (ISO-8859-_8)"),
706          ENC_ACTION(C_ISO_8859_8)},
707         {N_("/_Options/Character _encoding/Hebrew (Windows-1255)"),
708          ENC_ACTION(C_WINDOWS_1255)},
709         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
710
711         {N_("/_Options/Character _encoding/Arabic (ISO-8859-_6)"),
712          ENC_ACTION(C_ISO_8859_6)},
713         {N_("/_Options/Character _encoding/Arabic (Windows-1256)"),
714          ENC_ACTION(C_CP1256)},
715         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
716
717         {N_("/_Options/Character _encoding/Turkish (ISO-8859-_9)"),
718          ENC_ACTION(C_ISO_8859_9)},
719         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
720
721         {N_("/_Options/Character _encoding/Cyrillic (ISO-8859-_5)"),
722          ENC_ACTION(C_ISO_8859_5)},
723         {N_("/_Options/Character _encoding/Cyrillic (KOI8-_R)"),
724          ENC_ACTION(C_KOI8_R)},
725         {N_("/_Options/Character _encoding/Cyrillic (KOI8-U)"),
726          ENC_ACTION(C_KOI8_U)},
727         {N_("/_Options/Character _encoding/Cyrillic (Windows-1251)"),
728          ENC_ACTION(C_WINDOWS_1251)},
729         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
730
731         {N_("/_Options/Character _encoding/Japanese (ISO-2022-_JP)"),
732          ENC_ACTION(C_ISO_2022_JP)},
733         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
734
735         {N_("/_Options/Character _encoding/Simplified Chinese (_GB2312)"),
736          ENC_ACTION(C_GB2312)},
737         {N_("/_Options/Character _encoding/Simplified Chinese (GBK)"),
738          ENC_ACTION(C_GBK)},
739         {N_("/_Options/Character _encoding/Traditional Chinese (_Big5)"),
740          ENC_ACTION(C_BIG5)},
741         {N_("/_Options/Character _encoding/Traditional Chinese (EUC-_TW)"),
742          ENC_ACTION(C_EUC_TW)},
743         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
744
745         {N_("/_Options/Character _encoding/Korean (EUC-_KR)"),
746          ENC_ACTION(C_EUC_KR)},
747         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
748
749         {N_("/_Options/Character _encoding/Thai (TIS-620)"),
750          ENC_ACTION(C_TIS_620)},
751         {N_("/_Options/Character _encoding/Thai (Windows-874)"),
752          ENC_ACTION(C_WINDOWS_874)},
753
754         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
755         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
756         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
757         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
758         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
759         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
760         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
761 };
762
763 static GtkTargetEntry compose_mime_types[] =
764 {
765         {"text/uri-list", 0, 0},
766         {"text/plain", 0, 0},
767         {"STRING", 0, 0}
768 };
769
770 static gboolean compose_put_existing_to_front(MsgInfo *info)
771 {
772         GList *compose_list = compose_get_compose_list();
773         GList *elem = NULL;
774         
775         if (compose_list) {
776                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
777                      elem = elem->next) {
778                         Compose *c = (Compose*)elem->data;
779
780                         if (!c->targetinfo || !c->targetinfo->msgid ||
781                             !info->msgid)
782                                 continue;
783
784                         if (!strcmp(c->targetinfo->msgid, info->msgid)) {
785                                 gtkut_window_popup(c->window);
786                                 return TRUE;
787                         }
788                 }
789         }
790         return FALSE;
791 }
792
793 static GdkColor quote_color = 
794         {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
795
796 static GdkColor signature_color = {
797         (gulong)0,
798         (gushort)0x7fff,
799         (gushort)0x7fff,
800         (gushort)0x7fff
801 };
802
803 static GdkColor uri_color = {
804         (gulong)0,
805         (gushort)0,
806         (gushort)0,
807         (gushort)0
808 };
809
810 static void compose_create_tags(GtkTextView *text, Compose *compose)
811 {
812         GtkTextBuffer *buffer;
813         GdkColor black = {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
814
815         buffer = gtk_text_view_get_buffer(text);
816         
817         if (prefs_common.enable_color) {
818                 /* grab the quote colors, converting from an int to a GdkColor */
819                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
820                                                &quote_color);
821                 gtkut_convert_int_to_gdk_color(prefs_common.signature_col,
822                                                &signature_color);
823                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
824                                                &uri_color);
825         } else {
826                 signature_color = quote_color = uri_color = black;
827         }
828
829         gtk_text_buffer_create_tag(buffer, "quote",
830                                    "foreground-gdk", &quote_color,
831                                    NULL);
832         gtk_text_buffer_create_tag(buffer, "signature",
833                                    "foreground-gdk", &signature_color,
834                                    NULL);
835         gtk_text_buffer_create_tag(buffer, "link",
836                                          "foreground-gdk", &uri_color,
837                                          NULL);
838         compose->no_wrap_tag = gtk_text_buffer_create_tag(buffer, "no_wrap", NULL);
839         compose->no_join_tag = gtk_text_buffer_create_tag(buffer, "no_join", NULL);
840 }
841
842 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
843                      GPtrArray *attach_files)
844 {
845         return compose_generic_new(account, mailto, NULL, attach_files, NULL);
846 }
847
848 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
849 {
850         return compose_generic_new(account, NULL, item, NULL, NULL);
851 }
852
853 Compose *compose_new_with_list( PrefsAccount *account, GList *listAddress )
854 {
855         return compose_generic_new( account, NULL, NULL, NULL, listAddress );
856 }
857
858 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
859                              GPtrArray *attach_files, GList *listAddress )
860 {
861         Compose *compose;
862         GtkTextView *textview;
863         GtkTextBuffer *textbuf;
864         GtkTextIter iter;
865         GtkItemFactory *ifactory;
866
867         if (item && item->prefs && item->prefs->enable_default_account)
868                 account = account_find_from_id(item->prefs->default_account);
869
870         if (!account) account = cur_account;
871         g_return_val_if_fail(account != NULL, NULL);
872
873         compose = compose_create(account, COMPOSE_NEW, FALSE);
874         ifactory = gtk_item_factory_from_widget(compose->menubar);
875
876         compose->replyinfo = NULL;
877         compose->fwdinfo   = NULL;
878
879         textview = GTK_TEXT_VIEW(compose->text);
880         textbuf = gtk_text_view_get_buffer(textview);
881         compose_create_tags(textview, compose);
882
883         undo_block(compose->undostruct);
884 #ifdef USE_ASPELL
885         if (item && item->prefs && item->prefs->enable_default_dictionary &&
886             compose->gtkaspell) 
887                 gtkaspell_change_dict(compose->gtkaspell, 
888                     item->prefs->default_dictionary);
889 #endif
890
891         if (account->auto_sig)
892                 compose_insert_sig(compose, FALSE);
893         gtk_text_buffer_get_start_iter(textbuf, &iter);
894         gtk_text_buffer_place_cursor(textbuf, &iter);
895
896         if (account->protocol != A_NNTP) {
897                 if (mailto && *mailto != '\0') {
898                         compose_entries_set(compose, mailto);
899
900                 } else if (item && item->prefs->enable_default_to) {
901                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
902                         compose_entry_mark_default_to(compose, item->prefs->default_to);
903                 }
904                 if (item && item->ret_rcpt) {
905                         menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
906                 }
907         } else {
908                 if (mailto) {
909                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
910                 } else if (item) {
911                         compose_entry_append(compose, item->path, COMPOSE_NEWSGROUPS);
912                 }
913                 /*
914                  * CLAWS: just don't allow return receipt request, even if the user
915                  * may want to send an email. simple but foolproof.
916                  */
917                 menu_set_sensitive(ifactory, "/Options/Request Return Receipt", FALSE); 
918         }
919         compose_add_field_list( compose, listAddress );
920
921         if (attach_files) {
922                 gint i;
923                 gchar *file;
924
925                 for (i = 0; i < attach_files->len; i++) {
926                         file = g_ptr_array_index(attach_files, i);
927                         compose_attach_append(compose, file, file, NULL);
928                 }
929         }
930
931         compose_show_first_last_header(compose, TRUE);
932
933         /* Set save folder */
934         if (item && item->prefs && item->prefs->save_copy_to_folder) {
935                 gchar *folderidentifier;
936
937                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
938                 folderidentifier = folder_item_get_identifier(item);
939                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
940                 g_free(folderidentifier);
941         }
942         
943         gtk_widget_grab_focus(compose->header_last->entry);
944
945         undo_unblock(compose->undostruct);
946
947         if (prefs_common.auto_exteditor)
948                 compose_exec_ext_editor(compose);
949
950         compose->modified = FALSE;
951         compose_set_title(compose);
952         return compose;
953 }
954
955 static void compose_force_encryption(Compose *compose, PrefsAccount *account,
956                 gboolean override_pref)
957 {
958         gchar *privacy = NULL;
959
960         g_return_if_fail(compose != NULL);
961         g_return_if_fail(account != NULL);
962
963         if (override_pref == FALSE && account->default_encrypt_reply == FALSE)
964                 return;
965
966         if (account->default_privacy_system
967         &&  strlen(account->default_privacy_system)) {
968                 privacy = account->default_privacy_system;
969         } else {
970                 GSList *privacy_avail = privacy_get_system_ids();
971                 if (privacy_avail && g_slist_length(privacy_avail)) {
972                         privacy = (gchar *)(privacy_avail->data);
973                 }
974         }
975         if (privacy != NULL) {
976                 compose->privacy_system = g_strdup(privacy);
977                 compose_update_privacy_system_menu_item(compose, FALSE);
978                 compose_use_encryption(compose, TRUE);
979         }
980 }       
981
982 static void compose_force_signing(Compose *compose, PrefsAccount *account)
983 {
984         gchar *privacy = NULL;
985
986         if (account->default_privacy_system
987         &&  strlen(account->default_privacy_system)) {
988                 privacy = account->default_privacy_system;
989         } else {
990                 GSList *privacy_avail = privacy_get_system_ids();
991                 if (privacy_avail && g_slist_length(privacy_avail)) {
992                         privacy = (gchar *)(privacy_avail->data);
993                 }
994         }
995         if (privacy != NULL) {
996                 compose->privacy_system = g_strdup(privacy);
997                 compose_update_privacy_system_menu_item(compose, FALSE);
998                 compose_use_signing(compose, TRUE);
999         }
1000 }       
1001
1002 Compose *compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
1003 {
1004         MsgInfo *msginfo;
1005         guint list_len;
1006         Compose *compose = NULL;
1007         g_return_val_if_fail(msginfo_list != NULL, NULL);
1008
1009         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
1010         g_return_val_if_fail(msginfo != NULL, NULL);
1011
1012         list_len = g_slist_length(msginfo_list);
1013
1014         switch (mode) {
1015         case COMPOSE_REPLY:
1016                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1017                               FALSE, prefs_common.default_reply_list, FALSE, body);
1018                 break;
1019         case COMPOSE_REPLY_WITH_QUOTE:
1020                 compose = compose_reply(msginfo, TRUE, 
1021                         FALSE, prefs_common.default_reply_list, FALSE, body);
1022                 break;
1023         case COMPOSE_REPLY_WITHOUT_QUOTE:
1024                 compose = compose_reply(msginfo, FALSE, 
1025                         FALSE, prefs_common.default_reply_list, FALSE, NULL);
1026                 break;
1027         case COMPOSE_REPLY_TO_SENDER:
1028                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1029                               FALSE, FALSE, TRUE, body);
1030                 break;
1031         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
1032                 compose = compose_followup_and_reply_to(msginfo,
1033                                               prefs_common.reply_with_quote,
1034                                               FALSE, FALSE, body);
1035                 break;
1036         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
1037                 compose = compose_reply(msginfo, TRUE, 
1038                         FALSE, FALSE, TRUE, body);
1039                 break;
1040         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
1041                 compose = compose_reply(msginfo, FALSE, 
1042                         FALSE, FALSE, TRUE, NULL);
1043                 break;
1044         case COMPOSE_REPLY_TO_ALL:
1045                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1046                         TRUE, FALSE, FALSE, body);
1047                 break;
1048         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
1049                 compose = compose_reply(msginfo, TRUE, 
1050                         TRUE, FALSE, FALSE, body);
1051                 break;
1052         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
1053                 compose = compose_reply(msginfo, FALSE, 
1054                         TRUE, FALSE, FALSE, NULL);
1055                 break;
1056         case COMPOSE_REPLY_TO_LIST:
1057                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1058                         FALSE, TRUE, FALSE, body);
1059                 break;
1060         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
1061                 compose = compose_reply(msginfo, TRUE, 
1062                         FALSE, TRUE, FALSE, body);
1063                 break;
1064         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
1065                 compose = compose_reply(msginfo, FALSE, 
1066                         FALSE, TRUE, FALSE, NULL);
1067                 break;
1068         case COMPOSE_FORWARD:
1069                 if (prefs_common.forward_as_attachment) {
1070                         compose = compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
1071                         return compose;
1072                 } else {
1073                         compose = compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
1074                         return compose;
1075                 }
1076                 break;
1077         case COMPOSE_FORWARD_INLINE:
1078                 /* check if we reply to more than one Message */
1079                 if (list_len == 1) {
1080                         compose = compose_forward(NULL, msginfo, FALSE, body, FALSE, FALSE);
1081                         break;
1082                 } 
1083                 /* more messages FALL THROUGH */
1084         case COMPOSE_FORWARD_AS_ATTACH:
1085                 compose = compose_forward_multiple(NULL, msginfo_list);
1086                 break;
1087         case COMPOSE_REDIRECT:
1088                 compose = compose_redirect(NULL, msginfo, FALSE);
1089                 break;
1090         default:
1091                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
1092         }
1093         return compose;
1094 }
1095
1096 Compose *compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
1097                    gboolean to_ml, gboolean to_sender, 
1098                    const gchar *body)
1099 {
1100         return compose_generic_reply(msginfo, quote, to_all, to_ml, 
1101                               to_sender, FALSE, body);
1102 }
1103
1104 Compose *compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
1105                                    gboolean to_all,
1106                                    gboolean to_sender,
1107                                    const gchar *body)
1108 {
1109         return compose_generic_reply(msginfo, quote, to_all, FALSE, 
1110                               to_sender, TRUE, body);
1111 }
1112
1113 static void compose_extract_original_charset(Compose *compose)
1114 {
1115         MsgInfo *info = NULL;
1116         if (compose->replyinfo) {
1117                 info = compose->replyinfo;
1118         } else if (compose->fwdinfo) {
1119                 info = compose->fwdinfo;
1120         } else if (compose->targetinfo) {
1121                 info = compose->targetinfo;
1122         }
1123         if (info) {
1124                 MimeInfo *mimeinfo = procmime_scan_message(info);
1125                 MimeInfo *partinfo = mimeinfo;
1126                 while (partinfo && partinfo->type != MIMETYPE_TEXT)
1127                         partinfo = procmime_mimeinfo_next(partinfo);
1128                 if (partinfo) {
1129                         compose->orig_charset = 
1130                                 g_strdup(procmime_mimeinfo_get_parameter(
1131                                                 partinfo, "charset"));
1132                 }
1133                 procmime_mimeinfo_free_all(mimeinfo);
1134         }
1135 }
1136
1137 #define SIGNAL_BLOCK(buffer) {                                  \
1138         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1139                                 G_CALLBACK(compose_changed_cb), \
1140                                 compose);                       \
1141         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1142                                 G_CALLBACK(text_inserted),      \
1143                                 compose);                       \
1144 }
1145
1146 #define SIGNAL_UNBLOCK(buffer) {                                \
1147         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1148                                 G_CALLBACK(compose_changed_cb), \
1149                                 compose);                       \
1150         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1151                                 G_CALLBACK(text_inserted),      \
1152                                 compose);                       \
1153 }
1154
1155 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
1156                                   gboolean to_all, gboolean to_ml,
1157                                   gboolean to_sender,
1158                                   gboolean followup_and_reply_to,
1159                                   const gchar *body)
1160 {
1161         GtkItemFactory *ifactory;
1162         Compose *compose;
1163         PrefsAccount *account = NULL;
1164         PrefsAccount *reply_account;
1165         GtkTextView *textview;
1166         GtkTextBuffer *textbuf;
1167
1168         g_return_val_if_fail(msginfo != NULL, NULL);
1169         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1170
1171         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
1172         
1173         g_return_val_if_fail(account != NULL, NULL);
1174
1175         if (to_sender && account->protocol == A_NNTP &&
1176             !followup_and_reply_to) {
1177                 reply_account =
1178                         account_find_from_address(account->address);
1179                 if (!reply_account)
1180                         reply_account = compose_current_mail_account();
1181                 if (!reply_account)
1182                         return NULL;
1183         } else
1184                 reply_account = account;
1185
1186         compose = compose_create(account, COMPOSE_REPLY, FALSE);
1187         ifactory = gtk_item_factory_from_widget(compose->menubar);
1188
1189         menu_set_active(ifactory, "/Options/Remove references", FALSE);
1190         menu_set_sensitive(ifactory, "/Options/Remove references", TRUE);
1191
1192         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
1193
1194         if (!compose->replyinfo)
1195                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
1196         
1197         compose_extract_original_charset(compose);
1198         
1199         if (msginfo->folder && msginfo->folder->ret_rcpt)
1200                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1201
1202         /* Set save folder */
1203         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1204                 gchar *folderidentifier;
1205
1206                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1207                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1208                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1209                 g_free(folderidentifier);
1210         }
1211
1212         if (compose_parse_header(compose, msginfo) < 0) return NULL;
1213         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
1214                                 to_sender, followup_and_reply_to);
1215         compose_show_first_last_header(compose, TRUE);
1216
1217         textview = (GTK_TEXT_VIEW(compose->text));
1218         textbuf = gtk_text_view_get_buffer(textview);
1219         compose_create_tags(textview, compose);
1220
1221         undo_block(compose->undostruct);
1222 #ifdef USE_ASPELL
1223         if (msginfo->folder && msginfo->folder->prefs && 
1224             msginfo->folder->prefs && 
1225             msginfo->folder->prefs->enable_default_dictionary &&
1226             compose->gtkaspell)
1227                 gtkaspell_change_dict(compose->gtkaspell, 
1228                     msginfo->folder->prefs->default_dictionary);
1229 #endif
1230
1231         if (quote) {
1232                 gchar *qmark;
1233
1234                 if (prefs_common.quotemark && *prefs_common.quotemark)
1235                         qmark = prefs_common.quotemark;
1236                 else
1237                         qmark = "> ";
1238
1239                 compose_quote_fmt(compose, compose->replyinfo,
1240                                   prefs_common.quotefmt,
1241                                   qmark, body, FALSE);
1242         }
1243         if (procmime_msginfo_is_encrypted(compose->replyinfo)) {
1244                 compose_force_encryption(compose, account, FALSE);
1245         }
1246
1247         SIGNAL_BLOCK(textbuf);
1248         
1249         if (account->auto_sig)
1250                 compose_insert_sig(compose, FALSE);
1251
1252         compose_wrap_all(compose);
1253
1254         SIGNAL_UNBLOCK(textbuf);
1255         
1256         gtk_widget_grab_focus(compose->text);
1257
1258         undo_unblock(compose->undostruct);
1259
1260         if (prefs_common.auto_exteditor)
1261                 compose_exec_ext_editor(compose);
1262                 
1263         compose->modified = FALSE;
1264         compose_set_title(compose);
1265         return compose;
1266 }
1267
1268 #define INSERT_FW_HEADER(var, hdr) \
1269 if (msginfo->var && *msginfo->var) { \
1270         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1271         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1272         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1273 }
1274
1275 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1276                          gboolean as_attach, const gchar *body,
1277                          gboolean no_extedit,
1278                          gboolean batch)
1279 {
1280         Compose *compose;
1281         GtkTextView *textview;
1282         GtkTextBuffer *textbuf;
1283         GtkTextIter iter;
1284
1285         g_return_val_if_fail(msginfo != NULL, NULL);
1286         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1287
1288         if (!account && 
1289             !(account = compose_guess_forward_account_from_msginfo
1290                                 (msginfo)))
1291                 account = cur_account;
1292
1293         compose = compose_create(account, COMPOSE_FORWARD, batch);
1294
1295         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1296         if (!compose->fwdinfo)
1297                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1298
1299         compose_extract_original_charset(compose);
1300
1301         if (msginfo->subject && *msginfo->subject) {
1302                 gchar *buf, *buf2, *p;
1303
1304                 buf = p = g_strdup(msginfo->subject);
1305                 p += subject_get_prefix_length(p);
1306                 memmove(buf, p, strlen(p) + 1);
1307
1308                 buf2 = g_strdup_printf("Fw: %s", buf);
1309                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1310                 
1311                 g_free(buf);
1312                 g_free(buf2);
1313         }
1314
1315         textview = GTK_TEXT_VIEW(compose->text);
1316         textbuf = gtk_text_view_get_buffer(textview);
1317         compose_create_tags(textview, compose);
1318         
1319         undo_block(compose->undostruct);
1320         if (as_attach) {
1321                 gchar *msgfile;
1322
1323                 msgfile = procmsg_get_message_file_path(msginfo);
1324                 if (!is_file_exist(msgfile))
1325                         g_warning("%s: file not exist\n", msgfile);
1326                 else
1327                         compose_attach_append(compose, msgfile, msgfile,
1328                                               "message/rfc822");
1329
1330                 g_free(msgfile);
1331         } else {
1332                 gchar *qmark;
1333                 MsgInfo *full_msginfo;
1334
1335                 full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1336                 if (!full_msginfo)
1337                         full_msginfo = procmsg_msginfo_copy(msginfo);
1338
1339                 if (prefs_common.fw_quotemark &&
1340                     *prefs_common.fw_quotemark)
1341                         qmark = prefs_common.fw_quotemark;
1342                 else
1343                         qmark = "> ";
1344
1345                 compose_quote_fmt(compose, full_msginfo,
1346                                   prefs_common.fw_quotefmt,
1347                                   qmark, body, FALSE);
1348                 compose_attach_parts(compose, msginfo);
1349
1350                 procmsg_msginfo_free(full_msginfo);
1351         }
1352
1353         SIGNAL_BLOCK(textbuf);
1354
1355         if (account->auto_sig)
1356                 compose_insert_sig(compose, FALSE);
1357
1358         compose_wrap_all(compose);
1359
1360         SIGNAL_UNBLOCK(textbuf);
1361         
1362         gtk_text_buffer_get_start_iter(textbuf, &iter);
1363         gtk_text_buffer_place_cursor(textbuf, &iter);
1364
1365         gtk_widget_grab_focus(compose->header_last->entry);
1366
1367         if (!no_extedit && prefs_common.auto_exteditor)
1368                 compose_exec_ext_editor(compose);
1369         
1370         /*save folder*/
1371         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1372                 gchar *folderidentifier;
1373
1374                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1375                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1376                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1377                 g_free(folderidentifier);
1378         }
1379
1380         undo_unblock(compose->undostruct);
1381         
1382         compose->modified = FALSE;
1383         compose_set_title(compose);
1384         return compose;
1385 }
1386
1387 #undef INSERT_FW_HEADER
1388
1389 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1390 {
1391         Compose *compose;
1392         GtkTextView *textview;
1393         GtkTextBuffer *textbuf;
1394         GtkTextIter iter;
1395         GSList *msginfo;
1396         gchar *msgfile;
1397         gboolean single_mail = TRUE;
1398         
1399         g_return_val_if_fail(msginfo_list != NULL, NULL);
1400
1401         if (g_slist_length(msginfo_list) > 1)
1402                 single_mail = FALSE;
1403
1404         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next)
1405                 if (((MsgInfo *)msginfo->data)->folder == NULL)
1406                         return NULL;
1407
1408         /* guess account from first selected message */
1409         if (!account && 
1410             !(account = compose_guess_forward_account_from_msginfo
1411                                 (msginfo_list->data)))
1412                 account = cur_account;
1413
1414         g_return_val_if_fail(account != NULL, NULL);
1415
1416         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1417                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1418                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1419         }
1420
1421         compose = compose_create(account, COMPOSE_FORWARD, FALSE);
1422
1423         textview = GTK_TEXT_VIEW(compose->text);
1424         textbuf = gtk_text_view_get_buffer(textview);
1425         compose_create_tags(textview, compose);
1426         
1427         undo_block(compose->undostruct);
1428         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1429                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1430                 if (!is_file_exist(msgfile))
1431                         g_warning("%s: file not exist\n", msgfile);
1432                 else
1433                         compose_attach_append(compose, msgfile, msgfile,
1434                                 "message/rfc822");
1435                 g_free(msgfile);
1436         }
1437         
1438         if (single_mail) {
1439                 MsgInfo *info = (MsgInfo *)msginfo_list->data;
1440                 if (info->subject && *info->subject) {
1441                         gchar *buf, *buf2, *p;
1442
1443                         buf = p = g_strdup(info->subject);
1444                         p += subject_get_prefix_length(p);
1445                         memmove(buf, p, strlen(p) + 1);
1446
1447                         buf2 = g_strdup_printf("Fw: %s", buf);
1448                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1449
1450                         g_free(buf);
1451                         g_free(buf2);
1452                 }
1453         } else {
1454                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1455                         _("Fw: multiple emails"));
1456         }
1457
1458         SIGNAL_BLOCK(textbuf);
1459         
1460         if (account->auto_sig)
1461                 compose_insert_sig(compose, FALSE);
1462
1463         compose_wrap_all(compose);
1464
1465         SIGNAL_UNBLOCK(textbuf);
1466         
1467         gtk_text_buffer_get_start_iter(textbuf, &iter);
1468         gtk_text_buffer_place_cursor(textbuf, &iter);
1469
1470         gtk_widget_grab_focus(compose->header_last->entry);
1471         undo_unblock(compose->undostruct);
1472         compose->modified = FALSE;
1473         compose_set_title(compose);
1474         return compose;
1475 }
1476
1477 static gboolean compose_is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, GtkTextIter *iter) 
1478 {
1479         GtkTextIter start = *iter;
1480         GtkTextIter end_iter;
1481         int start_pos = gtk_text_iter_get_offset(&start);
1482         gchar *str = NULL;
1483         if (!compose->account->sig_sep)
1484                 return FALSE;
1485         
1486         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1487                 start_pos+strlen(compose->account->sig_sep));
1488
1489         /* check sig separator */
1490         str = gtk_text_iter_get_text(&start, &end_iter);
1491         if (!strcmp(str, compose->account->sig_sep)) {
1492                 gchar *tmp = NULL;
1493                 /* check end of line (\n) */
1494                 gtk_text_buffer_get_iter_at_offset(textbuf, &start,
1495                         start_pos+strlen(compose->account->sig_sep));
1496                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1497                         start_pos+strlen(compose->account->sig_sep)+1);
1498                 tmp = gtk_text_iter_get_text(&start, &end_iter);
1499                 if (!strcmp(tmp,"\n")) {
1500                         g_free(str);
1501                         g_free(tmp);
1502                         return TRUE;
1503                 }
1504                 g_free(tmp);    
1505         }
1506         g_free(str);
1507
1508         return FALSE;
1509 }
1510
1511 static void compose_colorize_signature(Compose *compose)
1512 {
1513         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
1514         GtkTextIter iter;
1515         GtkTextIter end_iter;
1516         gtk_text_buffer_get_start_iter(buffer, &iter);
1517         while (gtk_text_iter_forward_line(&iter))
1518                 if (compose_is_sig_separator(compose, buffer, &iter)) {
1519                         gtk_text_buffer_get_end_iter(buffer, &end_iter);
1520                         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &end_iter);
1521                 }
1522 }
1523
1524 void compose_reedit(MsgInfo *msginfo)
1525 {
1526         Compose *compose = NULL;
1527         PrefsAccount *account = NULL;
1528         GtkTextView *textview;
1529         GtkTextBuffer *textbuf;
1530         GtkTextMark *mark;
1531         GtkTextIter iter;
1532         FILE *fp;
1533         gchar buf[BUFFSIZE];
1534         gboolean use_signing = FALSE;
1535         gboolean use_encryption = FALSE;
1536         gchar *privacy_system = NULL;
1537
1538         g_return_if_fail(msginfo != NULL);
1539         g_return_if_fail(msginfo->folder != NULL);
1540
1541         if (compose_put_existing_to_front(msginfo)) 
1542                 return;
1543
1544         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1545             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1546                 gchar queueheader_buf[BUFFSIZE];
1547                 gint id, param;
1548
1549                 /* Select Account from queue headers */
1550                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1551                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1552                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1553                         account = account_find_from_id(id);
1554                 }
1555                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1556                                              sizeof(queueheader_buf), "NAID:")) {
1557                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1558                         account = account_find_from_id(id);
1559                 }
1560                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1561                                                     sizeof(queueheader_buf), "MAID:")) {
1562                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1563                         account = account_find_from_id(id);
1564                 }
1565                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1566                                                                 sizeof(queueheader_buf), "S:")) {
1567                         account = account_find_from_address(queueheader_buf);
1568                 }
1569                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1570                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1571                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1572                         use_signing = param;
1573                         
1574                 }
1575                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1576                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1577                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1578                         use_encryption = param;
1579                 }
1580                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1581                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1582                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1583                 }
1584                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1585                                              sizeof(queueheader_buf), "X-Priority: ")) {
1586                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1587                         compose->priority = param;
1588                 }
1589         } else 
1590                 account = msginfo->folder->folder->account;
1591
1592         if (!account && prefs_common.reedit_account_autosel) {
1593                 gchar from[BUFFSIZE];
1594                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1595                         extract_address(from);
1596                         account = account_find_from_address(from);
1597                 }
1598         }
1599         if (!account) account = cur_account;
1600         g_return_if_fail(account != NULL);
1601
1602         compose = compose_create(account, COMPOSE_REEDIT, FALSE);
1603         if (privacy_system != NULL) {
1604                 compose->privacy_system = privacy_system;
1605                 compose_use_signing(compose, use_signing);
1606                 compose_use_encryption(compose, use_encryption);
1607                 compose_update_privacy_system_menu_item(compose, FALSE);
1608         } else {
1609                 activate_privacy_system(compose, account, FALSE);
1610         }
1611         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1612
1613         compose_extract_original_charset(compose);
1614
1615         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1616             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1617                 gchar queueheader_buf[BUFFSIZE];
1618
1619                 /* Set message save folder */
1620                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1621                         gint startpos = 0;
1622
1623                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1624                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1625                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1626                 }
1627                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "RRCPT:")) {
1628                         gint active = atoi(&queueheader_buf[strlen("RRCPT:")]);
1629                         if (active) {
1630                                 GtkItemFactory *ifactory;
1631                                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1632                                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1633                         }
1634                 }
1635         }
1636         
1637         if (compose_parse_header(compose, msginfo) < 0) return;
1638         compose_reedit_set_entry(compose, msginfo);
1639
1640         textview = GTK_TEXT_VIEW(compose->text);
1641         textbuf = gtk_text_view_get_buffer(textview);
1642         compose_create_tags(textview, compose);
1643
1644         mark = gtk_text_buffer_get_insert(textbuf);
1645         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1646
1647         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1648                                         G_CALLBACK(compose_changed_cb),
1649                                         compose);
1650         
1651         if (procmime_msginfo_is_encrypted(msginfo)) {
1652                 fp = procmime_get_first_encrypted_text_content(msginfo);
1653                 if (fp) 
1654                         compose_force_encryption(compose, account, TRUE);
1655         } else
1656                 fp = procmime_get_first_text_content(msginfo);
1657         if (fp == NULL)
1658                 g_warning("Can't get text part\n");
1659
1660         if (fp != NULL) {
1661                 gboolean prev_autowrap = compose->autowrap;
1662
1663                 compose->autowrap = FALSE;
1664                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1665                         strcrchomp(buf);
1666                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1667                 }
1668                 compose_wrap_all_full(compose, FALSE);
1669                 compose->autowrap = prev_autowrap;
1670                 fclose(fp);
1671         }
1672         
1673         compose_attach_parts(compose, msginfo);
1674
1675         compose_colorize_signature(compose);
1676
1677         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1678                                         G_CALLBACK(compose_changed_cb),
1679                                         compose);
1680
1681         gtk_widget_grab_focus(compose->text);
1682
1683         if (prefs_common.auto_exteditor)
1684                 compose_exec_ext_editor(compose);
1685         compose->modified = FALSE;
1686         compose_set_title(compose);
1687 }
1688
1689 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo,
1690                                                  gboolean batch)
1691 {
1692         Compose *compose;
1693         gchar *filename;
1694         GtkItemFactory *ifactory;
1695         FolderItem *item;
1696
1697         g_return_val_if_fail(msginfo != NULL, NULL);
1698
1699         if (!account)
1700                 account = account_get_reply_account(msginfo,
1701                                         prefs_common.reply_account_autosel);
1702         g_return_val_if_fail(account != NULL, NULL);
1703
1704         compose = compose_create(account, COMPOSE_REDIRECT, batch);
1705         ifactory = gtk_item_factory_from_widget(compose->menubar);
1706         compose_create_tags(GTK_TEXT_VIEW(compose->text), compose);
1707         compose->replyinfo = NULL;
1708         compose->fwdinfo = NULL;
1709
1710         compose_show_first_last_header(compose, TRUE);
1711
1712         gtk_widget_grab_focus(compose->header_last->entry);
1713
1714         filename = procmsg_get_message_file_path(msginfo);
1715         if (filename == NULL)
1716                 return NULL;
1717
1718         compose->redirect_filename = filename;
1719         
1720         /* Set save folder */
1721         item = msginfo->folder;
1722         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1723                 gchar *folderidentifier;
1724
1725                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1726                 folderidentifier = folder_item_get_identifier(item);
1727                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1728                 g_free(folderidentifier);
1729         }
1730
1731         compose_attach_parts(compose, msginfo);
1732
1733         if (msginfo->subject)
1734                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1735                                    msginfo->subject);
1736         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1737
1738         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL, FALSE);
1739         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1740
1741         compose_colorize_signature(compose);
1742
1743         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1744         menu_set_sensitive(ifactory, "/Add...", FALSE);
1745         menu_set_sensitive(ifactory, "/Remove", FALSE);
1746         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1747
1748         ifactory = gtk_item_factory_from_widget(compose->menubar);
1749         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1750         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1751         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1752         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1753         menu_set_sensitive(ifactory, "/Edit", FALSE);
1754         menu_set_sensitive(ifactory, "/Options", FALSE);
1755         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1756         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1757         
1758         if (compose->toolbar->draft_btn)
1759                 gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1760         if (compose->toolbar->insert_btn)
1761                 gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1762         if (compose->toolbar->attach_btn)
1763                 gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1764         if (compose->toolbar->sig_btn)
1765                 gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1766         if (compose->toolbar->exteditor_btn)
1767                 gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1768         if (compose->toolbar->linewrap_current_btn)
1769                 gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1770         if (compose->toolbar->linewrap_all_btn)
1771                 gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1772
1773         compose->modified = FALSE;
1774         compose_set_title(compose);
1775         return compose;
1776 }
1777
1778 GList *compose_get_compose_list(void)
1779 {
1780         return compose_list;
1781 }
1782
1783 void compose_entry_append(Compose *compose, const gchar *address,
1784                           ComposeEntryType type)
1785 {
1786         gchar *header;
1787         gchar *cur, *begin;
1788         gboolean in_quote = FALSE;
1789         if (!address || *address == '\0') return;
1790
1791         switch (type) {
1792         case COMPOSE_CC:
1793                 header = N_("Cc:");
1794                 break;
1795         case COMPOSE_BCC:
1796                 header = N_("Bcc:");
1797                 break;
1798         case COMPOSE_REPLYTO:
1799                 header = N_("Reply-To:");
1800                 break;
1801         case COMPOSE_NEWSGROUPS:
1802                 header = N_("Newsgroups:");
1803                 break;
1804         case COMPOSE_FOLLOWUPTO:
1805                 header = N_( "Followup-To:");
1806                 break;
1807         case COMPOSE_TO:
1808         default:
1809                 header = N_("To:");
1810                 break;
1811         }
1812         header = prefs_common.trans_hdr ? gettext(header) : header;
1813         
1814         cur = begin = (gchar *)address;
1815         
1816         /* we separate the line by commas, but not if we're inside a quoted
1817          * string */
1818         while (*cur != '\0') {
1819                 if (*cur == '"') 
1820                         in_quote = !in_quote;
1821                 if (*cur == ',' && !in_quote) {
1822                         gchar *tmp = g_strdup(begin);
1823                         gchar *o_tmp = tmp;
1824                         tmp[cur-begin]='\0';
1825                         cur++;
1826                         begin = cur;
1827                         while (*tmp == ' ')
1828                                 tmp++;
1829                         compose_add_header_entry(compose, header, tmp);
1830                         g_free(o_tmp);
1831                         continue;
1832                 }
1833                 cur++;
1834         }
1835         if (begin < cur) {
1836                 gchar *tmp = g_strdup(begin);
1837                 gchar *o_tmp = tmp;
1838                 tmp[cur-begin]='\0';
1839                 cur++;
1840                 begin = cur;
1841                 while (*tmp == ' ')
1842                         tmp++;
1843                 compose_add_header_entry(compose, header, tmp);
1844                 g_free(o_tmp);          
1845         }
1846 }
1847
1848 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1849 {
1850         static GdkColor yellow;
1851         static GdkColor black;
1852         static gboolean yellow_initialised = FALSE;
1853         GSList *h_list;
1854         GtkEntry *entry;
1855                 
1856         if (!yellow_initialised) {
1857                 gdk_color_parse("#f5f6be", &yellow);
1858                 gdk_color_parse("#000000", &black);
1859                 yellow_initialised = gdk_colormap_alloc_color(
1860                         gdk_colormap_get_system(), &yellow, FALSE, TRUE);
1861                 yellow_initialised &= gdk_colormap_alloc_color(
1862                         gdk_colormap_get_system(), &black, FALSE, TRUE);
1863         }
1864
1865         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1866                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1867                 if (gtk_entry_get_text(entry) && 
1868                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1869                         if (yellow_initialised) {
1870                                 gtk_widget_modify_base(
1871                                         GTK_WIDGET(((ComposeHeaderEntry *)h_list->data)->entry),
1872                                         GTK_STATE_NORMAL, &yellow);
1873                                 gtk_widget_modify_text(
1874                                         GTK_WIDGET(((ComposeHeaderEntry *)h_list->data)->entry),
1875                                         GTK_STATE_NORMAL, &black);
1876                         }
1877                 }
1878         }
1879 }
1880
1881 void compose_toolbar_cb(gint action, gpointer data)
1882 {
1883         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1884         Compose *compose = (Compose*)toolbar_item->parent;
1885         
1886         g_return_if_fail(compose != NULL);
1887
1888         switch(action) {
1889         case A_SEND:
1890                 compose_send_cb(compose, 0, NULL);
1891                 break;
1892         case A_SENDL:
1893                 compose_send_later_cb(compose, 0, NULL);
1894                 break;
1895         case A_DRAFT:
1896                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1897                 break;
1898         case A_INSERT:
1899                 compose_insert_file_cb(compose, 0, NULL);
1900                 break;
1901         case A_ATTACH:
1902                 compose_attach_cb(compose, 0, NULL);
1903                 break;
1904         case A_SIG:
1905                 compose_insert_sig(compose, FALSE);
1906                 break;
1907         case A_EXTEDITOR:
1908                 compose_ext_editor_cb(compose, 0, NULL);
1909                 break;
1910         case A_LINEWRAP_CURRENT:
1911                 compose_beautify_paragraph(compose, NULL, TRUE);
1912                 break;
1913         case A_LINEWRAP_ALL:
1914                 compose_wrap_all_full(compose, TRUE);
1915                 break;
1916         case A_ADDRBOOK:
1917                 compose_address_cb(compose, 0, NULL);
1918                 break;
1919 #ifdef USE_ASPELL
1920         case A_CHECK_SPELLING:
1921                 compose_check_all(compose);
1922                 break;
1923 #endif
1924         default:
1925                 break;
1926         }
1927 }
1928
1929 static void compose_entries_set(Compose *compose, const gchar *mailto)
1930 {
1931         gchar *to = NULL;
1932         gchar *cc = NULL;
1933         gchar *subject = NULL;
1934         gchar *body = NULL;
1935         gchar *temp = NULL;
1936         gint  len = 0;
1937
1938         scan_mailto_url(mailto, &to, &cc, NULL, &subject, &body);
1939
1940         if (to)
1941                 compose_entry_append(compose, to, COMPOSE_TO);
1942         if (cc)
1943                 compose_entry_append(compose, cc, COMPOSE_CC);
1944         if (subject) {
1945                 if (!g_utf8_validate (subject, -1, NULL)) {
1946                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1947                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1948                         g_free(temp);
1949                 } else {
1950                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1951                 }
1952         }
1953         if (body) {
1954                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1955                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1956                 GtkTextMark *mark;
1957                 GtkTextIter iter;
1958                 gboolean prev_autowrap = compose->autowrap;
1959
1960                 compose->autowrap = FALSE;
1961
1962                 mark = gtk_text_buffer_get_insert(buffer);
1963                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1964
1965                 if (!g_utf8_validate (body, -1, NULL)) {
1966                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1967                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1968                         g_free(temp);
1969                 } else {
1970                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1971                 }
1972                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1973
1974                 compose->autowrap = prev_autowrap;
1975                 if (compose->autowrap)
1976                         compose_wrap_all(compose);
1977         }
1978
1979         g_free(to);
1980         g_free(cc);
1981         g_free(subject);
1982         g_free(body);
1983 }
1984
1985 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1986 {
1987         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1988                                        {"Cc:",          NULL, TRUE},
1989                                        {"References:",  NULL, FALSE},
1990                                        {"Bcc:",         NULL, TRUE},
1991                                        {"Newsgroups:",  NULL, TRUE},
1992                                        {"Followup-To:", NULL, TRUE},
1993                                        {"List-Post:",   NULL, FALSE},
1994                                        {"X-Priority:",  NULL, FALSE},
1995                                        {NULL,           NULL, FALSE}};
1996
1997         enum
1998         {
1999                 H_REPLY_TO      = 0,
2000                 H_CC            = 1,
2001                 H_REFERENCES    = 2,
2002                 H_BCC           = 3,
2003                 H_NEWSGROUPS    = 4,
2004                 H_FOLLOWUP_TO   = 5,
2005                 H_LIST_POST     = 6,
2006                 H_X_PRIORITY    = 7
2007         };
2008
2009         FILE *fp;
2010
2011         g_return_val_if_fail(msginfo != NULL, -1);
2012
2013         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
2014         procheader_get_header_fields(fp, hentry);
2015         fclose(fp);
2016
2017         if (hentry[H_REPLY_TO].body != NULL) {
2018                 if (hentry[H_REPLY_TO].body[0] != '\0') {
2019                         compose->replyto =
2020                                 conv_unmime_header(hentry[H_REPLY_TO].body,
2021                                                    NULL);
2022                 }
2023                 g_free(hentry[H_REPLY_TO].body);
2024                 hentry[H_REPLY_TO].body = NULL;
2025         }
2026         if (hentry[H_CC].body != NULL) {
2027                 compose->cc = conv_unmime_header(hentry[H_CC].body, NULL);
2028                 g_free(hentry[H_CC].body);
2029                 hentry[H_CC].body = NULL;
2030         }
2031         if (hentry[H_REFERENCES].body != NULL) {
2032                 if (compose->mode == COMPOSE_REEDIT)
2033                         compose->references = hentry[H_REFERENCES].body;
2034                 else {
2035                         compose->references = compose_parse_references
2036                                 (hentry[H_REFERENCES].body, msginfo->msgid);
2037                         g_free(hentry[H_REFERENCES].body);
2038                 }
2039                 hentry[H_REFERENCES].body = NULL;
2040         }
2041         if (hentry[H_BCC].body != NULL) {
2042                 if (compose->mode == COMPOSE_REEDIT)
2043                         compose->bcc =
2044                                 conv_unmime_header(hentry[H_BCC].body, NULL);
2045                 g_free(hentry[H_BCC].body);
2046                 hentry[H_BCC].body = NULL;
2047         }
2048         if (hentry[H_NEWSGROUPS].body != NULL) {
2049                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
2050                 hentry[H_NEWSGROUPS].body = NULL;
2051         }
2052         if (hentry[H_FOLLOWUP_TO].body != NULL) {
2053                 if (hentry[H_FOLLOWUP_TO].body[0] != '\0') {
2054                         compose->followup_to =
2055                                 conv_unmime_header(hentry[H_FOLLOWUP_TO].body,
2056                                                    NULL);
2057                 }
2058                 g_free(hentry[H_FOLLOWUP_TO].body);
2059                 hentry[H_FOLLOWUP_TO].body = NULL;
2060         }
2061         if (hentry[H_LIST_POST].body != NULL) {
2062                 gchar *to = NULL;
2063
2064                 extract_address(hentry[H_LIST_POST].body);
2065                 if (hentry[H_LIST_POST].body[0] != '\0') {
2066                         scan_mailto_url(hentry[H_LIST_POST].body,
2067                                         &to, NULL, NULL, NULL, NULL);
2068                         if (to) {
2069                                 g_free(compose->ml_post);
2070                                 compose->ml_post = to;
2071                         }
2072                 }
2073                 g_free(hentry[H_LIST_POST].body);
2074                 hentry[H_LIST_POST].body = NULL;
2075         }
2076
2077         /* CLAWS - X-Priority */
2078         if (compose->mode == COMPOSE_REEDIT)
2079                 if (hentry[H_X_PRIORITY].body != NULL) {
2080                         gint priority;
2081                         
2082                         priority = atoi(hentry[H_X_PRIORITY].body);
2083                         g_free(hentry[H_X_PRIORITY].body);
2084                         
2085                         hentry[H_X_PRIORITY].body = NULL;
2086                         
2087                         if (priority < PRIORITY_HIGHEST || 
2088                             priority > PRIORITY_LOWEST)
2089                                 priority = PRIORITY_NORMAL;
2090                         
2091                         compose->priority =  priority;
2092                 }
2093  
2094         if (compose->mode == COMPOSE_REEDIT) {
2095                 if (msginfo->inreplyto && *msginfo->inreplyto)
2096                         compose->inreplyto = g_strdup(msginfo->inreplyto);
2097                 return 0;
2098         }
2099
2100         if (msginfo->msgid && *msginfo->msgid)
2101                 compose->inreplyto = g_strdup(msginfo->msgid);
2102
2103         if (!compose->references) {
2104                 if (msginfo->msgid && *msginfo->msgid) {
2105                         if (msginfo->inreplyto && *msginfo->inreplyto)
2106                                 compose->references =
2107                                         g_strdup_printf("<%s>\n\t<%s>",
2108                                                         msginfo->inreplyto,
2109                                                         msginfo->msgid);
2110                         else
2111                                 compose->references =
2112                                         g_strconcat("<", msginfo->msgid, ">",
2113                                                     NULL);
2114                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
2115                         compose->references =
2116                                 g_strconcat("<", msginfo->inreplyto, ">",
2117                                             NULL);
2118                 }
2119         }
2120
2121         return 0;
2122 }
2123
2124 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
2125 {
2126         GSList *ref_id_list, *cur;
2127         GString *new_ref;
2128         gchar *new_ref_str;
2129
2130         ref_id_list = references_list_append(NULL, ref);
2131         if (!ref_id_list) return NULL;
2132         if (msgid && *msgid)
2133                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
2134
2135         for (;;) {
2136                 gint len = 0;
2137
2138                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
2139                         /* "<" + Message-ID + ">" + CR+LF+TAB */
2140                         len += strlen((gchar *)cur->data) + 5;
2141
2142                 if (len > MAX_REFERENCES_LEN) {
2143                         /* remove second message-ID */
2144                         if (ref_id_list && ref_id_list->next &&
2145                             ref_id_list->next->next) {
2146                                 g_free(ref_id_list->next->data);
2147                                 ref_id_list = g_slist_remove
2148                                         (ref_id_list, ref_id_list->next->data);
2149                         } else {
2150                                 slist_free_strings(ref_id_list);
2151                                 g_slist_free(ref_id_list);
2152                                 return NULL;
2153                         }
2154                 } else
2155                         break;
2156         }
2157
2158         new_ref = g_string_new("");
2159         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
2160                 if (new_ref->len > 0)
2161                         g_string_append(new_ref, "\n\t");
2162                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
2163         }
2164
2165         slist_free_strings(ref_id_list);
2166         g_slist_free(ref_id_list);
2167
2168         new_ref_str = new_ref->str;
2169         g_string_free(new_ref, FALSE);
2170
2171         return new_ref_str;
2172 }
2173
2174 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
2175                                 const gchar *fmt, const gchar *qmark,
2176                                 const gchar *body, gboolean rewrap)
2177 {
2178         static MsgInfo dummyinfo;
2179         gchar *quote_str = NULL;
2180         gchar *buf;
2181         gboolean prev_autowrap;
2182         const gchar *trimmed_body = body;
2183         gint cursor_pos = -1;
2184         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2185         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2186         GtkTextIter iter;
2187         GtkTextMark *mark;
2188         
2189
2190         SIGNAL_BLOCK(buffer);
2191
2192         if (!msginfo)
2193                 msginfo = &dummyinfo;
2194
2195         if (qmark != NULL) {
2196                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
2197                 quote_fmt_scan_string(qmark);
2198                 quote_fmt_parse();
2199
2200                 buf = quote_fmt_get_buffer();
2201                 if (buf == NULL)
2202                         alertpanel_error(_("Quote mark format error."));
2203                 else
2204                         Xstrdup_a(quote_str, buf, goto error)
2205         }
2206
2207         if (fmt && *fmt != '\0') {
2208                 while (trimmed_body && strlen(trimmed_body) > 1
2209                         && trimmed_body[0]=='\n')
2210                         *trimmed_body++;
2211
2212                 quote_fmt_init(msginfo, quote_str, trimmed_body, FALSE);
2213                 quote_fmt_scan_string(fmt);
2214                 quote_fmt_parse();
2215
2216                 buf = quote_fmt_get_buffer();
2217                 if (buf == NULL) {
2218                         alertpanel_error(_("Message reply/forward format error."));
2219                         goto error;
2220                 }
2221         } else
2222                 buf = "";
2223
2224         prev_autowrap = compose->autowrap;
2225         compose->autowrap = FALSE;
2226
2227         mark = gtk_text_buffer_get_insert(buffer);
2228         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2229         if (g_utf8_validate(buf, -1, NULL)) { 
2230                 gtk_text_buffer_insert(buffer, &iter, buf, -1);
2231         } else {
2232                 gchar *tmpout = NULL;
2233                 tmpout = conv_codeset_strdup
2234                         (buf, conv_get_locale_charset_str(),
2235                          CS_INTERNAL);
2236                 if (!tmpout || !g_utf8_validate(tmpout, -1, NULL)) {
2237                         g_free(tmpout);
2238                         tmpout = g_malloc(strlen(buf)*2+1);
2239                         conv_localetodisp(tmpout, strlen(buf)*2+1, buf);
2240                 }
2241                 gtk_text_buffer_insert(buffer, &iter, tmpout, -1);
2242                 g_free(tmpout);
2243         }
2244
2245         cursor_pos = quote_fmt_get_cursor_pos();
2246         compose->set_cursor_pos = cursor_pos;
2247         if (cursor_pos == -1) {
2248                 cursor_pos = 0;
2249         }
2250         gtk_text_buffer_get_start_iter(buffer, &iter);
2251         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
2252         gtk_text_buffer_place_cursor(buffer, &iter);
2253
2254         compose->autowrap = prev_autowrap;
2255         if (compose->autowrap && rewrap)
2256                 compose_wrap_all(compose);
2257
2258         goto ok;
2259
2260 error:
2261         buf = NULL;
2262 ok:
2263         SIGNAL_UNBLOCK(buffer);
2264
2265
2266         return buf;
2267 }
2268
2269 /* if ml_post is of type addr@host and from is of type
2270  * addr-anything@host, return TRUE
2271  */
2272 static gboolean is_subscription(const gchar *ml_post, const gchar *from)
2273 {
2274         gchar *left_ml = NULL;
2275         gchar *right_ml = NULL;
2276         gchar *left_from = NULL;
2277         gchar *right_from = NULL;
2278         gboolean result = FALSE;
2279         
2280         if (!ml_post || !from)
2281                 return FALSE;
2282         
2283         left_ml = g_strdup(ml_post);
2284         if (strstr(left_ml, "@")) {
2285                 right_ml = strstr(left_ml, "@")+1;
2286                 *(strstr(left_ml, "@")) = '\0';
2287         }
2288         
2289         left_from = g_strdup(from);
2290         if (strstr(left_from, "@")) {
2291                 right_from = strstr(left_from, "@")+1;
2292                 *(strstr(left_from, "@")) = '\0';
2293         }
2294         
2295         if (left_ml && left_from && right_ml && right_from
2296         &&  !strncmp(left_from, left_ml, strlen(left_ml))
2297         &&  !strcmp(right_from, right_ml)) {
2298                 result = TRUE;
2299         }
2300         g_free(left_ml);
2301         g_free(left_from);
2302         
2303         return result;
2304 }
2305
2306 static gboolean same_address(const gchar *addr1, const gchar *addr2)
2307 {
2308         gchar *my_addr1, *my_addr2;
2309         
2310         if (!addr1 || !addr2)
2311                 return FALSE;
2312
2313         Xstrdup_a(my_addr1, addr1, return FALSE);
2314         Xstrdup_a(my_addr2, addr2, return FALSE);
2315         
2316         extract_address(my_addr1);
2317         extract_address(my_addr2);
2318         
2319         return !strcmp(my_addr1, my_addr2);
2320 }
2321
2322 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
2323                                     gboolean to_all, gboolean to_ml,
2324                                     gboolean to_sender,
2325                                     gboolean followup_and_reply_to)
2326 {
2327         GSList *cc_list = NULL;
2328         GSList *cur;
2329         gchar *from = NULL;
2330         gchar *replyto = NULL;
2331         GHashTable *to_table;
2332
2333         gboolean reply_to_ml = FALSE;
2334         gboolean default_reply_to = FALSE;
2335
2336         g_return_if_fail(compose->account != NULL);
2337         g_return_if_fail(msginfo != NULL);
2338
2339         reply_to_ml = to_ml && compose->ml_post;
2340
2341         default_reply_to = msginfo->folder && 
2342                 msginfo->folder->prefs->enable_default_reply_to;
2343
2344         if (compose->account->protocol != A_NNTP) {
2345                 if (reply_to_ml && !default_reply_to) {
2346                         
2347                         gboolean is_subscr = is_subscription(compose->ml_post,
2348                                                              msginfo->from);
2349                         if (!is_subscr) {
2350                                 /* normal answer to ml post with a reply-to */
2351                                 compose_entry_append(compose,
2352                                            compose->ml_post,
2353                                            COMPOSE_TO);
2354                                 if (compose->replyto
2355                                 &&  !same_address(compose->ml_post, compose->replyto))
2356                                         compose_entry_append(compose,
2357                                                 compose->replyto,
2358                                                 COMPOSE_CC);
2359                         } else {
2360                                 /* answer to subscription confirmation */
2361                                 if (compose->replyto)
2362                                         compose_entry_append(compose,
2363                                                 compose->replyto,
2364                                                 COMPOSE_TO);
2365                                 else if (msginfo->from)
2366                                         compose_entry_append(compose,
2367                                                 msginfo->from,
2368                                                 COMPOSE_TO);
2369                         }
2370                 }
2371                 else if (!(to_all || to_sender) && default_reply_to) {
2372                         compose_entry_append(compose,
2373                             msginfo->folder->prefs->default_reply_to,
2374                             COMPOSE_TO);
2375                         compose_entry_mark_default_to(compose,
2376                                 msginfo->folder->prefs->default_reply_to);
2377                 } else {
2378                         gchar *tmp1 = NULL;
2379                         Xstrdup_a(tmp1, msginfo->from, return);
2380                         extract_address(tmp1);
2381                         if (to_all || to_sender ||
2382                             !account_find_from_address(tmp1))
2383                                 compose_entry_append(compose,
2384                                  (compose->replyto && !to_sender)
2385                                           ? compose->replyto :
2386                                           msginfo->from ? msginfo->from : "",
2387                                           COMPOSE_TO);
2388                         else if (!to_all && !to_sender) {
2389                                 /* reply to the last list of recipients */
2390                                 compose_entry_append(compose,
2391                                           msginfo->to ? msginfo->to : "",
2392                                           COMPOSE_TO);
2393                                 compose_entry_append(compose,
2394                                           msginfo->cc ? msginfo->cc : "",
2395                                           COMPOSE_CC);
2396                         }
2397                 }
2398         } else {
2399                 if (to_sender || (compose->followup_to && 
2400                         !strncmp(compose->followup_to, "poster", 6)))
2401                         compose_entry_append
2402                                 (compose, 
2403                                  (compose->replyto ? compose->replyto :
2404                                         msginfo->from ? msginfo->from : ""),
2405                                  COMPOSE_TO);
2406                                  
2407                 else if (followup_and_reply_to || to_all) {
2408                         compose_entry_append
2409                                 (compose,
2410                                  (compose->replyto ? compose->replyto :
2411                                  msginfo->from ? msginfo->from : ""),
2412                                  COMPOSE_TO);                           
2413                 
2414                         compose_entry_append
2415                                 (compose,
2416                                  compose->followup_to ? compose->followup_to :
2417                                  compose->newsgroups ? compose->newsgroups : "",
2418                                  COMPOSE_NEWSGROUPS);
2419                 } 
2420                 else 
2421                         compose_entry_append
2422                                 (compose,
2423                                  compose->followup_to ? compose->followup_to :
2424                                  compose->newsgroups ? compose->newsgroups : "",
2425                                  COMPOSE_NEWSGROUPS);
2426         }
2427
2428         if (msginfo->subject && *msginfo->subject) {
2429                 gchar *buf, *buf2;
2430                 guchar *p;
2431
2432                 buf = p = g_strdup(msginfo->subject);
2433                 p += subject_get_prefix_length(p);
2434                 memmove(buf, p, strlen(p) + 1);
2435
2436                 buf2 = g_strdup_printf("Re: %s", buf);
2437                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
2438
2439                 g_free(buf2);
2440                 g_free(buf);
2441         } else
2442                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
2443
2444         if (to_ml && compose->ml_post) return;
2445         if (!to_all || compose->account->protocol == A_NNTP) return;
2446
2447         if (compose->replyto) {
2448                 Xstrdup_a(replyto, compose->replyto, return);
2449                 extract_address(replyto);
2450         }
2451         if (msginfo->from) {
2452                 Xstrdup_a(from, msginfo->from, return);
2453                 extract_address(from);
2454         }
2455
2456         if (replyto && from)
2457                 cc_list = address_list_append_with_comments(cc_list, from);
2458         if (to_all && msginfo->folder && 
2459             msginfo->folder->prefs->enable_default_reply_to)
2460                 cc_list = address_list_append_with_comments(cc_list,
2461                                 msginfo->folder->prefs->default_reply_to);
2462         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
2463         cc_list = address_list_append_with_comments(cc_list, compose->cc);
2464
2465         to_table = g_hash_table_new(g_str_hash, g_str_equal);
2466         if (replyto)
2467                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
2468         if (compose->account)
2469                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
2470                                     GINT_TO_POINTER(1));
2471
2472         /* remove address on To: and that of current account */
2473         for (cur = cc_list; cur != NULL; ) {
2474                 GSList *next = cur->next;
2475                 gchar *addr;
2476
2477                 addr = g_strdup(cur->data);
2478                 extract_address(addr);
2479
2480                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2481                         cc_list = g_slist_remove(cc_list, cur->data);
2482                 else
2483                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2484
2485                 cur = next;
2486         }
2487         hash_free_strings(to_table);
2488         g_hash_table_destroy(to_table);
2489
2490         if (cc_list) {
2491                 for (cur = cc_list; cur != NULL; cur = cur->next)
2492                         compose_entry_append(compose, (gchar *)cur->data,
2493                                              COMPOSE_CC);
2494                 slist_free_strings(cc_list);
2495                 g_slist_free(cc_list);
2496         }
2497
2498 }
2499
2500 #define SET_ENTRY(entry, str) \
2501 { \
2502         if (str && *str) \
2503                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2504 }
2505
2506 #define SET_ADDRESS(type, str) \
2507 { \
2508         if (str && *str) \
2509                 compose_entry_append(compose, str, type); \
2510 }
2511
2512 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2513 {
2514         g_return_if_fail(msginfo != NULL);
2515
2516         SET_ENTRY(subject_entry, msginfo->subject);
2517         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2518         SET_ADDRESS(COMPOSE_CC, compose->cc);
2519         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2520         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2521         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2522         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2523
2524         compose_update_priority_menu_item(compose);
2525         compose_update_privacy_system_menu_item(compose, FALSE);
2526         compose_show_first_last_header(compose, TRUE);
2527 }
2528
2529 #undef SET_ENTRY
2530 #undef SET_ADDRESS
2531
2532 static void compose_insert_sig(Compose *compose, gboolean replace)
2533 {
2534         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2535         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2536         GtkTextMark *mark;
2537         GtkTextIter iter, iter_end;
2538         gint cur_pos;
2539         gboolean prev_autowrap;
2540
2541         
2542         g_return_if_fail(compose->account != NULL);
2543
2544         prev_autowrap = compose->autowrap;
2545         compose->autowrap = FALSE;
2546
2547         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2548                                         G_CALLBACK(compose_changed_cb),
2549                                         compose);
2550         
2551         mark = gtk_text_buffer_get_insert(buffer);
2552         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2553         cur_pos = gtk_text_iter_get_offset (&iter);
2554
2555         gtk_text_buffer_get_end_iter(buffer, &iter);
2556
2557         if (replace && compose->sig_str) {
2558                 gboolean found;
2559                 GtkTextIter first_iter, start_iter, end_iter;
2560
2561                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2562
2563                 if (compose->sig_str[0] == '\0')
2564                         found = FALSE;
2565                 else
2566                         found = gtk_text_iter_forward_search(&first_iter,
2567                                                              compose->sig_str,
2568                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2569                                                              &start_iter, &end_iter,
2570                                                              NULL);
2571
2572                 if (found) {
2573                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2574                         iter = start_iter;
2575                 }
2576         }
2577
2578         g_free(compose->sig_str);
2579         compose->sig_str = compose_get_signature_str(compose);
2580         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2581                 compose->sig_str = g_strdup("");
2582
2583         cur_pos = gtk_text_iter_get_offset(&iter);
2584         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2585         /* skip \n\n */
2586         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2587         gtk_text_iter_forward_char(&iter);
2588         gtk_text_iter_forward_char(&iter);
2589         gtk_text_buffer_get_end_iter(buffer, &iter_end);
2590         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &iter_end);
2591
2592         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2593                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2594
2595         /* put the cursor where it should be 
2596          * either where the quote_fmt says, either before the signature */
2597         if (compose->set_cursor_pos < 0)
2598                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2599         else
2600                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, 
2601                         compose->set_cursor_pos);
2602                 
2603         gtk_text_buffer_place_cursor(buffer, &iter);
2604         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2605                                         G_CALLBACK(compose_changed_cb),
2606                                         compose);
2607                 
2608         compose->autowrap = prev_autowrap;
2609         if (compose->autowrap)
2610                 compose_wrap_all(compose);
2611 }
2612
2613 static gchar *compose_get_signature_str(Compose *compose)
2614 {
2615         gchar *sig_body = NULL;
2616         gchar *sig_str = NULL;
2617         gchar *utf8_sig_str = NULL;
2618
2619         g_return_val_if_fail(compose->account != NULL, NULL);
2620
2621         if (!compose->account->sig_path)
2622                 return NULL;
2623
2624         if (compose->account->sig_type == SIG_FILE) {
2625                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2626                         g_warning("can't open signature file: %s\n",
2627                                   compose->account->sig_path);
2628                         return NULL;
2629                 }
2630         }
2631
2632         if (compose->account->sig_type == SIG_COMMAND)
2633                 sig_body = get_command_output(compose->account->sig_path);
2634         else {
2635                 gchar *tmp;
2636
2637                 tmp = file_read_to_str(compose->account->sig_path);
2638                 if (!tmp)
2639                         return NULL;
2640                 sig_body = normalize_newlines(tmp);
2641                 g_free(tmp);
2642         }
2643
2644         if (compose->account->sig_sep) {
2645                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2646                                       NULL);
2647                 g_free(sig_body);
2648         } else
2649                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2650
2651         if (sig_str) {
2652                 if (g_utf8_validate(sig_str, -1, NULL) == TRUE)
2653                         utf8_sig_str = sig_str;
2654                 else {
2655                         utf8_sig_str = conv_codeset_strdup
2656                                 (sig_str, conv_get_locale_charset_str(),
2657                                  CS_INTERNAL);
2658                         g_free(sig_str);
2659                 }
2660         }
2661
2662         return utf8_sig_str;
2663 }
2664
2665 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2666 {
2667         GtkTextView *text;
2668         GtkTextBuffer *buffer;
2669         GtkTextMark *mark;
2670         GtkTextIter iter;
2671         const gchar *cur_encoding;
2672         gchar buf[BUFFSIZE];
2673         gint len;
2674         FILE *fp;
2675         gboolean prev_autowrap;
2676         gboolean badtxt = FALSE;
2677
2678         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2679
2680         if ((fp = g_fopen(file, "rb")) == NULL) {
2681                 FILE_OP_ERROR(file, "fopen");
2682                 return COMPOSE_INSERT_READ_ERROR;
2683         }
2684
2685         prev_autowrap = compose->autowrap;
2686         compose->autowrap = FALSE;
2687
2688         text = GTK_TEXT_VIEW(compose->text);
2689         buffer = gtk_text_view_get_buffer(text);
2690         mark = gtk_text_buffer_get_insert(buffer);
2691         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2692
2693         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2694                                         G_CALLBACK(text_inserted),
2695                                         compose);
2696
2697         cur_encoding = conv_get_locale_charset_str();
2698
2699         while (fgets(buf, sizeof(buf), fp) != NULL) {
2700                 gchar *str;
2701
2702                 if (g_utf8_validate(buf, -1, NULL) == TRUE)
2703                         str = g_strdup(buf);
2704                 else
2705                         str = conv_codeset_strdup
2706                                 (buf, cur_encoding, CS_INTERNAL);
2707                 if (!str) continue;
2708
2709                 /* strip <CR> if DOS/Windows file,
2710                    replace <CR> with <LF> if Macintosh file. */
2711                 strcrchomp(str);
2712                 len = strlen(str);
2713                 if (len > 0 && str[len - 1] != '\n') {
2714                         while (--len >= 0)
2715                                 if (str[len] == '\r') str[len] = '\n';
2716                 }
2717
2718                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2719                 g_free(str);
2720         }
2721
2722         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2723                                           G_CALLBACK(text_inserted),
2724                                           compose);
2725         compose->autowrap = prev_autowrap;
2726         if (compose->autowrap)
2727                 compose_wrap_all(compose);
2728
2729         fclose(fp);
2730
2731         if (badtxt)
2732                 return COMPOSE_INSERT_INVALID_CHARACTER;
2733         else 
2734                 return COMPOSE_INSERT_SUCCESS;
2735 }
2736
2737 static void compose_attach_append(Compose *compose, const gchar *file,
2738                                   const gchar *filename,
2739                                   const gchar *content_type)
2740 {
2741         AttachInfo *ainfo;
2742         GtkTreeIter iter;
2743         FILE *fp;
2744         off_t size;
2745         GAuto *auto_ainfo;
2746         gchar *size_text;
2747         GtkListStore *store;
2748         gchar *name;
2749         gboolean has_binary = FALSE;
2750
2751         if (!is_file_exist(file)) {
2752                 g_warning("File %s doesn't exist\n", filename);
2753                 return;
2754         }
2755         if ((size = get_file_size(file)) < 0) {
2756                 g_warning("Can't get file size of %s\n", filename);
2757                 return;
2758         }
2759         if (size == 0) {
2760                 alertpanel_notice(_("File %s is empty."), filename);
2761                 return;
2762         }
2763         if ((fp = g_fopen(file, "rb")) == NULL) {
2764                 alertpanel_error(_("Can't read %s."), filename);
2765                 return;
2766         }
2767         fclose(fp);
2768
2769         ainfo = g_new0(AttachInfo, 1);
2770         auto_ainfo = g_auto_pointer_new_with_free
2771                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2772         ainfo->file = g_strdup(file);
2773
2774         if (content_type) {
2775                 ainfo->content_type = g_strdup(content_type);
2776                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2777                         MsgInfo *msginfo;
2778                         MsgFlags flags = {0, 0};
2779
2780                         if (procmime_get_encoding_for_text_file(file, &has_binary) == ENC_7BIT)
2781                                 ainfo->encoding = ENC_7BIT;
2782                         else
2783                                 ainfo->encoding = ENC_8BIT;
2784
2785                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2786                         if (msginfo && msginfo->subject)
2787                                 name = g_strdup(msginfo->subject);
2788                         else
2789                                 name = g_path_get_basename(filename ? filename : file);
2790
2791                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2792
2793                         procmsg_msginfo_free(msginfo);
2794                 } else {
2795                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2796                                 ainfo->encoding = procmime_get_encoding_for_text_file(file, &has_binary);
2797                         else
2798                                 ainfo->encoding = ENC_BASE64;
2799                         name = g_path_get_basename(filename ? filename : file);
2800                         ainfo->name = g_strdup(name);
2801                 }
2802                 g_free(name);
2803         } else {
2804                 ainfo->content_type = procmime_get_mime_type(file);
2805                 if (!ainfo->content_type) {
2806                         ainfo->content_type =
2807                                 g_strdup("application/octet-stream");
2808                         ainfo->encoding = ENC_BASE64;
2809                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2810                         ainfo->encoding =
2811                                 procmime_get_encoding_for_text_file(file, &has_binary);
2812                 else
2813                         ainfo->encoding = ENC_BASE64;
2814                 name = g_path_get_basename(filename ? filename : file);
2815                 ainfo->name = g_strdup(name);   
2816                 g_free(name);
2817         }
2818
2819         if (!strcmp(ainfo->content_type, "unknown") || has_binary) {
2820                 g_free(ainfo->content_type);
2821                 ainfo->content_type = g_strdup("application/octet-stream");
2822         }
2823
2824         ainfo->size = size;
2825         size_text = to_human_readable(size);
2826
2827         store = GTK_LIST_STORE(gtk_tree_view_get_model
2828                         (GTK_TREE_VIEW(compose->attach_clist)));
2829                 
2830         gtk_list_store_append(store, &iter);
2831         gtk_list_store_set(store, &iter, 
2832                            COL_MIMETYPE, ainfo->content_type,
2833                            COL_SIZE, size_text,
2834                            COL_NAME, ainfo->name,
2835                            COL_DATA, ainfo,
2836                            COL_AUTODATA, auto_ainfo,
2837                            -1);
2838         
2839         g_auto_pointer_free(auto_ainfo);
2840 }
2841
2842 static void compose_use_signing(Compose *compose, gboolean use_signing)
2843 {
2844         GtkItemFactory *ifactory;
2845         GtkWidget *menuitem = NULL;
2846
2847         compose->use_signing = use_signing;
2848         ifactory = gtk_item_factory_from_widget(compose->menubar);
2849         menuitem = gtk_item_factory_get_item
2850                 (ifactory, "/Options/Sign");
2851         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2852                                        use_signing);
2853 }
2854
2855 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2856 {
2857         GtkItemFactory *ifactory;
2858         GtkWidget *menuitem = NULL;
2859
2860         compose->use_encryption = use_encryption;
2861         ifactory = gtk_item_factory_from_widget(compose->menubar);
2862         menuitem = gtk_item_factory_get_item
2863                 (ifactory, "/Options/Encrypt");
2864
2865         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2866                                        use_encryption);
2867 }
2868
2869 #define NEXT_PART_NOT_CHILD(info)  \
2870 {  \
2871         node = info->node;  \
2872         while (node->children)  \
2873                 node = g_node_last_child(node);  \
2874         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2875 }
2876
2877 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2878 {
2879         MimeInfo *mimeinfo;
2880         MimeInfo *child;
2881         MimeInfo *firsttext = NULL;
2882         MimeInfo *encrypted = NULL;
2883         GNode    *node;
2884         gchar *outfile;
2885         const gchar *partname = NULL;
2886
2887         mimeinfo = procmime_scan_message(msginfo);
2888         if (!mimeinfo) return;
2889
2890         if (mimeinfo->node->children == NULL) {
2891                 procmime_mimeinfo_free_all(mimeinfo);
2892                 return;
2893         }
2894
2895         /* find first content part */
2896         child = (MimeInfo *) mimeinfo->node->children->data;
2897         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2898                 child = (MimeInfo *)child->node->children->data;
2899
2900         if (child->type == MIMETYPE_TEXT) {
2901                 firsttext = child;
2902                 debug_print("First text part found\n");
2903         } else if (compose->mode == COMPOSE_REEDIT &&
2904                  child->type == MIMETYPE_APPLICATION &&
2905                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2906                 encrypted = (MimeInfo *)child->node->parent->data;
2907         }
2908      
2909         child = (MimeInfo *) mimeinfo->node->children->data;
2910         while (child != NULL) {
2911                 if (child == encrypted) {
2912                         /* skip this part of tree */
2913                         NEXT_PART_NOT_CHILD(child);
2914                         continue;
2915                 }
2916
2917                 if (child->type == MIMETYPE_MULTIPART) {
2918                         /* get the actual content */
2919                         child = procmime_mimeinfo_next(child);
2920                         continue;
2921                 }
2922                     
2923                 if (child == firsttext) {
2924                         child = procmime_mimeinfo_next(child);
2925                         continue;
2926                 }
2927
2928                 outfile = procmime_get_tmp_file_name(child);
2929                 if (procmime_get_part(outfile, child) < 0)
2930                         g_warning("Can't get the part of multipart message.");
2931                 else {
2932                         gchar *content_type;
2933
2934                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2935
2936                         /* if we meet a pgp signature, we don't attach it, but
2937                          * we force signing. */
2938                         if (strcmp(content_type, "application/pgp-signature")) {
2939                                 partname = procmime_mimeinfo_get_parameter(child, "filename");
2940                                 if (partname == NULL)
2941                                         partname = procmime_mimeinfo_get_parameter(child, "name");
2942                                 if (partname == NULL)
2943                                         partname = "";
2944                                 compose_attach_append(compose, outfile, 
2945                                                       partname, content_type);
2946                         } else {
2947                                 compose_force_signing(compose, compose->account);
2948                         }
2949                         g_free(content_type);
2950                 }
2951                 g_free(outfile);
2952                 NEXT_PART_NOT_CHILD(child);
2953         }
2954         procmime_mimeinfo_free_all(mimeinfo);
2955 }
2956
2957 #undef NEXT_PART_NOT_CHILD
2958
2959
2960
2961 typedef enum {
2962         WAIT_FOR_INDENT_CHAR,
2963         WAIT_FOR_INDENT_CHAR_OR_SPACE,
2964 } IndentState;
2965
2966 /* return indent length, we allow:
2967    indent characters followed by indent characters or spaces/tabs,
2968    alphabets and numbers immediately followed by indent characters,
2969    and the repeating sequences of the above
2970    If quote ends with multiple spaces, only the first one is included. */
2971 static gchar *compose_get_quote_str(GtkTextBuffer *buffer,
2972                                     const GtkTextIter *start, gint *len)
2973 {
2974         GtkTextIter iter = *start;
2975         gunichar wc;
2976         gchar ch[6];
2977         gint clen;
2978         IndentState state = WAIT_FOR_INDENT_CHAR;
2979         gboolean is_space;
2980         gboolean is_indent;
2981         gint alnum_count = 0;
2982         gint space_count = 0;
2983         gint quote_len = 0;
2984
2985         if (prefs_common.quote_chars == NULL) {
2986                 return 0 ;
2987         }
2988
2989         while (!gtk_text_iter_ends_line(&iter)) {
2990                 wc = gtk_text_iter_get_char(&iter);
2991                 if (g_unichar_iswide(wc))
2992                         break;
2993                 clen = g_unichar_to_utf8(wc, ch);
2994                 if (clen != 1)
2995                         break;
2996
2997                 is_indent = strchr(prefs_common.quote_chars, ch[0]) ? TRUE : FALSE;
2998                 is_space = g_unichar_isspace(wc);
2999
3000                 if (state == WAIT_FOR_INDENT_CHAR) {
3001                         if (!is_indent && !g_unichar_isalnum(wc))
3002                                 break;
3003                         if (is_indent) {
3004                                 quote_len += alnum_count + space_count + 1;
3005                                 alnum_count = space_count = 0;
3006                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
3007                         } else
3008                                 alnum_count++;
3009                 } else if (state == WAIT_FOR_INDENT_CHAR_OR_SPACE) {
3010                         if (!is_indent && !is_space && !g_unichar_isalnum(wc))
3011                                 break;
3012                         if (is_space)
3013                                 space_count++;
3014                         else if (is_indent) {
3015                                 quote_len += alnum_count + space_count + 1;
3016                                 alnum_count = space_count = 0;
3017                         } else {
3018                                 alnum_count++;
3019                                 state = WAIT_FOR_INDENT_CHAR;
3020                         }
3021                 }
3022
3023                 gtk_text_iter_forward_char(&iter);
3024         }
3025
3026         if (quote_len > 0 && space_count > 0)
3027                 quote_len++;
3028
3029         if (len)
3030                 *len = quote_len;
3031
3032         if (quote_len > 0) {
3033                 iter = *start;
3034                 gtk_text_iter_forward_chars(&iter, quote_len);
3035                 return gtk_text_buffer_get_text(buffer, start, &iter, FALSE);
3036         }
3037
3038         return NULL;
3039 }
3040
3041 /* return TRUE if the line is itemized */
3042 static gboolean compose_is_itemized(GtkTextBuffer *buffer,
3043                                     const GtkTextIter *start)
3044 {
3045         GtkTextIter iter = *start;
3046         gunichar wc;
3047         gchar ch[6];
3048         gint clen;
3049
3050         if (gtk_text_iter_ends_line(&iter))
3051                 return FALSE;
3052
3053         while (1) {
3054                 wc = gtk_text_iter_get_char(&iter);
3055                 if (!g_unichar_isspace(wc))
3056                         break;
3057                 gtk_text_iter_forward_char(&iter);
3058                 if (gtk_text_iter_ends_line(&iter))
3059                         return FALSE;
3060         }
3061
3062         clen = g_unichar_to_utf8(wc, ch);
3063         if (clen != 1)
3064                 return FALSE;
3065
3066         if (!strchr("*-+", ch[0]))
3067                 return FALSE;
3068
3069         gtk_text_iter_forward_char(&iter);
3070         if (gtk_text_iter_ends_line(&iter))
3071                 return FALSE;
3072         wc = gtk_text_iter_get_char(&iter);
3073         if (g_unichar_isspace(wc))
3074                 return TRUE;
3075
3076         return FALSE;
3077 }
3078
3079 static gboolean compose_get_line_break_pos(GtkTextBuffer *buffer,
3080                                            const GtkTextIter *start,
3081                                            GtkTextIter *break_pos,
3082                                            gint max_col,
3083                                            gint quote_len)
3084 {
3085         GtkTextIter iter = *start, line_end = *start;
3086         PangoLogAttr *attrs;
3087         gchar *str;
3088         gchar *p;
3089         gint len;
3090         gint i;
3091         gint col = 0;
3092         gint pos = 0;
3093         gboolean can_break = FALSE;
3094         gboolean do_break = FALSE;
3095         gboolean was_white = FALSE;
3096         gboolean prev_dont_break = FALSE;
3097
3098         gtk_text_iter_forward_to_line_end(&line_end);
3099         str = gtk_text_buffer_get_text(buffer, &iter, &line_end, FALSE);
3100         len = g_utf8_strlen(str, -1);
3101         /* g_print("breaking line: %d: %s (len = %d)\n",
3102                 gtk_text_iter_get_line(&iter), str, len); */
3103         attrs = g_new(PangoLogAttr, len + 1);
3104
3105         pango_default_break(str, -1, NULL, attrs, len + 1);
3106
3107         p = str;
3108
3109         /* skip quote and leading spaces */
3110         for (i = 0; *p != '\0' && i < len; i++) {
3111                 gunichar wc;
3112
3113                 wc = g_utf8_get_char(p);
3114                 if (i >= quote_len && !g_unichar_isspace(wc))
3115                         break;
3116                 if (g_unichar_iswide(wc))
3117                         col += 2;
3118                 else if (*p == '\t')
3119                         col += 8;
3120                 else
3121                         col++;
3122                 p = g_utf8_next_char(p);
3123         }
3124
3125         for (; *p != '\0' && i < len; i++) {
3126                 PangoLogAttr *attr = attrs + i;
3127                 gunichar wc;
3128                 gint uri_len;
3129
3130                 if (attr->is_line_break && can_break && was_white && !prev_dont_break)
3131                         pos = i;
3132                 
3133                 was_white = attr->is_white;
3134
3135                 /* don't wrap URI */
3136                 if ((uri_len = get_uri_len(p)) > 0) {
3137                         col += uri_len;
3138                         if (pos > 0 && col > max_col) {
3139                                 do_break = TRUE;
3140                                 break;
3141                         }
3142                         i += uri_len - 1;
3143                         p += uri_len;
3144                         can_break = TRUE;
3145                         continue;
3146                 }
3147
3148                 wc = g_utf8_get_char(p);
3149                 if (g_unichar_iswide(wc)) {
3150                         col += 2;
3151                         if (prev_dont_break && can_break && attr->is_line_break)
3152                                 pos = i;
3153                 } else if (*p == '\t')
3154                         col += 8;
3155                 else
3156                         col++;
3157                 if (pos > 0 && col > max_col) {
3158                         do_break = TRUE;
3159                         break;
3160                 }
3161
3162                 if (*p == '-' || *p == '/')
3163                         prev_dont_break = TRUE;
3164                 else
3165                         prev_dont_break = FALSE;
3166
3167                 p = g_utf8_next_char(p);
3168                 can_break = TRUE;
3169         }
3170
3171         debug_print("compose_get_line_break_pos(): do_break = %d, pos = %d, col = %d\n", do_break, pos, col);
3172
3173         g_free(attrs);
3174         g_free(str);
3175
3176         *break_pos = *start;
3177         gtk_text_iter_set_line_offset(break_pos, pos);
3178
3179         return do_break;
3180 }
3181
3182 static gboolean compose_join_next_line(Compose *compose,
3183                                        GtkTextBuffer *buffer,
3184                                        GtkTextIter *iter,
3185                                        const gchar *quote_str)
3186 {
3187         GtkTextIter iter_ = *iter, cur, prev, next, end;
3188         PangoLogAttr attrs[3];
3189         gchar *str;
3190         gchar *next_quote_str;
3191         gunichar wc1, wc2;
3192         gint quote_len;
3193         gboolean keep_cursor = FALSE;
3194
3195         if (!gtk_text_iter_forward_line(&iter_) ||
3196             gtk_text_iter_ends_line(&iter_))
3197                 return FALSE;
3198
3199         next_quote_str = compose_get_quote_str(buffer, &iter_, &quote_len);
3200
3201         if ((quote_str || next_quote_str) &&
3202             strcmp2(quote_str, next_quote_str) != 0) {
3203                 g_free(next_quote_str);
3204                 return FALSE;
3205         }
3206         g_free(next_quote_str);
3207
3208         end = iter_;
3209         if (quote_len > 0) {
3210                 gtk_text_iter_forward_chars(&end, quote_len);
3211                 if (gtk_text_iter_ends_line(&end))
3212                         return FALSE;
3213         }
3214
3215         /* don't join itemized lines */
3216         if (compose_is_itemized(buffer, &end))
3217                 return FALSE;
3218
3219         /* don't join signature separator */
3220         if (compose_is_sig_separator(compose, buffer, &iter_))
3221                 return FALSE;
3222
3223         /* delete quote str */
3224         if (quote_len > 0)
3225                 gtk_text_buffer_delete(buffer, &iter_, &end);
3226
3227         /* don't join line breaks put by the user */
3228         prev = cur = iter_;
3229         gtk_text_iter_backward_char(&cur);
3230         if (gtk_text_iter_has_tag(&cur, compose->no_join_tag)) {
3231                 gtk_text_iter_forward_char(&cur);
3232                 *iter = cur;
3233                 return FALSE;
3234         }
3235         gtk_text_iter_forward_char(&cur);
3236         /* delete linebreak and extra spaces */
3237         while (gtk_text_iter_backward_char(&cur)) {
3238                 wc1 = gtk_text_iter_get_char(&cur);
3239                 if (!g_unichar_isspace(wc1))
3240                         break;
3241                 prev = cur;
3242         }
3243         next = cur = iter_;
3244         while (!gtk_text_iter_ends_line(&cur)) {
3245                 wc1 = gtk_text_iter_get_char(&cur);
3246                 if (!g_unichar_isspace(wc1))
3247                         break;
3248                 gtk_text_iter_forward_char(&cur);
3249                 next = cur;
3250         }
3251         if (!gtk_text_iter_equal(&prev, &next)) {
3252                 GtkTextMark *mark;
3253
3254                 mark = gtk_text_buffer_get_insert(buffer);
3255                 gtk_text_buffer_get_iter_at_mark(buffer, &cur, mark);
3256                 if (gtk_text_iter_equal(&prev, &cur))
3257                         keep_cursor = TRUE;
3258                 gtk_text_buffer_delete(buffer, &prev, &next);
3259         }
3260         iter_ = prev;
3261
3262         /* insert space if required */
3263         gtk_text_iter_backward_char(&prev);
3264         wc1 = gtk_text_iter_get_char(&prev);
3265         wc2 = gtk_text_iter_get_char(&next);
3266         gtk_text_iter_forward_char(&next);
3267         str = gtk_text_buffer_get_text(buffer, &prev, &next, FALSE);
3268         pango_default_break(str, -1, NULL, attrs, 3);
3269         if (!attrs[1].is_line_break ||
3270             (!g_unichar_iswide(wc1) || !g_unichar_iswide(wc2))) {
3271                 gtk_text_buffer_insert(buffer, &iter_, " ", 1);
3272                 if (keep_cursor) {
3273                         gtk_text_iter_backward_char(&iter_);
3274                         gtk_text_buffer_place_cursor(buffer, &iter_);
3275                 }
3276         }
3277         g_free(str);
3278
3279         *iter = iter_;
3280         return TRUE;
3281 }
3282
3283 #define ADD_TXT_POS(bp_, ep_, pti_) \
3284         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
3285                 last = last->next; \
3286                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
3287                 last->next = NULL; \
3288         } else { \
3289                 g_warning("alloc error scanning URIs\n"); \
3290         }
3291
3292 static gboolean automatic_break = FALSE;
3293 static void compose_beautify_paragraph(Compose *compose, GtkTextIter *par_iter, gboolean force)
3294 {
3295         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3296         GtkTextBuffer *buffer;
3297         GtkTextIter iter, break_pos, end_of_line;
3298         gchar *quote_str = NULL;
3299         gint quote_len;
3300         gboolean wrap_quote = prefs_common.linewrap_quote;
3301         gboolean prev_autowrap = compose->autowrap;
3302         gint startq_offset = -1, noq_offset = -1;
3303         gint uri_start = -1, uri_stop = -1;
3304         gint nouri_start = -1, nouri_stop = -1;
3305         gint num_blocks = 0;
3306
3307         compose->autowrap = FALSE;
3308
3309         buffer = gtk_text_view_get_buffer(text);
3310         undo_wrapping(compose->undostruct, TRUE);
3311         if (par_iter) {
3312                 iter = *par_iter;
3313         } else {
3314                 GtkTextMark *mark;
3315                 mark = gtk_text_buffer_get_insert(buffer);
3316                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
3317         }
3318
3319         /* move to paragraph start */
3320         gtk_text_iter_set_line_offset(&iter, 0);
3321         if (gtk_text_iter_ends_line(&iter)) {
3322                 while (gtk_text_iter_ends_line(&iter) &&
3323                        gtk_text_iter_forward_line(&iter))
3324                         ;
3325         } else {
3326                 while (gtk_text_iter_backward_line(&iter)) {
3327                         if (gtk_text_iter_ends_line(&iter)) {
3328                                 gtk_text_iter_forward_line(&iter);
3329                                 break;
3330                         }
3331                 }
3332         }
3333
3334         /* go until paragraph end (empty line) */
3335         
3336         while (!gtk_text_iter_ends_line(&iter)) {
3337                 gchar *scanpos = NULL;
3338                 /* parse table - in order of priority */
3339                 struct table {
3340                         const gchar *needle; /* token */
3341
3342                         /* token search function */
3343                         gchar    *(*search)     (const gchar *haystack,
3344                                                  const gchar *needle);
3345                         /* part parsing function */
3346                         gboolean  (*parse)      (const gchar *start,
3347                                                  const gchar *scanpos,
3348                                                  const gchar **bp_,
3349                                                  const gchar **ep_,
3350                                                  gboolean hdr);
3351                         /* part to URI function */
3352                         gchar    *(*build_uri)  (const gchar *bp,
3353                                                  const gchar *ep);
3354                 };
3355
3356                 static struct table parser[] = {
3357                         {"http://",  strcasestr, get_uri_part,   make_uri_string},
3358                         {"https://", strcasestr, get_uri_part,   make_uri_string},
3359                         {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
3360                         {"www.",     strcasestr, get_uri_part,   make_http_string},
3361                         {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
3362                         {"@",        strcasestr, get_email_part, make_email_string}
3363                 };
3364                 const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
3365                 gint last_index = PARSE_ELEMS;
3366                 gint  n;
3367                 gchar *o_walk = NULL, *walk = NULL, *bp = NULL, *ep = NULL;
3368                 gint walk_pos;
3369                 
3370                 if (!prev_autowrap && num_blocks == 0) {
3371                         num_blocks++;
3372                         g_signal_handlers_block_by_func(G_OBJECT(buffer),
3373                                         G_CALLBACK(text_inserted),
3374                                         compose);
3375                 }
3376                 if (gtk_text_iter_has_tag(&iter, compose->no_wrap_tag) && !force)
3377                         goto colorize;
3378
3379                 uri_start = uri_stop = -1;
3380                 quote_len = 0;
3381                 quote_str = compose_get_quote_str(buffer, &iter, &quote_len);
3382
3383                 if (quote_str) {
3384                         if (!wrap_quote) {
3385                                 if (startq_offset == -1) {
3386                                         startq_offset = gtk_text_iter_get_offset(&iter);
3387                                 }
3388                                 goto colorize;
3389                         }
3390                         debug_print("compose_beautify_paragraph(): quote_str = '%s'\n", quote_str);
3391                         if (startq_offset == -1) 
3392                                 startq_offset = gtk_text_iter_get_offset(&iter);
3393                 } else {
3394                         if (startq_offset == -1)
3395                                 noq_offset = gtk_text_iter_get_offset(&iter);
3396                 }
3397
3398                 if (prev_autowrap == FALSE && !force && !wrap_quote) {
3399                         goto colorize;
3400                 }
3401                 if (compose_get_line_break_pos(buffer, &iter, &break_pos,
3402                                                prefs_common.linewrap_len,
3403                                                quote_len)) {
3404                         GtkTextIter prev, next, cur;
3405                         
3406                         if (prev_autowrap != FALSE || force) {
3407                                 automatic_break = TRUE;
3408                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3409                                 automatic_break = FALSE;
3410                         } else if (quote_str && wrap_quote) {
3411                                 automatic_break = TRUE;
3412                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3413                                 automatic_break = FALSE;
3414                         } else 
3415                                 goto colorize;
3416                         /* remove trailing spaces */
3417                         cur = break_pos;
3418                         gtk_text_iter_backward_char(&cur);
3419                         prev = next = cur;
3420                         while (!gtk_text_iter_starts_line(&cur)) {
3421                                 gunichar wc;
3422
3423                                 gtk_text_iter_backward_char(&cur);
3424                                 wc = gtk_text_iter_get_char(&cur);
3425                                 if (!g_unichar_isspace(wc))
3426                                         break;
3427                                 prev = cur;
3428                         }
3429                         if (!gtk_text_iter_equal(&prev, &next)) {
3430                                 gtk_text_buffer_delete(buffer, &prev, &next);
3431                                 break_pos = next;
3432                                 gtk_text_iter_forward_char(&break_pos);
3433                         }
3434
3435                         if (quote_str)
3436                                 gtk_text_buffer_insert(buffer, &break_pos,
3437                                                        quote_str, -1);
3438
3439                         iter = break_pos;
3440                         compose_join_next_line(compose, buffer, &iter, quote_str);
3441
3442                         /* move iter to current line start */
3443                         gtk_text_iter_set_line_offset(&iter, 0);
3444                         if (quote_str) {
3445                                 g_free(quote_str);
3446                                 quote_str = NULL;
3447                         }
3448                         continue;
3449                 } else {
3450                         /* move iter to next line start */
3451                         iter = break_pos;
3452                 }
3453
3454 colorize:
3455                 if (!prev_autowrap && num_blocks > 0) {
3456                         num_blocks--;
3457                         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
3458                                         G_CALLBACK(text_inserted),
3459                                         compose);
3460                 }
3461                 end_of_line = iter;
3462                 while (!gtk_text_iter_ends_line(&end_of_line)) {
3463                         gtk_text_iter_forward_char(&end_of_line);
3464                 }
3465                 o_walk = walk = gtk_text_buffer_get_text(buffer, &iter, &end_of_line, FALSE);
3466
3467                 nouri_start = gtk_text_iter_get_offset(&iter);
3468                 nouri_stop = gtk_text_iter_get_offset(&end_of_line);
3469
3470                 walk_pos = gtk_text_iter_get_offset(&iter);
3471                 /* FIXME: this looks phony. scanning for anything in the parse table */
3472                 for (n = 0; n < PARSE_ELEMS; n++) {
3473                         gchar *tmp;
3474
3475                         tmp = parser[n].search(walk, parser[n].needle);
3476                         if (tmp) {
3477                                 if (scanpos == NULL || tmp < scanpos) {
3478                                         scanpos = tmp;
3479                                         last_index = n;
3480                                 }
3481                         }                                       
3482                 }
3483
3484                 bp = ep = 0;
3485                 if (scanpos) {
3486                         /* check if URI can be parsed */
3487                         if (parser[last_index].parse(walk, scanpos, (const gchar **)&bp,
3488                                         (const gchar **)&ep, FALSE)
3489                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
3490                                         walk = ep;
3491                         } else
3492                                 walk = scanpos +
3493                                         strlen(parser[last_index].needle);
3494                 } 
3495                 if (bp && ep) {
3496                         uri_start = walk_pos + (bp - o_walk);
3497                         uri_stop  = walk_pos + (ep - o_walk);
3498                 }
3499                 g_free(o_walk);
3500                 o_walk = NULL;
3501                 gtk_text_iter_forward_line(&iter);
3502                 g_free(quote_str);
3503                 quote_str = NULL;
3504                 if (startq_offset != -1) {
3505                         GtkTextIter startquote, endquote;
3506                         gtk_text_buffer_get_iter_at_offset(
3507                                 buffer, &startquote, startq_offset);
3508                         endquote = iter;
3509                         gtk_text_buffer_apply_tag_by_name(
3510                                 buffer, "quote", &startquote, &endquote);
3511                         startq_offset = -1;
3512                 } else if (noq_offset != -1) {
3513                         GtkTextIter startnoquote, endnoquote;
3514                         gtk_text_buffer_get_iter_at_offset(
3515                                 buffer, &startnoquote, noq_offset);
3516                         endnoquote = iter;
3517                         gtk_text_buffer_remove_tag_by_name(
3518                                 buffer, "quote", &startnoquote, &endnoquote);
3519                         noq_offset = -1;
3520                 }
3521                 
3522                 /* always */ {
3523                         GtkTextIter nouri_start_iter, nouri_end_iter;
3524                         gtk_text_buffer_get_iter_at_offset(
3525                                 buffer, &nouri_start_iter, nouri_start);
3526                         gtk_text_buffer_get_iter_at_offset(
3527                                 buffer, &nouri_end_iter, nouri_stop);
3528                         gtk_text_buffer_remove_tag_by_name(
3529                                 buffer, "link", &nouri_start_iter, &nouri_end_iter);
3530                 }
3531                 if (uri_start > 0 && uri_stop > 0) {
3532                         GtkTextIter uri_start_iter, uri_end_iter;
3533                         gtk_text_buffer_get_iter_at_offset(
3534                                 buffer, &uri_start_iter, uri_start);
3535                         gtk_text_buffer_get_iter_at_offset(
3536                                 buffer, &uri_end_iter, uri_stop);
3537                         gtk_text_buffer_apply_tag_by_name(
3538                                 buffer, "link", &uri_start_iter, &uri_end_iter);
3539                 }
3540         }
3541
3542         if (par_iter)
3543                 *par_iter = iter;
3544         undo_wrapping(compose->undostruct, FALSE);
3545         compose->autowrap = prev_autowrap;
3546 }
3547
3548 void compose_action_cb(void *data)
3549 {
3550         Compose *compose = (Compose *)data;
3551         compose_wrap_all(compose);
3552 }
3553
3554 static void compose_wrap_all(Compose *compose)
3555 {
3556         compose_wrap_all_full(compose, FALSE);
3557 }
3558
3559 static void compose_wrap_all_full(Compose *compose, gboolean force)
3560 {
3561         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3562         GtkTextBuffer *buffer;
3563         GtkTextIter iter;
3564
3565         buffer = gtk_text_view_get_buffer(text);
3566
3567         gtk_text_buffer_get_start_iter(buffer, &iter);
3568         while (!gtk_text_iter_is_end(&iter))
3569                 compose_beautify_paragraph(compose, &iter, force);
3570
3571 }
3572
3573 static void compose_set_title(Compose *compose)
3574 {
3575         gchar *str;
3576         gchar *edited;
3577         gchar *subject;
3578         
3579         edited = compose->modified ? _(" [Edited]") : "";
3580         
3581         subject = gtk_editable_get_chars(
3582                         GTK_EDITABLE(compose->subject_entry), 0, -1);
3583
3584         if (subject && strlen(subject))
3585                 str = g_strdup_printf(_("%s - Compose message%s"),
3586                                       subject, edited); 
3587         else
3588                 str = g_strdup_printf(_("[no subject] - Compose message%s"), edited);
3589         gtk_window_set_title(GTK_WINDOW(compose->window), str);
3590         g_free(str);
3591         g_free(subject);
3592 }
3593
3594 /**
3595  * compose_current_mail_account:
3596  * 
3597  * Find a current mail account (the currently selected account, or the
3598  * default account, if a news account is currently selected).  If a
3599  * mail account cannot be found, display an error message.
3600  * 
3601  * Return value: Mail account, or NULL if not found.
3602  **/
3603 static PrefsAccount *
3604 compose_current_mail_account(void)
3605 {
3606         PrefsAccount *ac;
3607
3608         if (cur_account && cur_account->protocol != A_NNTP)
3609                 ac = cur_account;
3610         else {
3611                 ac = account_get_default();
3612                 if (!ac || ac->protocol == A_NNTP) {
3613                         alertpanel_error(_("Account for sending mail is not specified.\n"
3614                                            "Please select a mail account before sending."));
3615                         return NULL;
3616                 }
3617         }
3618         return ac;
3619 }
3620
3621 static void compose_select_account(Compose *compose, PrefsAccount *account,
3622                                    gboolean init)
3623 {
3624         GtkItemFactory *ifactory;
3625
3626         g_return_if_fail(account != NULL);
3627
3628         compose->account = account;
3629
3630         compose_set_title(compose);
3631
3632         ifactory = gtk_item_factory_from_widget(compose->menubar);
3633
3634         if (account->default_sign && compose->mode != COMPOSE_REDIRECT)
3635                 menu_set_active(ifactory, "/Options/Sign", TRUE);
3636         else
3637                 menu_set_active(ifactory, "/Options/Sign", FALSE);
3638         if (account->default_encrypt && compose->mode != COMPOSE_REDIRECT)
3639                 menu_set_active(ifactory, "/Options/Encrypt", TRUE);
3640         else
3641                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
3642                                        
3643         activate_privacy_system(compose, account, FALSE);
3644
3645         if (!init && compose->mode != COMPOSE_REDIRECT)
3646                 compose_insert_sig(compose, TRUE);
3647 }
3648
3649 gboolean compose_check_for_valid_recipient(Compose *compose) {
3650         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
3651         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
3652         gboolean recipient_found = FALSE;
3653         GSList *list;
3654         gchar **strptr;
3655
3656         /* free to and newsgroup list */
3657         slist_free_strings(compose->to_list);
3658         g_slist_free(compose->to_list);
3659         compose->to_list = NULL;
3660                         
3661         slist_free_strings(compose->newsgroup_list);
3662         g_slist_free(compose->newsgroup_list);
3663         compose->newsgroup_list = NULL;
3664
3665         /* search header entries for to and newsgroup entries */
3666         for (list = compose->header_list; list; list = list->next) {
3667                 gchar *header;
3668                 gchar *entry;
3669                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3670                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3671                 g_strstrip(entry);
3672                 if (entry[0] != '\0') {
3673                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
3674                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3675                                         compose->to_list = address_list_append(compose->to_list, entry);
3676                                         recipient_found = TRUE;
3677                                 }
3678                         }
3679                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
3680                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3681                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
3682                                         recipient_found = TRUE;
3683                                 }
3684                         }
3685                 }
3686                 g_free(header);
3687                 g_free(entry);
3688         }
3689         return recipient_found;
3690 }
3691
3692 static gboolean compose_check_for_set_recipients(Compose *compose)
3693 {
3694         if (compose->account->set_autocc && compose->account->auto_cc) {
3695                 gboolean found_other = FALSE;
3696                 GSList *list;
3697                 /* search header entries for to and newsgroup entries */
3698                 for (list = compose->header_list; list; list = list->next) {
3699                         gchar *entry;
3700                         gchar *header;
3701                         entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3702                         header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3703                         g_strstrip(entry);
3704                         if (strcmp(entry, compose->account->auto_cc)
3705                         ||  strcmp(header, (prefs_common.trans_hdr ? gettext("Cc:") : "Cc:"))) {
3706                                 found_other = TRUE;
3707                                 g_free(entry);
3708                                 break;
3709                         }
3710                         g_free(entry);
3711                         g_free(header);
3712                 }
3713                 if (!found_other) {
3714                         AlertValue aval;
3715                         aval = alertpanel(_("Send"),
3716                                           _("The only recipient is the default CC address. Send anyway?"),
3717                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3718                         if (aval != G_ALERTALTERNATE)
3719                                 return FALSE;
3720                 }
3721         }
3722         if (compose->account->set_autobcc && compose->account->auto_bcc) {
3723                 gboolean found_other = FALSE;
3724                 GSList *list;
3725                 /* search header entries for to and newsgroup entries */
3726                 for (list = compose->header_list; list; list = list->next) {
3727                         gchar *entry;
3728                         gchar *header;
3729                         entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3730                         header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3731                         g_strstrip(entry);
3732                         if (strcmp(entry, compose->account->auto_cc)
3733                         ||  strcmp(header, (prefs_common.trans_hdr ? gettext("Bcc:") : "Bcc:"))) {
3734                                 found_other = TRUE;
3735                                 g_free(entry);
3736                                 break;
3737                         }
3738                         g_free(entry);
3739                         g_free(header);
3740                 }
3741                 if (!found_other) {
3742                         AlertValue aval;
3743                         aval = alertpanel(_("Send"),
3744                                           _("The only recipient is the default BCC address. Send anyway?"),
3745                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3746                         if (aval != G_ALERTALTERNATE)
3747                                 return FALSE;
3748                 }
3749         }
3750         return TRUE;
3751 }
3752
3753 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
3754 {
3755         const gchar *str;
3756
3757         if (compose_check_for_valid_recipient(compose) == FALSE) {
3758                 alertpanel_error(_("Recipient is not specified."));
3759                 return FALSE;
3760         }
3761
3762         if (compose_check_for_set_recipients(compose) == FALSE) {
3763                 return FALSE;
3764         }
3765
3766         if (!compose->batch) {
3767                 str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3768                 if (*str == '\0' && check_subject == TRUE) {
3769                         AlertValue aval;
3770
3771                         aval = alertpanel(_("Send"),
3772                                           _("Subject is empty. Send it anyway?"),
3773                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3774                         if (aval != G_ALERTALTERNATE)
3775                                 return FALSE;
3776                 }
3777         }
3778
3779         return TRUE;
3780 }
3781
3782 gint compose_send(Compose *compose)
3783 {
3784         gint msgnum;
3785         FolderItem *folder;
3786         gint val = -1;
3787         gchar *msgpath = NULL;
3788         gboolean discard_window = FALSE;
3789
3790         if (prefs_common.send_dialog_mode != SEND_DIALOG_ALWAYS
3791                         || compose->batch == TRUE)
3792                 discard_window = TRUE;
3793
3794         compose_allow_user_actions (compose, FALSE);
3795         compose->sending = TRUE;
3796
3797         if (compose_check_entries(compose, TRUE) == FALSE) {
3798                 if (compose->batch) {
3799                         gtk_widget_show_all(compose->window);
3800                 }
3801                 goto bail;
3802         }
3803
3804         val = compose_queue(compose, &msgnum, &folder, &msgpath);
3805
3806         if (val) {
3807                 if (compose->batch) {
3808                         gtk_widget_show_all(compose->window);
3809                 }
3810                 if (val == -4) {
3811                         alertpanel_error(_("Could not queue message for sending:\n\n"
3812                                            "Charset conversion failed."));
3813                 } else if (val == -3) {
3814                         alertpanel_error(_("Could not queue message for sending:\n\n"
3815                                            "Signature failed."));
3816                 } else if (val == -2 && errno != 0) {
3817                         alertpanel_error(_("Could not queue message for sending:\n\n%s."), strerror(errno));
3818                 } else {
3819                         alertpanel_error(_("Could not queue message for sending."));
3820                 }
3821                 goto bail;
3822         }
3823
3824         if (discard_window) {
3825                 compose->sending = FALSE;
3826                 compose_close(compose);
3827                 /* No more compose access in the normal codepath 
3828                  * after this point! */
3829                 compose = NULL;
3830         }
3831
3832         if (msgnum == 0) {
3833                 if (!discard_window) {
3834                         goto bail;
3835                 }
3836                 alertpanel_error(_("The message was queued but could not be "
3837                                    "sent.\nUse \"Send queued messages\" from "
3838                                    "the main window to retry."));
3839                 return -1;
3840         }
3841         
3842         if (msgpath == NULL) {
3843                 msgpath = folder_item_fetch_msg(folder, msgnum);
3844                 val = procmsg_send_message_queue(msgpath);
3845                 g_free(msgpath);
3846         } else {
3847                 val = procmsg_send_message_queue(msgpath);
3848                 g_unlink(msgpath);
3849                 g_free(msgpath);
3850         }
3851         if (!discard_window) {
3852                 compose->sending = FALSE;
3853                 compose_allow_user_actions (compose, TRUE);
3854                 if (val != 0) {
3855                         folder_item_remove_msg(folder, msgnum);
3856                         folder_item_scan(folder);
3857                 }
3858         }
3859
3860         if (val == 0) {
3861                 folder_item_remove_msg(folder, msgnum);
3862                 folder_item_scan(folder);
3863                 if (!discard_window)
3864                         compose_close(compose);
3865         } else {
3866                 if (!discard_window) {
3867                         goto bail;              
3868                 }
3869                 alertpanel_error(_("The message was queued but could not be "
3870                                    "sent.\nUse \"Send queued messages\" from "
3871                                    "the main window to retry."));
3872                 return -1;
3873         }
3874
3875         return 0;
3876
3877 bail:
3878         compose_allow_user_actions (compose, TRUE);
3879         compose->sending = FALSE;
3880         compose->modified = TRUE; 
3881
3882         return -1;
3883 }
3884
3885 static gboolean compose_use_attach(Compose *compose) 
3886 {
3887         GtkTreeModel *model = gtk_tree_view_get_model
3888                                 (GTK_TREE_VIEW(compose->attach_clist));
3889         return gtk_tree_model_iter_n_children(model, NULL) > 0;
3890 }
3891
3892 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3893                                                            FILE *fp)
3894 {
3895         gchar buf[BUFFSIZE];
3896         gchar *str;
3897         gboolean first_to_address;
3898         gboolean first_cc_address;
3899         GSList *list;
3900         ComposeHeaderEntry *headerentry;
3901         const gchar *headerentryname;
3902         gchar *cc_hdr;
3903         gchar *to_hdr;
3904
3905         debug_print("Writing redirect header\n");
3906
3907         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3908         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3909
3910         first_to_address = TRUE;
3911         for (list = compose->header_list; list; list = list->next) {
3912                 headerentry = ((ComposeHeaderEntry *)list->data);
3913                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3914
3915                 if (g_utf8_collate(headerentryname, to_hdr) == 0) {
3916                         const gchar *entstr = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3917                         Xstrdup_a(str, entstr, return -1);
3918                         g_strstrip(str);
3919                         if (str[0] != '\0') {
3920                                 compose_convert_header
3921                                         (compose, buf, sizeof(buf), str,
3922                                         strlen("Resent-To") + 2, TRUE);
3923
3924                                 if (first_to_address) {
3925                                         fprintf(fp, "Resent-To: ");
3926                                         first_to_address = FALSE;
3927                                 } else {
3928                                         fprintf(fp, ",");
3929                                 }
3930                                 fprintf(fp, "%s", buf);
3931                         }
3932                 }
3933         }
3934         if (!first_to_address) {
3935                 fprintf(fp, "\n");
3936         }
3937
3938         first_cc_address = TRUE;
3939         for (list = compose->header_list; list; list = list->next) {
3940                 headerentry = ((ComposeHeaderEntry *)list->data);
3941                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3942
3943                 if (g_utf8_collate(headerentryname, cc_hdr) == 0) {
3944                         const gchar *strg = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3945                         Xstrdup_a(str, strg, return -1);
3946                         g_strstrip(str);
3947                         if (str[0] != '\0') {
3948                                 compose_convert_header
3949                                         (compose, buf, sizeof(buf), str,
3950                                         strlen("Resent-Cc") + 2, TRUE);
3951
3952                                 if (first_cc_address) {
3953                                         fprintf(fp, "Resent-Cc: ");
3954                                         first_cc_address = FALSE;
3955                                 } else {
3956                                         fprintf(fp, ",");
3957                                 }
3958                                 fprintf(fp, "%s", buf);
3959                         }
3960                 }
3961         }
3962         if (!first_cc_address) {
3963                 fprintf(fp, "\n");
3964         }
3965         
3966         return(0);
3967 }
3968
3969 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3970 {
3971         gchar buf[BUFFSIZE];
3972         gchar *str;
3973         const gchar *entstr;
3974         /* struct utsname utsbuf; */
3975
3976         g_return_val_if_fail(fp != NULL, -1);
3977         g_return_val_if_fail(compose->account != NULL, -1);
3978         g_return_val_if_fail(compose->account->address != NULL, -1);
3979
3980         /* Resent-Date */
3981         get_rfc822_date(buf, sizeof(buf));
3982         fprintf(fp, "Resent-Date: %s\n", buf);
3983
3984         /* Resent-From */
3985         if (compose->account->name && *compose->account->name) {
3986                 compose_convert_header
3987                         (compose, buf, sizeof(buf), compose->account->name,
3988                          strlen("From: "), TRUE);
3989                 fprintf(fp, "Resent-From: %s <%s>\n",
3990                         buf, compose->account->address);
3991         } else
3992                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3993
3994         /* Subject */
3995         entstr = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3996         if (*entstr != '\0') {
3997                 Xstrdup_a(str, entstr, return -1);
3998                 g_strstrip(str);
3999                 if (*str != '\0') {
4000                         compose_convert_header(compose, buf, sizeof(buf), str,
4001                                                strlen("Subject: "), FALSE);
4002                         fprintf(fp, "Subject: %s\n", buf);
4003                 }
4004         }
4005
4006         /* Resent-Message-ID */
4007         if (compose->account->gen_msgid) {
4008                 generate_msgid(buf, sizeof(buf));
4009                 fprintf(fp, "Resent-Message-ID: <%s>\n", buf);
4010                 compose->msgid = g_strdup(buf);
4011         }
4012
4013         compose_redirect_write_headers_from_headerlist(compose, fp);
4014
4015         /* separator between header and body */
4016         fputs("\n", fp);
4017
4018         return 0;
4019 }
4020
4021 static gint compose_redirect_write_to_file(Compose *compose, FILE *fdest)
4022 {
4023         FILE *fp;
4024         size_t len;
4025         gchar buf[BUFFSIZE];
4026
4027         if ((fp = g_fopen(compose->redirect_filename, "rb")) == NULL) {
4028                 FILE_OP_ERROR(compose->redirect_filename, "fopen");
4029                 return -1;
4030         }
4031
4032         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
4033                 /* should filter returnpath, delivered-to */
4034                 if (g_ascii_strncasecmp(buf, "Return-Path:",
4035                                         strlen("Return-Path:")) == 0 ||
4036                     g_ascii_strncasecmp(buf, "Delivered-To:",
4037                                         strlen("Delivered-To:")) == 0 ||
4038                     g_ascii_strncasecmp(buf, "Received:",
4039                                         strlen("Received:")) == 0 ||
4040                     g_ascii_strncasecmp(buf, "Subject:",
4041                                         strlen("Subject:")) == 0 ||
4042                     g_ascii_strncasecmp(buf, "X-UIDL:",
4043                                         strlen("X-UIDL:")) == 0)
4044                         continue;
4045
4046                 if (fputs(buf, fdest) == -1)
4047                         goto error;
4048
4049                 if (!prefs_common.redirect_keep_from) {
4050                         if (g_ascii_strncasecmp(buf, "From:",
4051                                           strlen("From:")) == 0) {
4052                                 fputs(" (by way of ", fdest);
4053                                 if (compose->account->name
4054                                     && *compose->account->name) {
4055                                         compose_convert_header
4056                                                 (compose, buf, sizeof(buf),
4057                                                  compose->account->name,
4058                                                  strlen("From: "),
4059                                                  FALSE);
4060                                         fprintf(fdest, "%s <%s>",
4061                                                 buf,
4062                                                 compose->account->address);
4063                                 } else
4064                                         fprintf(fdest, "%s",
4065                                                 compose->account->address);
4066                                 fputs(")", fdest);
4067                         }
4068                 }
4069
4070                 if (fputs("\n", fdest) == -1)
4071                         goto error;
4072         }
4073
4074         compose_redirect_write_headers(compose, fdest);
4075
4076         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
4077                 if (fwrite(buf, sizeof(gchar), len, fdest) != len)
4078                         goto error;
4079         }
4080
4081         fclose(fp);
4082
4083         return 0;
4084 error:
4085         fclose(fp);
4086
4087         return -1;
4088 }
4089
4090 static gint compose_write_to_file(Compose *compose, FILE *fp, gint action)
4091 {
4092         GtkTextBuffer *buffer;
4093         GtkTextIter start, end;
4094         gchar *chars;
4095         gchar *buf;
4096         const gchar *out_codeset;
4097         EncodingType encoding;
4098         MimeInfo *mimemsg, *mimetext;
4099         gint line;
4100
4101         /* create message MimeInfo */
4102         mimemsg = procmime_mimeinfo_new();
4103         mimemsg->type = MIMETYPE_MESSAGE;
4104         mimemsg->subtype = g_strdup("rfc822");
4105         mimemsg->content = MIMECONTENT_MEM;
4106         mimemsg->tmp = TRUE; /* must free content later */
4107         mimemsg->data.mem = compose_get_header(compose);
4108
4109         /* Create text part MimeInfo */
4110         /* get all composed text */
4111         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4112         gtk_text_buffer_get_start_iter(buffer, &start);
4113         gtk_text_buffer_get_end_iter(buffer, &end);
4114         chars = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4115         if (is_ascii_str(chars)) {
4116                 buf = chars;
4117                 chars = NULL;
4118                 out_codeset = CS_US_ASCII;
4119                 encoding = ENC_7BIT;
4120         } else {
4121                 const gchar *src_codeset = CS_INTERNAL;
4122
4123                 out_codeset = conv_get_charset_str(compose->out_encoding);
4124
4125                 if (!out_codeset) {
4126                         gchar *test_conv_global_out = NULL;
4127                         gchar *test_conv_reply = NULL;
4128
4129                         /* automatic mode. be automatic. */
4130                         codeconv_set_strict(TRUE);
4131                         
4132                         out_codeset = conv_get_outgoing_charset_str();
4133                         if (out_codeset) {
4134                                 debug_print("trying to convert to %s\n", out_codeset);
4135                                 test_conv_global_out = conv_codeset_strdup(chars, src_codeset, out_codeset);
4136                         }
4137                         
4138                         if (!test_conv_global_out && compose->orig_charset
4139                         &&  strcmp(compose->orig_charset, CS_US_ASCII)) {
4140                                 out_codeset = compose->orig_charset;
4141                                 debug_print("failure; trying to convert to %s\n", out_codeset);
4142                                 test_conv_reply = conv_codeset_strdup(chars, src_codeset, out_codeset);
4143                         }
4144                         
4145                         if (!test_conv_global_out && !test_conv_reply) {
4146                                 /* we're lost */
4147                                 out_codeset = CS_INTERNAL;
4148                                 debug_print("failure; finally using %s\n", out_codeset);
4149                         }
4150                         g_free(test_conv_global_out);
4151                         g_free(test_conv_reply);
4152                         codeconv_set_strict(FALSE);
4153                 }
4154
4155                 if (!g_ascii_strcasecmp(out_codeset, CS_US_ASCII))
4156                         out_codeset = CS_ISO_8859_1;
4157
4158                 if (prefs_common.encoding_method == CTE_BASE64)
4159                         encoding = ENC_BASE64;
4160                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
4161                         encoding = ENC_QUOTED_PRINTABLE;
4162                 else if (prefs_common.encoding_method == CTE_8BIT)
4163                         encoding = ENC_8BIT;
4164                 else
4165                         encoding = procmime_get_encoding_for_charset(out_codeset);
4166
4167                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
4168                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
4169
4170                 if (action == COMPOSE_WRITE_FOR_SEND) {
4171                         codeconv_set_strict(TRUE);
4172                         buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
4173                         codeconv_set_strict(FALSE);
4174
4175                         if (!buf) {
4176                                 AlertValue aval;
4177                                 gchar *msg;
4178
4179                                 msg = g_strdup_printf(_("Can't convert the character encoding of the message \n"
4180                                                         "to the specified %s charset.\n"
4181                                                         "Send it as %s?"), out_codeset, src_codeset);
4182                                 aval = alertpanel_full(_("Error"), msg, GTK_STOCK_CANCEL, _("+_Send"), NULL, FALSE,
4183                                                       NULL, ALERT_ERROR, G_ALERTDEFAULT);
4184                                 g_free(msg);
4185
4186                                 if (aval != G_ALERTALTERNATE) {
4187                                         g_free(chars);
4188                                         return -3;
4189                                 } else {
4190                                         buf = chars;
4191                                         out_codeset = src_codeset;
4192                                         chars = NULL;
4193                                 }
4194                         }
4195                 } else {
4196                         buf = chars;
4197                         out_codeset = src_codeset;
4198                         chars = NULL;
4199                 }
4200         }
4201         g_free(chars);
4202
4203         if (encoding == ENC_8BIT || encoding == ENC_7BIT) {
4204                 if (!strncmp(buf, "From ", sizeof("From ")-1) ||
4205                     strstr(buf, "\nFrom ") != NULL) {
4206                         encoding = ENC_QUOTED_PRINTABLE;
4207                 }
4208         }
4209
4210         mimetext = procmime_mimeinfo_new();
4211         mimetext->content = MIMECONTENT_MEM;
4212         mimetext->tmp = TRUE; /* must free content later */
4213         mimetext->data.mem = buf;
4214         mimetext->type = MIMETYPE_TEXT;
4215         mimetext->subtype = g_strdup("plain");
4216         g_hash_table_insert(mimetext->typeparameters, g_strdup("charset"),
4217                             g_strdup(out_codeset));
4218         /* protect trailing spaces when signing message */
4219         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4220             privacy_system_can_sign(compose->privacy_system)) {
4221                 encoding = ENC_QUOTED_PRINTABLE;
4222         }
4223         
4224         /* check for line length limit */
4225         if (action == COMPOSE_WRITE_FOR_SEND &&
4226             encoding != ENC_QUOTED_PRINTABLE && encoding != ENC_BASE64 &&
4227             check_line_length(buf, 1000, &line) < 0) {
4228                 AlertValue aval;
4229                 gchar *msg;
4230
4231                 msg = g_strdup_printf
4232                         (_("Line %d exceeds the line length limit (998 bytes).\n"
4233                            "The contents of the message might be broken on the way to the delivery.\n"
4234                            "\n"
4235                            "Send it anyway?"), line + 1);
4236                 aval = alertpanel(_("Warning"), msg, GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL);
4237                 g_free(msg);
4238                 if (aval != G_ALERTALTERNATE) {
4239                         return -1;
4240                 }
4241         }
4242         
4243         if (encoding != ENC_UNKNOWN)
4244                 procmime_encode_content(mimetext, encoding);
4245
4246         /* append attachment parts */
4247         if (compose_use_attach(compose)) {
4248                 MimeInfo *mimempart;
4249                 gchar *boundary = NULL;
4250                 mimempart = procmime_mimeinfo_new();
4251                 mimempart->content = MIMECONTENT_EMPTY;
4252                 mimempart->type = MIMETYPE_MULTIPART;
4253                 mimempart->subtype = g_strdup("mixed");
4254
4255                 do {
4256                         if (boundary)
4257                                 g_free(boundary);
4258                         boundary = generate_mime_boundary(NULL);
4259                 } while (strstr(buf, boundary) != NULL);
4260
4261                 g_hash_table_insert(mimempart->typeparameters, g_strdup("boundary"),
4262                                     boundary);
4263
4264                 mimetext->disposition = DISPOSITIONTYPE_INLINE;
4265
4266                 g_node_append(mimempart->node, mimetext->node);
4267                 g_node_append(mimemsg->node, mimempart->node);
4268
4269                 compose_add_attachments(compose, mimempart);
4270         } else
4271                 g_node_append(mimemsg->node, mimetext->node);
4272
4273         /* sign message if sending */
4274         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4275             privacy_system_can_sign(compose->privacy_system))
4276                 if (!privacy_sign(compose->privacy_system, mimemsg, compose->account))
4277                         return -2;
4278
4279         procmime_write_mimeinfo(mimemsg, fp);
4280         
4281         procmime_mimeinfo_free_all(mimemsg);
4282
4283         return 0;
4284 }
4285
4286 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
4287 {
4288         GtkTextBuffer *buffer;
4289         GtkTextIter start, end;
4290         FILE *fp;
4291         size_t len;
4292         gchar *chars, *tmp;
4293
4294         if ((fp = g_fopen(file, "wb")) == NULL) {
4295                 FILE_OP_ERROR(file, "fopen");
4296                 return -1;
4297         }
4298
4299         /* chmod for security */
4300         if (change_file_mode_rw(fp, file) < 0) {
4301                 FILE_OP_ERROR(file, "chmod");
4302                 g_warning("can't change file mode\n");
4303         }
4304
4305         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4306         gtk_text_buffer_get_start_iter(buffer, &start);
4307         gtk_text_buffer_get_end_iter(buffer, &end);
4308         tmp = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4309
4310         chars = conv_codeset_strdup
4311                 (tmp, CS_INTERNAL, conv_get_locale_charset_str());
4312
4313         g_free(tmp);
4314         if (!chars) return -1;
4315
4316         /* write body */
4317         len = strlen(chars);
4318         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
4319                 FILE_OP_ERROR(file, "fwrite");
4320                 g_free(chars);
4321                 fclose(fp);
4322                 g_unlink(file);
4323                 return -1;
4324         }
4325
4326         g_free(chars);
4327
4328         if (fclose(fp) == EOF) {
4329                 FILE_OP_ERROR(file, "fclose");
4330                 g_unlink(file);
4331                 return -1;
4332         }
4333         return 0;
4334 }
4335
4336 static gint compose_remove_reedit_target(Compose *compose, gboolean force)
4337 {
4338         FolderItem *item;
4339         MsgInfo *msginfo = compose->targetinfo;
4340
4341         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
4342         if (!msginfo) return -1;
4343
4344         if (!force && MSG_IS_LOCKED(msginfo->flags))
4345                 return 0;
4346
4347         item = msginfo->folder;
4348         g_return_val_if_fail(item != NULL, -1);
4349
4350         if (procmsg_msg_exist(msginfo) &&
4351             (folder_has_parent_of_type(item, F_QUEUE) ||
4352              folder_has_parent_of_type(item, F_DRAFT) 
4353              || msginfo == compose->autosaved_draft)) {
4354                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
4355                         g_warning("can't remove the old message\n");
4356                         return -1;
4357                 }
4358         }
4359
4360         return 0;
4361 }
4362
4363 void compose_remove_draft(Compose *compose)
4364 {
4365         FolderItem *drafts;
4366         MsgInfo *msginfo = compose->targetinfo;
4367         drafts = account_get_special_folder(compose->account, F_DRAFT);
4368
4369         if (procmsg_msg_exist(msginfo)) {
4370                 folder_item_remove_msg(drafts, msginfo->msgnum);
4371         }
4372
4373 }
4374
4375 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item, gchar **msgpath)
4376 {
4377         return compose_queue_sub (compose, msgnum, item, msgpath, FALSE);
4378 }
4379 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gchar **msgpath, gboolean check_subject)
4380 {
4381         FolderItem *queue;
4382         gchar *tmp;
4383         FILE *fp;
4384         GSList *cur;
4385         gint num;
4386         static gboolean lock = FALSE;
4387         PrefsAccount *mailac = NULL, *newsac = NULL;
4388         
4389         debug_print("queueing message...\n");
4390         g_return_val_if_fail(compose->account != NULL, -1);
4391
4392         lock = TRUE;
4393         
4394         if (compose_check_entries(compose, check_subject) == FALSE) {
4395                 lock = FALSE;
4396                 return -1;
4397         }
4398
4399         if (!compose->to_list && !compose->newsgroup_list) {
4400                 g_warning("can't get recipient list.");
4401                 lock = FALSE;
4402                 return -1;
4403         }
4404
4405         if (compose->to_list) {
4406                 if (compose->account->protocol != A_NNTP)
4407                         mailac = compose->account;
4408                 else if (cur_account && cur_account->protocol != A_NNTP)
4409                         mailac = cur_account;
4410                 else if (!(mailac = compose_current_mail_account())) {
4411                         lock = FALSE;
4412                         alertpanel_error(_("No account for sending mails available!"));
4413                         return -1;
4414                 }
4415         }
4416
4417         if (compose->newsgroup_list) {
4418                 if (compose->account->protocol == A_NNTP)
4419                         newsac = compose->account;
4420                 else if (!newsac->protocol != A_NNTP) {
4421                         lock = FALSE;
4422                         alertpanel_error(_("No account for posting news available!"));
4423                         return -1;
4424                 }                       
4425         }
4426
4427         /* write queue header */
4428         tmp = g_strdup_printf("%s%cqueue.%p", get_tmp_dir(),
4429                               G_DIR_SEPARATOR, compose);
4430         if ((fp = g_fopen(tmp, "wb")) == NULL) {
4431                 FILE_OP_ERROR(tmp, "fopen");
4432                 g_free(tmp);
4433                 return -2;
4434         }
4435
4436         if (change_file_mode_rw(fp, tmp) < 0) {
4437                 FILE_OP_ERROR(tmp, "chmod");
4438                 g_warning("can't change file mode\n");
4439         }
4440
4441         /* queueing variables */
4442         fprintf(fp, "AF:\n");
4443         fprintf(fp, "NF:0\n");
4444         fprintf(fp, "PS:10\n");
4445         fprintf(fp, "SRH:1\n");
4446         fprintf(fp, "SFN:\n");
4447         fprintf(fp, "DSR:\n");
4448         if (compose->msgid)
4449                 fprintf(fp, "MID:<%s>\n", compose->msgid);
4450         else
4451                 fprintf(fp, "MID:\n");
4452         fprintf(fp, "CFG:\n");
4453         fprintf(fp, "PT:0\n");
4454         fprintf(fp, "S:%s\n", compose->account->address);
4455         fprintf(fp, "RQ:\n");
4456         if (mailac)
4457                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
4458         else
4459                 fprintf(fp, "SSV:\n");
4460         if (newsac)
4461                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
4462         else
4463                 fprintf(fp, "NSV:\n");
4464         fprintf(fp, "SSH:\n");
4465         /* write recepient list */
4466         if (compose->to_list) {
4467                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
4468                 for (cur = compose->to_list->next; cur != NULL;
4469                      cur = cur->next)
4470                         fprintf(fp, ",<%s>", (gchar *)cur->data);
4471                 fprintf(fp, "\n");
4472         }
4473         /* write newsgroup list */
4474         if (compose->newsgroup_list) {
4475                 fprintf(fp, "NG:");
4476                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
4477                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
4478                         fprintf(fp, ",%s", (gchar *)cur->data);
4479                 fprintf(fp, "\n");
4480         }
4481         /* Sylpheed account IDs */
4482         if (mailac)
4483                 fprintf(fp, "MAID:%d\n", mailac->account_id);
4484         if (newsac)
4485                 fprintf(fp, "NAID:%d\n", newsac->account_id);
4486
4487         if (compose->privacy_system != NULL) {
4488                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
4489                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
4490                 if (compose->use_encryption) {
4491                         gchar *encdata;
4492
4493                         encdata = privacy_get_encrypt_data(compose->privacy_system, compose->to_list);
4494                         if (encdata != NULL) {
4495                                 if (strcmp(encdata, "_DONT_ENCRYPT_")) {
4496                                         fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4497                                         fprintf(fp, "X-Sylpheed-Encrypt-Data:%s\n", 
4498                                                 encdata);
4499                                 } /* else we finally dont want to encrypt */
4500                         } else {
4501                                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4502                                 /* and if encdata was null, it means there's been a problem in 
4503                                  * key selection */
4504                         }
4505                         g_free(encdata);
4506                 }
4507         }
4508
4509         /* Save copy folder */
4510         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
4511                 gchar *savefolderid;
4512                 
4513                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
4514                 fprintf(fp, "SCF:%s\n", savefolderid);
4515                 g_free(savefolderid);
4516         }
4517         /* Save copy folder */
4518         if (compose->return_receipt) {
4519                 fprintf(fp, "RRCPT:1\n");
4520         }
4521         /* Message-ID of message replying to */
4522         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
4523                 gchar *folderid;
4524                 
4525                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
4526                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
4527                 g_free(folderid);
4528         }
4529         /* Message-ID of message forwarding to */
4530         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
4531                 gchar *folderid;
4532                 
4533                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
4534                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
4535                 g_free(folderid);
4536         }
4537         fprintf(fp, "\n");
4538
4539         if (compose->redirect_filename != NULL) {
4540                 if (compose_redirect_write_to_file(compose, fp) < 0) {
4541                         lock = FALSE;
4542                         fclose(fp);
4543                         g_unlink(tmp);
4544                         g_free(tmp);
4545                         return -2;
4546                 }
4547         } else {
4548                 gint result = 0;
4549                 if ((result = compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_SEND)) < 0) {
4550                         lock = FALSE;
4551                         fclose(fp);
4552                         g_unlink(tmp);
4553                         g_free(tmp);
4554                         return result - 1; /* -2 for a generic error, -3 for signing error, -4 for encoding */
4555                 }
4556         }
4557
4558         if (fclose(fp) == EOF) {
4559                 FILE_OP_ERROR(tmp, "fclose");
4560                 g_unlink(tmp);
4561                 g_free(tmp);
4562                 return -2;
4563         }
4564
4565         queue = account_get_special_folder(compose->account, F_QUEUE);
4566         if (!queue) {
4567                 g_warning("can't find queue folder\n");
4568                 g_unlink(tmp);
4569                 g_free(tmp);
4570                 return -1;
4571         }
4572         folder_item_scan(queue);
4573         if ((num = folder_item_add_msg(queue, tmp, NULL, FALSE)) < 0) {
4574                 g_warning("can't queue the message\n");
4575                 g_unlink(tmp);
4576                 g_free(tmp);
4577                 return -1;
4578         }
4579         
4580         if (msgpath == NULL) {
4581                 g_unlink(tmp);
4582                 g_free(tmp);
4583         } else
4584                 *msgpath = tmp;
4585
4586         if (compose->mode == COMPOSE_REEDIT) {
4587                 compose_remove_reedit_target(compose, FALSE);
4588         }
4589
4590         if ((msgnum != NULL) && (item != NULL)) {
4591                 *msgnum = num;
4592                 *item = queue;
4593         }
4594
4595         return 0;
4596 }
4597
4598 static void compose_add_attachments(Compose *compose, MimeInfo *parent)
4599 {
4600         AttachInfo *ainfo;
4601         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
4602         MimeInfo *mimepart;
4603         struct stat statbuf;
4604         gchar *type, *subtype;
4605         GtkTreeModel *model;
4606         GtkTreeIter iter;
4607
4608         model = gtk_tree_view_get_model(tree_view);
4609         
4610         if (!gtk_tree_model_get_iter_first(model, &iter))
4611                 return;
4612         do {
4613                 gtk_tree_model_get(model, &iter,
4614                                    COL_DATA, &ainfo,
4615                                    -1);
4616                                                            
4617                 mimepart = procmime_mimeinfo_new();
4618                 mimepart->content = MIMECONTENT_FILE;
4619                 mimepart->data.filename = g_strdup(ainfo->file);
4620                 mimepart->tmp = FALSE; /* or we destroy our attachment */
4621                 mimepart->offset = 0;
4622
4623                 stat(ainfo->file, &statbuf);
4624                 mimepart->length = statbuf.st_size;
4625
4626                 type = g_strdup(ainfo->content_type);
4627
4628                 if (!strchr(type, '/')) {
4629                         g_free(type);
4630                         type = g_strdup("application/octet-stream");
4631                 }
4632
4633                 subtype = strchr(type, '/') + 1;
4634                 *(subtype - 1) = '\0';
4635                 mimepart->type = procmime_get_media_type(type);
4636                 mimepart->subtype = g_strdup(subtype);
4637                 g_free(type);
4638
4639                 if (mimepart->type == MIMETYPE_MESSAGE && 
4640                     !g_ascii_strcasecmp(mimepart->subtype, "rfc822")) {
4641                         mimepart->disposition = DISPOSITIONTYPE_INLINE;
4642                 } else {
4643                         g_hash_table_insert(mimepart->typeparameters,
4644                                             g_strdup("name"), g_strdup(ainfo->name));
4645                         g_hash_table_insert(mimepart->dispositionparameters,
4646                                             g_strdup("filename"), g_strdup(ainfo->name));
4647                         mimepart->disposition = DISPOSITIONTYPE_ATTACHMENT;
4648                 }
4649
4650                 if (compose->use_signing) {
4651                         if (ainfo->encoding == ENC_7BIT)
4652                                 ainfo->encoding = ENC_QUOTED_PRINTABLE;
4653                         else if (ainfo->encoding == ENC_8BIT)
4654                                 ainfo->encoding = ENC_BASE64;
4655                 }
4656                 
4657                 procmime_encode_content(mimepart, ainfo->encoding);
4658
4659                 g_node_append(parent->node, mimepart->node);
4660         } while (gtk_tree_model_iter_next(model, &iter));
4661 }
4662
4663 #define QUOTE_IF_REQUIRED(out, str)                                     \
4664 {                                                                       \
4665         if (*str != '"' && strpbrk(str, ",.[]<>")) {                    \
4666                 gchar *__tmp;                                           \
4667                 gint len;                                               \
4668                                                                         \
4669                 len = strlen(str) + 3;                                  \
4670                 if ((__tmp = alloca(len)) == NULL) {                    \
4671                         g_warning("can't allocate memory\n");           \
4672                         g_string_free(header, TRUE);                    \
4673                         return NULL;                                    \
4674                 }                                                       \
4675                 g_snprintf(__tmp, len, "\"%s\"", str);                  \
4676                 out = __tmp;                                            \
4677         } else {                                                        \
4678                 gchar *__tmp;                                           \
4679                                                                         \
4680                 if ((__tmp = alloca(strlen(str) + 1)) == NULL) {        \
4681                         g_warning("can't allocate memory\n");           \
4682                         g_string_free(header, TRUE);                    \
4683                         return NULL;                                    \
4684                 } else                                                  \
4685                         strcpy(__tmp, str);                             \
4686                                                                         \
4687                 out = __tmp;                                            \
4688         }                                                               \
4689 }
4690
4691 #define IS_IN_CUSTOM_HEADER(header) \
4692         (compose->account->add_customhdr && \
4693          custom_header_find(compose->account->customhdr_list, header) != NULL)
4694
4695 static void compose_add_headerfield_from_headerlist(Compose *compose, 
4696                                                     GString *header, 
4697                                                     const gchar *fieldname,
4698                                                     const gchar *seperator)
4699 {
4700         gchar *str, *fieldname_w_colon, *trans_fieldname;
4701         gboolean add_field = FALSE;
4702         GSList *list;
4703         ComposeHeaderEntry *headerentry;
4704         const gchar * headerentryname;
4705         GString *fieldstr;
4706
4707         if (IS_IN_CUSTOM_HEADER(fieldname))
4708                 return;
4709
4710         debug_print("Adding %s-fields\n", fieldname);
4711
4712         fieldstr = g_string_sized_new(64);
4713
4714         fieldname_w_colon = g_strconcat(fieldname, ":", NULL);
4715         trans_fieldname = (prefs_common.trans_hdr ? gettext(fieldname_w_colon) : fieldname_w_colon);
4716
4717         for (list = compose->header_list; list; list = list->next) {
4718                 headerentry = ((ComposeHeaderEntry *)list->data);
4719                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
4720
4721                 if (!g_utf8_collate(trans_fieldname, headerentryname)) {
4722                         str = gtk_editable_get_chars(GTK_EDITABLE(headerentry->entry), 0, -1);
4723                         g_strstrip(str);
4724                         if (str[0] != '\0') {
4725                                 if (add_field)
4726                                         g_string_append(fieldstr, seperator);
4727                                 g_string_append(fieldstr, str);
4728                                 add_field = TRUE;
4729                         }
4730                         g_free(str);
4731                 }
4732         }
4733         if (add_field) {
4734                 gchar *buf;
4735
4736                 buf = g_new0(gchar, fieldstr->len * 4 + 256);
4737                 compose_convert_header
4738                         (compose, buf, fieldstr->len * 4  + 256, fieldstr->str,
4739                         strlen(fieldname) + 2, TRUE);
4740                 g_string_append_printf(header, "%s: %s\n", fieldname, buf);
4741                 g_free(buf);
4742         }
4743
4744         g_free(fieldname_w_colon);
4745         g_string_free(fieldstr, TRUE);
4746
4747         return;
4748 }
4749
4750 static gchar *compose_get_header(Compose *compose)
4751 {
4752         gchar buf[BUFFSIZE];
4753         const gchar *entry_str;
4754         gchar *str;
4755         gchar *name;
4756         GSList *list;
4757         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4758         GString *header;
4759
4760         g_return_val_if_fail(compose->account != NULL, NULL);
4761         g_return_val_if_fail(compose->account->address != NULL, NULL);
4762
4763         header = g_string_sized_new(64);
4764
4765         /* Date */
4766         if (compose->account->add_date) {
4767                 get_rfc822_date(buf, sizeof(buf));
4768                 g_string_append_printf(header, "Date: %s\n", buf);
4769         }
4770
4771         /* From */
4772         if (compose->account->name && *compose->account->name) {
4773                 compose_convert_header
4774                         (compose, buf, sizeof(buf), compose->account->name,
4775                          strlen("From: "), TRUE);
4776                 QUOTE_IF_REQUIRED(name, buf);
4777                 g_string_append_printf(header, "From: %s <%s>\n",
4778                         name, compose->account->address);
4779         } else
4780                 g_string_append_printf(header, "From: %s\n", compose->account->address);
4781         
4782         /* To */
4783         compose_add_headerfield_from_headerlist(compose, header, "To", ", ");
4784
4785         /* Newsgroups */
4786         compose_add_headerfield_from_headerlist(compose, header, "Newsgroups", ",");
4787
4788         /* Cc */
4789         compose_add_headerfield_from_headerlist(compose, header, "Cc", ", ");
4790
4791         /* Bcc */
4792         compose_add_headerfield_from_headerlist(compose, header, "Bcc", ", ");
4793
4794         /* Subject */
4795         str = gtk_editable_get_chars(GTK_EDITABLE(compose->subject_entry), 0, -1);
4796
4797         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4798                 g_strstrip(str);
4799                 if (*str != '\0') {
4800                         compose_convert_header(compose, buf, sizeof(buf), str,
4801                                                strlen("Subject: "), FALSE);
4802                         g_string_append_printf(header, "Subject: %s\n", buf);
4803                 }
4804         }
4805         g_free(str);
4806
4807         /* Message-ID */
4808         if (compose->account->gen_msgid) {
4809                 generate_msgid(buf, sizeof(buf));
4810                 g_string_append_printf(header, "Message-ID: <%s>\n", buf);
4811                 compose->msgid = g_strdup(buf);
4812         }
4813
4814         if (compose->remove_references == FALSE) {
4815                 /* In-Reply-To */
4816                 if (compose->inreplyto && compose->to_list)
4817                         g_string_append_printf(header, "In-Reply-To: <%s>\n", compose->inreplyto);
4818         
4819                 /* References */
4820                 if (compose->references)
4821                         g_string_append_printf(header, "References: %s\n", compose->references);
4822         }
4823
4824         /* Followup-To */
4825         compose_add_headerfield_from_headerlist(compose, header, "Followup-To", ",");
4826
4827         /* Reply-To */
4828         compose_add_headerfield_from_headerlist(compose, header, "Reply-To", ", ");
4829
4830         /* Organization */
4831         if (compose->account->organization &&
4832             strlen(compose->account->organization) &&
4833             !IS_IN_CUSTOM_HEADER("Organization")) {
4834                 compose_convert_header(compose, buf, sizeof(buf),
4835                                        compose->account->organization,
4836                                        strlen("Organization: "), FALSE);
4837                 g_string_append_printf(header, "Organization: %s\n", buf);
4838         }
4839
4840         /* Program version and system info */
4841         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4842             !compose->newsgroup_list) {
4843                 g_string_append_printf(header, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4844                         prog_version,
4845                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4846                         TARGET_ALIAS);
4847         }
4848         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4849                 g_string_append_printf(header, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4850                         prog_version,
4851                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4852                         TARGET_ALIAS);
4853         }
4854
4855         /* custom headers */
4856         if (compose->account->add_customhdr) {
4857                 GSList *cur;
4858
4859                 for (cur = compose->account->customhdr_list; cur != NULL;
4860                      cur = cur->next) {
4861                         CustomHeader *chdr = (CustomHeader *)cur->data;
4862
4863                         if (custom_header_is_allowed(chdr->name)) {
4864                                 compose_convert_header
4865                                         (compose, buf, sizeof(buf),
4866                                          chdr->value ? chdr->value : "",
4867                                          strlen(chdr->name) + 2, FALSE);
4868                                 g_string_append_printf(header, "%s: %s\n", chdr->name, buf);
4869                         }
4870                 }
4871         }
4872
4873         /* PRIORITY */
4874         switch (compose->priority) {
4875                 case PRIORITY_HIGHEST: g_string_append_printf(header, "Importance: high\n"
4876                                                    "X-Priority: 1 (Highest)\n");
4877                         break;
4878                 case PRIORITY_HIGH: g_string_append_printf(header, "Importance: high\n"
4879                                                 "X-Priority: 2 (High)\n");
4880                         break;
4881                 case PRIORITY_NORMAL: break;
4882                 case PRIORITY_LOW: g_string_append_printf(header, "Importance: low\n"
4883                                                "X-Priority: 4 (Low)\n");
4884                         break;
4885                 case PRIORITY_LOWEST: g_string_append_printf(header, "Importance: low\n"
4886                                                   "X-Priority: 5 (Lowest)\n");
4887                         break;
4888                 default: debug_print("compose: priority unknown : %d\n",
4889                                      compose->priority);
4890         }
4891
4892         /* Request Return Receipt */
4893         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4894                 if (compose->return_receipt) {
4895                         if (compose->account->name
4896                             && *compose->account->name) {
4897                                 compose_convert_header(compose, buf, sizeof(buf), 
4898                                                        compose->account->name, 
4899                                                        strlen("Disposition-Notification-To: "),
4900                                                        TRUE);
4901                                 g_string_append_printf(header, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4902                         } else
4903                                 g_string_append_printf(header, "Disposition-Notification-To: %s\n", compose->account->address);
4904                 }
4905         }
4906
4907         /* get special headers */
4908         for (list = compose->header_list; list; list = list->next) {
4909                 ComposeHeaderEntry *headerentry;
4910                 gchar *tmp;
4911                 gchar *headername;
4912                 gchar *headername_wcolon;
4913                 gchar *headername_trans;
4914                 gchar *headervalue;
4915                 gchar **string;
4916                 gboolean standard_header = FALSE;
4917
4918                 headerentry = ((ComposeHeaderEntry *)list->data);
4919                 
4920                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4921                 if (strchr(tmp, ' ') != NULL || strchr(tmp, '\r') != NULL || strchr(tmp, '\n') != NULL) {
4922                         g_free(tmp);
4923                         continue;
4924                 }
4925
4926                 if (!strstr(tmp, ":")) {
4927                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4928                         headername = g_strdup(tmp);
4929                 } else {
4930                         headername_wcolon = g_strdup(tmp);
4931                         headername = g_strdup(strtok(tmp, ":"));
4932                 }
4933                 g_free(tmp);
4934                 
4935                 entry_str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4936                 Xstrdup_a(headervalue, entry_str, return NULL);
4937                 subst_char(headervalue, '\r', ' ');
4938                 subst_char(headervalue, '\n', ' ');
4939                 string = std_headers;
4940                 while (*string != NULL) {
4941                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4942                         if (!strcmp(headername_trans,headername_wcolon))
4943                                 standard_header = TRUE;
4944                         string++;
4945                 }
4946                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4947                         g_string_append_printf(header, "%s %s\n", headername_wcolon, headervalue);
4948                                 
4949                 g_free(headername);
4950                 g_free(headername_wcolon);              
4951         }
4952
4953         str = header->str;
4954         g_string_free(header, FALSE);
4955
4956         return str;
4957 }
4958
4959 #undef IS_IN_CUSTOM_HEADER
4960
4961 static void compose_convert_header(Compose *compose, gchar *dest, gint len, gchar *src,
4962                                    gint header_len, gboolean addr_field)
4963 {
4964         gchar *tmpstr = NULL;
4965         const gchar *out_codeset = NULL;
4966
4967         g_return_if_fail(src != NULL);
4968         g_return_if_fail(dest != NULL);
4969
4970         if (len < 1) return;
4971
4972         tmpstr = g_strdup(src);
4973
4974         subst_char(tmpstr, '\n', ' ');
4975         subst_char(tmpstr, '\r', ' ');
4976         g_strchomp(tmpstr);
4977
4978         if (!g_utf8_validate(tmpstr, -1, NULL)) {
4979                 gchar *mybuf = g_malloc(strlen(tmpstr)*2 +1);
4980                 conv_localetodisp(mybuf, strlen(tmpstr)*2 +1, tmpstr);
4981                 g_free(tmpstr);
4982                 tmpstr = mybuf;
4983         }
4984
4985         codeconv_set_strict(TRUE);
4986         conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
4987                 conv_get_charset_str(compose->out_encoding));
4988         codeconv_set_strict(FALSE);
4989         
4990         if (!dest || *dest == '\0') {
4991                 gchar *test_conv_global_out = NULL;
4992                 gchar *test_conv_reply = NULL;
4993
4994                 /* automatic mode. be automatic. */
4995                 codeconv_set_strict(TRUE);
4996
4997                 out_codeset = conv_get_outgoing_charset_str();
4998                 if (out_codeset) {
4999                         debug_print("trying to convert to %s\n", out_codeset);
5000                         test_conv_global_out = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
5001                 }
5002
5003                 if (!test_conv_global_out && compose->orig_charset) {
5004                         out_codeset = compose->orig_charset;
5005                         debug_print("failure; trying to convert to %s\n", out_codeset);
5006                         test_conv_reply = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
5007                 }
5008
5009                 if (!test_conv_global_out && !test_conv_reply) {
5010                         /* we're lost */
5011                         out_codeset = CS_INTERNAL;
5012                         debug_print("finally using %s\n", out_codeset);
5013                 }
5014                 g_free(test_conv_global_out);
5015                 g_free(test_conv_reply);
5016                 conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
5017                                         out_codeset);
5018                 codeconv_set_strict(FALSE);
5019         }
5020         g_free(tmpstr);
5021 }
5022
5023 static void compose_create_header_entry(Compose *compose) 
5024 {
5025         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
5026
5027         GtkWidget *combo;
5028         GtkWidget *entry;
5029         GList *combo_list = NULL;
5030         gchar **string;
5031         const gchar *header = NULL;
5032         ComposeHeaderEntry *headerentry;
5033         gboolean standard_header = FALSE;
5034
5035         headerentry = g_new0(ComposeHeaderEntry, 1);
5036
5037         /* Combo box */
5038         combo = gtk_combo_new();
5039         string = headers; 
5040         while(*string != NULL) {
5041                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
5042                 string++;
5043         }
5044         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
5045         g_list_free(combo_list);
5046         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
5047         g_signal_connect(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
5048                          G_CALLBACK(compose_grab_focus_cb), compose);
5049         gtk_widget_show(combo);
5050         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
5051         if (compose->header_last) {     
5052                 const gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
5053                 string = headers;
5054                 while (*string != NULL) {
5055                         if (!strcmp(*string, last_header_entry))
5056                                 standard_header = TRUE;
5057                         string++;
5058                 }
5059                 if (standard_header)
5060                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
5061         }
5062         if (!compose->header_last || !standard_header) {
5063                 switch(compose->account->protocol) {
5064                         case A_NNTP:
5065                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
5066                                 break;
5067                         default:
5068                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
5069                                 break;
5070                 }                                                                   
5071         }
5072         if (header)
5073                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
5074
5075         g_signal_connect_after(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
5076                          G_CALLBACK(compose_grab_focus_cb), compose);
5077
5078         /* Entry field */
5079         entry = gtk_entry_new(); 
5080         gtk_widget_show(entry);
5081         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
5082
5083         g_signal_connect(G_OBJECT(entry), "key-press-event", 
5084                          G_CALLBACK(compose_headerentry_key_press_event_cb), 
5085                          headerentry);
5086         g_signal_connect(G_OBJECT(entry), "changed", 
5087                          G_CALLBACK(compose_headerentry_changed_cb), 
5088                          headerentry);
5089         g_signal_connect_after(G_OBJECT(entry), "grab_focus",
5090                          G_CALLBACK(compose_grab_focus_cb), compose);
5091                          
5092         /* email dnd */
5093         gtk_drag_dest_set(entry, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5094                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5095                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5096         g_signal_connect(G_OBJECT(entry), "drag_data_received",
5097                          G_CALLBACK(compose_header_drag_received_cb),
5098                          entry);
5099         g_signal_connect(G_OBJECT(entry), "drag-drop",
5100                          G_CALLBACK(compose_drag_drop),
5101                          compose);
5102         
5103         address_completion_register_entry(GTK_ENTRY(entry));
5104
5105         headerentry->compose = compose;
5106         headerentry->combo = combo;
5107         headerentry->entry = entry;
5108         headerentry->headernum = compose->header_nextrow;
5109
5110         compose->header_nextrow++;
5111         compose->header_last = headerentry;
5112 }
5113
5114 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
5115 {
5116         ComposeHeaderEntry *last_header;
5117         
5118         last_header = compose->header_last;
5119         
5120         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
5121         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
5122 }
5123
5124 static GtkWidget *compose_create_header(Compose *compose) 
5125 {
5126         GtkWidget *label;
5127         GtkWidget *hbox;
5128         GtkWidget *from_optmenu_hbox;
5129         GtkWidget *header_scrolledwin;
5130         GtkWidget *header_table;
5131
5132         gint count = 0;
5133
5134         /* header labels and entries */
5135         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5136         gtk_widget_show(header_scrolledwin);
5137         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
5138
5139         header_table = gtk_table_new(2, 2, FALSE);
5140         gtk_widget_show(header_table);
5141         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
5142         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
5143         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
5144         count = 0;
5145
5146         /* option menu for selecting accounts */
5147         hbox = gtk_hbox_new(FALSE, 0);
5148         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
5149         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
5150         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
5151                          GTK_FILL, 0, 2, 0);
5152         from_optmenu_hbox = compose_account_option_menu_create(compose);
5153         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
5154                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
5155         count++;
5156
5157         compose->header_table = header_table;
5158         compose->header_list = NULL;
5159         compose->header_nextrow = count;
5160
5161         compose_create_header_entry(compose);
5162
5163         compose->table            = NULL;
5164
5165         return header_scrolledwin ;
5166 }
5167
5168 GtkWidget *compose_create_attach(Compose *compose)
5169 {
5170         GtkWidget *attach_scrwin;
5171         GtkWidget *attach_clist;
5172
5173         GtkListStore *store;
5174         GtkCellRenderer *renderer;
5175         GtkTreeViewColumn *column;
5176         GtkTreeSelection *selection;
5177
5178         /* attachment list */
5179         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
5180         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
5181                                        GTK_POLICY_AUTOMATIC,
5182                                        GTK_POLICY_AUTOMATIC);
5183         gtk_widget_set_size_request(attach_scrwin, -1, 80);
5184
5185         store = gtk_list_store_new(N_ATTACH_COLS, 
5186                                    G_TYPE_STRING,
5187                                    G_TYPE_STRING,
5188                                    G_TYPE_STRING,
5189                                    G_TYPE_POINTER,
5190                                    G_TYPE_AUTO_POINTER,
5191                                    -1);
5192         attach_clist = GTK_WIDGET(gtk_tree_view_new_with_model
5193                                         (GTK_TREE_MODEL(store)));
5194         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
5195         g_object_unref(store);
5196         
5197         renderer = gtk_cell_renderer_text_new();
5198         column = gtk_tree_view_column_new_with_attributes
5199                         (_("Mime type"), renderer, "text", 
5200                          COL_MIMETYPE, NULL);
5201         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5202         
5203         renderer = gtk_cell_renderer_text_new();
5204         column = gtk_tree_view_column_new_with_attributes
5205                         (_("Size"), renderer, "text", 
5206                          COL_SIZE, NULL);
5207         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5208         
5209         renderer = gtk_cell_renderer_text_new();
5210         column = gtk_tree_view_column_new_with_attributes
5211                         (_("Name"), renderer, "text", 
5212                          COL_NAME, NULL);
5213         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);
5214
5215         gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(attach_clist),
5216                                      prefs_common.enable_rules_hint);
5217         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(attach_clist));
5218         gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE);
5219
5220         g_signal_connect(G_OBJECT(attach_clist), "row_activated",
5221                          G_CALLBACK(attach_selected), compose);
5222         g_signal_connect(G_OBJECT(attach_clist), "button_press_event",
5223                          G_CALLBACK(attach_button_pressed), compose);
5224         g_signal_connect(G_OBJECT(attach_clist), "key_press_event",
5225                          G_CALLBACK(attach_key_pressed), compose);
5226
5227         /* drag and drop */
5228         gtk_drag_dest_set(attach_clist,
5229                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5230                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5231                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5232         g_signal_connect(G_OBJECT(attach_clist), "drag_data_received",
5233                          G_CALLBACK(compose_attach_drag_received_cb),
5234                          compose);
5235         g_signal_connect(G_OBJECT(attach_clist), "drag-drop",
5236                          G_CALLBACK(compose_drag_drop),
5237                          compose);
5238
5239         compose->attach_scrwin = attach_scrwin;
5240         compose->attach_clist  = attach_clist;
5241
5242         return attach_scrwin;
5243 }
5244
5245 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
5246 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
5247
5248 static GtkWidget *compose_create_others(Compose *compose)
5249 {
5250         GtkWidget *table;
5251         GtkWidget *savemsg_checkbtn;
5252         GtkWidget *savemsg_entry;
5253         GtkWidget *savemsg_select;
5254         
5255         guint rowcount = 0;
5256         gchar *folderidentifier;
5257
5258         /* Table for settings */
5259         table = gtk_table_new(3, 1, FALSE);
5260         gtk_widget_show(table);
5261         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
5262         rowcount = 0;
5263
5264         /* Save Message to folder */
5265         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
5266         gtk_widget_show(savemsg_checkbtn);
5267         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5268         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5269                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
5270         }
5271         g_signal_connect(G_OBJECT(savemsg_checkbtn), "toggled",
5272                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
5273
5274         savemsg_entry = gtk_entry_new();
5275         gtk_widget_show(savemsg_entry);
5276         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
5277         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
5278         g_signal_connect_after(G_OBJECT(savemsg_entry), "grab_focus",
5279                          G_CALLBACK(compose_grab_focus_cb), compose);
5280         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5281                 folderidentifier = folder_item_get_identifier(account_get_special_folder
5282                                   (compose->account, F_OUTBOX));
5283                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
5284                 g_free(folderidentifier);
5285         }
5286
5287         savemsg_select = gtkut_get_browse_file_btn(_("_Browse"));
5288         gtk_widget_show(savemsg_select);
5289         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5290         g_signal_connect(G_OBJECT(savemsg_select), "clicked",
5291                          G_CALLBACK(compose_savemsg_select_cb),
5292                          compose);
5293
5294         rowcount++;
5295
5296         compose->savemsg_checkbtn = savemsg_checkbtn;
5297         compose->savemsg_entry = savemsg_entry;
5298
5299         return table;   
5300 }
5301
5302 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
5303 {
5304         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
5305                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
5306 }
5307
5308 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
5309 {
5310         FolderItem *dest;
5311         gchar * path;
5312
5313         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
5314         if (!dest) return;
5315
5316         path = folder_item_get_identifier(dest);
5317
5318         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
5319         g_free(path);
5320 }
5321
5322 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, gboolean wrap,
5323                                   GdkAtom clip);
5324
5325 #define BLOCK_WRAP() {                                                  \
5326         prev_autowrap = compose->autowrap;                              \
5327         buffer = gtk_text_view_get_buffer(                              \
5328                                         GTK_TEXT_VIEW(compose->text));  \
5329         compose->autowrap = FALSE;                                      \
5330                                                                         \
5331         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5332                                 G_CALLBACK(compose_changed_cb),         \
5333                                 compose);                               \
5334         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5335                                 G_CALLBACK(text_inserted),              \
5336                                 compose);                               \
5337 }
5338 #define UNBLOCK_WRAP() {                                                \
5339         compose->autowrap = prev_autowrap;                              \
5340         if (compose->autowrap)                                          \
5341                 compose_wrap_all(compose);                              \
5342                                                                         \
5343         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5344                                 G_CALLBACK(compose_changed_cb),         \
5345                                 compose);                               \
5346         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5347                                 G_CALLBACK(text_inserted),              \
5348                                 compose);                               \
5349 }
5350
5351
5352 static gboolean text_clicked(GtkWidget *text, GdkEventButton *event,
5353                                        Compose *compose)
5354 {
5355         gint prev_autowrap;
5356         GtkTextBuffer *buffer;
5357 #if USE_ASPELL
5358         if (event->button == 3) {
5359                 GtkTextIter iter;
5360                 GtkTextIter sel_start, sel_end;
5361                 gboolean stuff_selected;
5362                 gint x, y;
5363                 /* move the cursor to allow GtkAspell to check the word
5364                  * under the mouse */
5365                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(text),
5366                         GTK_TEXT_WINDOW_TEXT, event->x, event->y,
5367                         &x, &y);
5368                 gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW(text),
5369                         &iter, x, y);
5370                 /* get selection */
5371                 stuff_selected = gtk_text_buffer_get_selection_bounds(
5372                                 GTK_TEXT_VIEW(text)->buffer,
5373                                 &sel_start, &sel_end);
5374
5375                 gtk_text_buffer_place_cursor (GTK_TEXT_VIEW(text)->buffer, &iter);
5376                 /* reselect stuff */
5377                 if (stuff_selected 
5378                 && gtk_text_iter_in_range(&iter, &sel_start, &sel_end)) {
5379                         gtk_text_buffer_select_range(GTK_TEXT_VIEW(text)->buffer,
5380                                 &sel_start, &sel_end);
5381                 }
5382                 return FALSE; /* pass the event so that the right-click goes through */
5383         }
5384 #endif
5385         if (event->button == 2) {
5386                 BLOCK_WRAP();
5387                 entry_paste_clipboard(compose, compose->focused_editable, 
5388                                 prefs_common.linewrap_pastes,
5389                                 GDK_SELECTION_PRIMARY);
5390                 UNBLOCK_WRAP();
5391                 return TRUE;
5392         }
5393         return FALSE;
5394 }
5395
5396 static Compose *compose_create(PrefsAccount *account, ComposeMode mode,
5397                                                  gboolean batch)
5398 {
5399         Compose   *compose;
5400         GtkWidget *window;
5401         GtkWidget *vbox;
5402         GtkWidget *menubar;
5403         GtkWidget *handlebox;
5404
5405         GtkWidget *notebook;
5406
5407         GtkWidget *vbox2;
5408
5409         GtkWidget *label;
5410         GtkWidget *subject_hbox;
5411         GtkWidget *subject_frame;
5412         GtkWidget *subject_entry;
5413         GtkWidget *subject;
5414         GtkWidget *paned;
5415
5416         GtkWidget *edit_vbox;
5417         GtkWidget *ruler_hbox;
5418         GtkWidget *ruler;
5419         GtkWidget *scrolledwin;
5420         GtkWidget *text;
5421         GtkTextBuffer *buffer;
5422         GtkClipboard *clipboard;
5423
5424         UndoMain *undostruct;
5425
5426         gchar *titles[N_ATTACH_COLS];
5427         guint n_menu_entries;
5428         GdkColormap *cmap;
5429         GdkColor color[1];
5430         gboolean success[1];
5431         GtkWidget *popupmenu;
5432         GtkItemFactory *popupfactory;
5433         GtkItemFactory *ifactory;
5434         GtkWidget *tmpl_menu;
5435         gint n_entries;
5436         GtkWidget *menuitem;
5437
5438 #if USE_ASPELL
5439         GtkAspell * gtkaspell = NULL;
5440 #endif
5441
5442         static GdkGeometry geometry;
5443
5444         g_return_val_if_fail(account != NULL, NULL);
5445
5446         debug_print("Creating compose window...\n");
5447         compose = g_new0(Compose, 1);
5448
5449         titles[COL_MIMETYPE] = _("MIME type");
5450         titles[COL_SIZE]     = _("Size");
5451         titles[COL_NAME]     = _("Name");
5452
5453         compose->batch = batch;
5454         compose->account = account;
5455         
5456         compose->mutex = g_mutex_new();
5457         compose->set_cursor_pos = -1;
5458
5459         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5460         gtk_window_set_resizable(GTK_WINDOW(window), TRUE);
5461         gtk_widget_set_size_request(window, -1, prefs_common.compose_height);
5462
5463         if (!geometry.max_width) {
5464                 geometry.max_width = gdk_screen_width();
5465                 geometry.max_height = gdk_screen_height();
5466         }
5467
5468         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5469                                       &geometry, GDK_HINT_MAX_SIZE);
5470         if (!geometry.min_width) {
5471                 geometry.min_width = 600;
5472                 geometry.min_height = 480;
5473         }
5474         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5475                                       &geometry, GDK_HINT_MIN_SIZE);
5476         gtk_widget_set_uposition(window, prefs_common.compose_x, 
5477                                  prefs_common.compose_y);
5478
5479         g_signal_connect(G_OBJECT(window), "delete_event",
5480                          G_CALLBACK(compose_delete_cb), compose);
5481         MANAGE_WINDOW_SIGNALS_CONNECT(window);
5482         gtk_widget_realize(window);
5483
5484         gtkut_widget_set_composer_icon(window);
5485
5486         vbox = gtk_vbox_new(FALSE, 0);
5487         gtk_container_add(GTK_CONTAINER(window), vbox);
5488
5489         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
5490         menubar = menubar_create(window, compose_entries,
5491                                  n_menu_entries, "<Compose>", compose);
5492         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
5493
5494         if (prefs_common.toolbar_detachable) {
5495                 handlebox = gtk_handle_box_new();
5496         } else {
5497                 handlebox = gtk_hbox_new(FALSE, 0);
5498         }
5499         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
5500
5501         gtk_widget_realize(handlebox);
5502         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
5503                                           (gpointer)compose);
5504
5505         vbox2 = gtk_vbox_new(FALSE, 2);
5506         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
5507         gtk_container_set_border_width(GTK_CONTAINER(vbox2), 0);
5508         
5509         /* Notebook */
5510         notebook = gtk_notebook_new();
5511         gtk_widget_set_size_request(notebook, -1, 130);
5512         gtk_widget_show(notebook);
5513
5514         /* header labels and entries */
5515         gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
5516                         compose_create_header(compose),
5517                         gtk_label_new_with_mnemonic(_("Hea_der")));
5518         /* attachment list */
5519         gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
5520                         compose_create_attach(compose),
5521                         gtk_label_new_with_mnemonic(_("_Attachments")));
5522         /* Others Tab */
5523         gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
5524                         compose_create_others(compose),
5525                         gtk_label_new_with_mnemonic(_("Othe_rs")));
5526
5527         /* Subject */
5528         subject_hbox = gtk_hbox_new(FALSE, 0);
5529         gtk_widget_show(subject_hbox);
5530
5531         subject_frame = gtk_frame_new(NULL);
5532         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_NONE);
5533         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, 0);
5534         gtk_widget_show(subject_frame);
5535
5536         subject = gtk_hbox_new(FALSE, 0);
5537         gtk_container_set_border_width(GTK_CONTAINER(subject), 0);
5538         gtk_widget_show(subject);
5539
5540         label = gtk_label_new(_("Subject:"));
5541         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 0);
5542         gtk_widget_show(label);
5543
5544         subject_entry = gtk_entry_new();
5545         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 0);
5546         g_signal_connect_after(G_OBJECT(subject_entry), "grab_focus",
5547                          G_CALLBACK(compose_grab_focus_cb), compose);
5548         gtk_widget_show(subject_entry);
5549         compose->subject_entry = subject_entry;
5550         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
5551         
5552         edit_vbox = gtk_vbox_new(FALSE, 0);
5553
5554         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
5555
5556         /* ruler */
5557         ruler_hbox = gtk_hbox_new(FALSE, 0);
5558         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
5559
5560         ruler = gtk_shruler_new();
5561         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
5562         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
5563                            BORDER_WIDTH);
5564
5565         /* text widget */
5566         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5567         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
5568                                        GTK_POLICY_AUTOMATIC,
5569                                        GTK_POLICY_AUTOMATIC);
5570         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
5571                                             GTK_SHADOW_IN);
5572         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
5573         gtk_widget_set_size_request(scrolledwin, prefs_common.compose_width, -1);
5574
5575         text = gtk_text_view_new();
5576         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
5577         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD_CHAR);
5578         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), TRUE);
5579         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
5580         gtk_text_buffer_add_selection_clipboard(buffer, clipboard);
5581         
5582         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
5583
5584         g_signal_connect_after(G_OBJECT(text), "size_allocate",
5585                                G_CALLBACK(compose_edit_size_alloc),
5586                                ruler);
5587         g_signal_connect(G_OBJECT(buffer), "changed",
5588                          G_CALLBACK(compose_changed_cb), compose);
5589         g_signal_connect(G_OBJECT(text), "grab_focus",
5590                          G_CALLBACK(compose_grab_focus_cb), compose);
5591         g_signal_connect(G_OBJECT(buffer), "insert_text",
5592                          G_CALLBACK(text_inserted), compose);
5593         g_signal_connect(G_OBJECT(text), "button_press_event",
5594                          G_CALLBACK(text_clicked), compose);
5595         g_signal_connect(G_OBJECT(subject_entry), "changed",
5596                          G_CALLBACK(compose_changed_cb), compose);
5597
5598         /* drag and drop */
5599         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5600                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5601                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5602         g_signal_connect(G_OBJECT(text), "drag_data_received",
5603                          G_CALLBACK(compose_insert_drag_received_cb),
5604                          compose);
5605         g_signal_connect(G_OBJECT(text), "drag-drop",
5606                          G_CALLBACK(compose_drag_drop),
5607                          compose);
5608         gtk_widget_show_all(vbox);
5609
5610         /* pane between attach clist and text */
5611         paned = gtk_vpaned_new();
5612         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
5613         gtk_container_add(GTK_CONTAINER(vbox2), paned);
5614         gtk_paned_add1(GTK_PANED(paned), notebook);
5615         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
5616         gtk_widget_show_all(paned);
5617
5618
5619         if (prefs_common.textfont) {
5620                 PangoFontDescription *font_desc;
5621
5622                 font_desc = pango_font_description_from_string
5623                         (prefs_common.textfont);
5624                 if (font_desc) {
5625                         gtk_widget_modify_font(text, font_desc);
5626                         pango_font_description_free(font_desc);
5627                 }
5628         }
5629
5630         color[0] = quote_color;
5631         cmap = gdk_drawable_get_colormap(window->window);
5632         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
5633         if (success[0] == FALSE) {
5634                 GtkStyle *style;
5635
5636                 g_warning("Compose: color allocation failed.\n");
5637                 style = gtk_widget_get_style(text);
5638                 quote_color = style->black;
5639         }
5640
5641         n_entries = sizeof(compose_popup_entries) /
5642                 sizeof(compose_popup_entries[0]);
5643         popupmenu = menu_create_items(compose_popup_entries, n_entries,
5644                                       "<Compose>", &popupfactory,
5645                                       compose);
5646
5647         ifactory = gtk_item_factory_from_widget(menubar);
5648         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5649         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5650         menu_set_sensitive(ifactory, "/Options/Remove references", FALSE);
5651
5652         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5653
5654         undostruct = undo_init(text);
5655         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
5656                                    menubar);
5657
5658         address_completion_start(window);
5659
5660         compose->window        = window;
5661         compose->vbox          = vbox;
5662         compose->menubar       = menubar;
5663         compose->handlebox     = handlebox;
5664
5665         compose->vbox2         = vbox2;
5666
5667         compose->paned = paned;
5668
5669         compose->edit_vbox     = edit_vbox;
5670         compose->ruler_hbox    = ruler_hbox;
5671         compose->ruler         = ruler;
5672         compose->scrolledwin   = scrolledwin;
5673         compose->text          = text;
5674
5675         compose->focused_editable = NULL;
5676
5677         compose->popupmenu    = popupmenu;
5678         compose->popupfactory = popupfactory;
5679
5680         compose->tmpl_menu = tmpl_menu;
5681
5682         compose->mode = mode;
5683
5684         compose->targetinfo = NULL;
5685         compose->replyinfo  = NULL;
5686         compose->fwdinfo    = NULL;
5687
5688         compose->replyto     = NULL;
5689         compose->cc          = NULL;
5690         compose->bcc         = NULL;
5691         compose->followup_to = NULL;
5692
5693         compose->ml_post     = NULL;
5694
5695         compose->inreplyto   = NULL;
5696         compose->references  = NULL;
5697         compose->msgid       = NULL;
5698         compose->boundary    = NULL;
5699
5700         compose->autowrap       = prefs_common.autowrap;
5701
5702         compose->use_signing    = FALSE;
5703         compose->use_encryption = FALSE;
5704         compose->privacy_system = NULL;
5705
5706         compose->modified = FALSE;
5707
5708         compose->return_receipt = FALSE;
5709
5710         compose->to_list        = NULL;
5711         compose->newsgroup_list = NULL;
5712
5713         compose->undostruct = undostruct;
5714
5715         compose->sig_str = NULL;
5716
5717         compose->exteditor_file    = NULL;
5718         compose->exteditor_pid     = -1;
5719         compose->exteditor_tag     = -1;
5720         compose->draft_timeout_tag = -1;
5721
5722 #if USE_ASPELL
5723         menu_set_sensitive(ifactory, "/Spelling", FALSE);
5724         if (mode != COMPOSE_REDIRECT) {
5725                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
5726                     strcmp(prefs_common.dictionary, _("None"))) {
5727                         gtkaspell = gtkaspell_new(prefs_common.aspell_path,
5728                                                   prefs_common.dictionary,
5729                                                   conv_get_locale_charset_str(),
5730                                                   prefs_common.misspelled_col,
5731                                                   prefs_common.check_while_typing,
5732                                                   prefs_common.recheck_when_changing_dict,
5733                                                   prefs_common.use_alternate,
5734                                                   GTK_TEXT_VIEW(text),
5735                                                   GTK_WINDOW(compose->window));
5736                         if (!gtkaspell) {
5737                                 alertpanel_error(_("Spell checker could not "
5738                                                 "be started.\n%s"),
5739                                                 gtkaspell_checkers_strerror());
5740                                 gtkaspell_checkers_reset_error();
5741                         } else {
5742                                 if (!gtkaspell_set_sug_mode(gtkaspell,
5743                                                 prefs_common.aspell_sugmode)) {
5744                                         debug_print("Aspell: could not set "
5745                                                     "suggestion mode %s\n",
5746                                                     gtkaspell_checkers_strerror());
5747                                         gtkaspell_checkers_reset_error();
5748                                 }
5749
5750                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
5751                         }
5752                 }
5753         }
5754         compose->gtkaspell = gtkaspell;
5755 #endif
5756
5757         compose_select_account(compose, account, TRUE);
5758
5759         menu_set_active(ifactory, "/Edit/Auto wrapping", prefs_common.autowrap);
5760         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
5761                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
5762
5763         if (account->set_autobcc && account->auto_bcc && mode != COMPOSE_REEDIT) 
5764                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
5765         
5766         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
5767                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
5768
5769
5770         if (account->protocol != A_NNTP)
5771                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
5772         else
5773                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
5774
5775         addressbook_set_target_compose(compose);
5776         
5777         if (mode != COMPOSE_REDIRECT)
5778                 compose_set_template_menu(compose);
5779         else {
5780                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5781                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
5782         }
5783
5784         compose_list = g_list_append(compose_list, compose);
5785
5786         if (!prefs_common.show_ruler)
5787                 gtk_widget_hide(ruler_hbox);
5788                 
5789         menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Show ruler");
5790         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
5791                                        prefs_common.show_ruler);
5792
5793         /* Priority */
5794         compose->priority = PRIORITY_NORMAL;
5795         compose_update_priority_menu_item(compose);
5796
5797         compose_set_out_encoding(compose);
5798         
5799         /* Actions menu */
5800         compose_update_actions_menu(compose);
5801
5802         /* Privacy Systems menu */
5803         compose_update_privacy_systems_menu(compose);
5804
5805         activate_privacy_system(compose, account, TRUE);
5806         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
5807         if (batch) {
5808                 gtk_widget_realize(window);
5809         } else {
5810                 gtk_widget_show(window);
5811         }
5812         
5813         return compose;
5814 }
5815
5816 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5817 {
5818         GList *accounts;
5819         GtkWidget *optmenu;
5820         GtkWidget *menu;
5821         gint num = 0, def_menu = 0;
5822
5823         accounts = account_get_list();
5824         g_return_val_if_fail(accounts != NULL, NULL);
5825
5826         optmenu = gtk_option_menu_new();
5827         menu = gtk_menu_new();
5828
5829         for (; accounts != NULL; accounts = accounts->next, num++) {
5830                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5831                 GtkWidget *menuitem;
5832                 gchar *name;
5833
5834                 if (ac == compose->account) def_menu = num;
5835
5836                 if (ac->name)
5837                         name = g_strdup_printf("<i>%s</i> : %s &lt;<b>%s</b>&gt;",
5838                                                ac->account_name,
5839                                                ac->name, ac->address);
5840                 else
5841                         name = g_strdup_printf("<i>%s</i> : &lt;<b>%s</b>&gt;",
5842                                                ac->account_name, ac->address);
5843                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
5844                 gtk_label_set_use_markup (
5845                                 GTK_LABEL (gtk_bin_get_child (GTK_BIN (menuitem))),
5846                                 TRUE);
5847                 g_free(name);
5848                 g_signal_connect(G_OBJECT(menuitem), "activate",
5849                                  G_CALLBACK(account_activated),
5850                                  compose);
5851         }
5852
5853         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5854         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5855
5856         return optmenu;
5857 }
5858
5859 static void compose_set_priority_cb(gpointer data,
5860                                     guint action,
5861                                     GtkWidget *widget)
5862 {
5863         Compose *compose = (Compose *) data;
5864         compose->priority = action;
5865 }
5866
5867 static void compose_update_priority_menu_item(Compose * compose)
5868 {
5869         GtkItemFactory *ifactory;
5870         GtkWidget *menuitem = NULL;
5871
5872         ifactory = gtk_item_factory_from_widget(compose->menubar);
5873         
5874         switch (compose->priority) {
5875                 case PRIORITY_HIGHEST:
5876                         menuitem = gtk_item_factory_get_item
5877                                 (ifactory, "/Options/Priority/Highest");
5878                         break;
5879                 case PRIORITY_HIGH:
5880                         menuitem = gtk_item_factory_get_item
5881                                 (ifactory, "/Options/Priority/High");
5882                         break;
5883                 case PRIORITY_NORMAL:
5884                         menuitem = gtk_item_factory_get_item
5885                                 (ifactory, "/Options/Priority/Normal");
5886                         break;
5887                 case PRIORITY_LOW:
5888                         menuitem = gtk_item_factory_get_item
5889                                 (ifactory, "/Options/Priority/Low");
5890                         break;
5891                 case PRIORITY_LOWEST:
5892                         menuitem = gtk_item_factory_get_item
5893                                 (ifactory, "/Options/Priority/Lowest");
5894                         break;
5895         }
5896         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5897 }       
5898
5899 static void compose_set_privacy_system_cb(GtkWidget *widget, gpointer data)
5900 {
5901         Compose *compose = (Compose *) data;
5902         gchar *systemid;
5903         GtkItemFactory *ifactory;
5904         gboolean can_sign = FALSE, can_encrypt = FALSE;
5905
5906         g_return_if_fail(GTK_IS_CHECK_MENU_ITEM(widget));
5907
5908         if (!GTK_CHECK_MENU_ITEM(widget)->active)
5909                 return;
5910
5911         systemid = g_object_get_data(G_OBJECT(widget), "privacy_system");
5912         g_free(compose->privacy_system);
5913         compose->privacy_system = NULL;
5914         if (systemid != NULL) {
5915                 compose->privacy_system = g_strdup(systemid);
5916
5917                 can_sign = privacy_system_can_sign(systemid);
5918                 can_encrypt = privacy_system_can_encrypt(systemid);
5919         }
5920
5921         debug_print("activated privacy system: %s\n", systemid != NULL ? systemid : "None");
5922
5923         ifactory = gtk_item_factory_from_widget(compose->menubar);
5924         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5925         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5926 }
5927
5928 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn)
5929 {
5930         static gchar *branch_path = "/Options/Privacy System";
5931         GtkItemFactory *ifactory;
5932         GtkWidget *menuitem = NULL;
5933         GList *amenu;
5934         gboolean can_sign = FALSE, can_encrypt = FALSE;
5935         gboolean found = FALSE;
5936
5937         ifactory = gtk_item_factory_from_widget(compose->menubar);
5938
5939         if (compose->privacy_system != NULL) {
5940                 gchar *systemid;
5941
5942                 menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
5943                 g_return_if_fail(menuitem != NULL);
5944
5945                 amenu = GTK_MENU_SHELL(menuitem)->children;
5946                 menuitem = NULL;
5947                 while (amenu != NULL) {
5948                         GList *alist = amenu->next;
5949
5950                         systemid = g_object_get_data(G_OBJECT(amenu->data), "privacy_system");
5951                         if (systemid != NULL) {
5952                                 if (strcmp(systemid, compose->privacy_system) == 0) {
5953                                         menuitem = GTK_WIDGET(amenu->data);
5954
5955                                         can_sign = privacy_system_can_sign(systemid);
5956                                         can_encrypt = privacy_system_can_encrypt(systemid);
5957                                         found = TRUE;
5958                                         break;
5959                                 } 
5960                         } else if (strlen(compose->privacy_system) == 0) {
5961                                         menuitem = GTK_WIDGET(amenu->data);
5962
5963                                         can_sign = FALSE;
5964                                         can_encrypt = FALSE;
5965                                         found = TRUE;
5966                                         break;
5967                         }
5968
5969                         amenu = alist;
5970                 }
5971                 if (menuitem != NULL)
5972                         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5973                 
5974                 if (warn && !found && strlen(compose->privacy_system)) {
5975                         gchar *tmp = g_strdup_printf(
5976                                 _("The privacy system '%s' cannot be loaded. You "
5977                                   "will not be able to sign or encrypt this message."),
5978                                   compose->privacy_system);
5979                         alertpanel_warning(tmp);
5980                         g_free(tmp);
5981                 }
5982         } 
5983
5984         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5985         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5986 }       
5987  
5988 static void compose_set_out_encoding(Compose *compose)
5989 {
5990         GtkItemFactoryEntry *entry;
5991         GtkItemFactory *ifactory;
5992         CharSet out_encoding;
5993         gchar *path, *p, *q;
5994         GtkWidget *item;
5995
5996         out_encoding = conv_get_charset_from_str(prefs_common.outgoing_charset);
5997         ifactory = gtk_item_factory_from_widget(compose->menubar);
5998
5999         for (entry = compose_entries; entry->callback != compose_address_cb;
6000              entry++) {
6001                 if (entry->callback == compose_set_encoding_cb &&
6002                     (CharSet)entry->callback_action == out_encoding) {
6003                         p = q = path = g_strdup(entry->path);
6004                         while (*p) {
6005                                 if (*p == '_') {
6006                                         if (p[1] == '_') {
6007                                                 p++;
6008                                                 *q++ = '_';
6009                                         }
6010                                 } else
6011                                         *q++ = *p;
6012                                 p++;
6013                         }
6014                         *q = '\0';
6015                         item = gtk_item_factory_get_item(ifactory, path);
6016                         gtk_widget_activate(item);
6017                         g_free(path);
6018                         break;
6019                 }
6020         }
6021 }
6022
6023 static void compose_set_template_menu(Compose *compose)
6024 {
6025         GSList *tmpl_list, *cur;
6026         GtkWidget *menu;
6027         GtkWidget *item;
6028
6029         tmpl_list = template_get_config();
6030
6031         menu = gtk_menu_new();
6032
6033         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
6034                 Template *tmpl = (Template *)cur->data;
6035
6036                 item = gtk_menu_item_new_with_label(tmpl->name);
6037                 gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
6038                 g_signal_connect(G_OBJECT(item), "activate",
6039                                  G_CALLBACK(compose_template_activate_cb),
6040                                  compose);
6041                 g_object_set_data(G_OBJECT(item), "template", tmpl);
6042                 gtk_widget_show(item);
6043         }
6044
6045         gtk_widget_show(menu);
6046         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
6047 }
6048
6049 void compose_update_actions_menu(Compose *compose)
6050 {
6051         GtkItemFactory *ifactory;
6052
6053         ifactory = gtk_item_factory_from_widget(compose->menubar);
6054         action_update_compose_menu(ifactory, "/Tools/Actions", compose);
6055 }
6056
6057 void compose_update_privacy_systems_menu(Compose *compose)
6058 {
6059         static gchar *branch_path = "/Options/Privacy System";
6060         GtkItemFactory *ifactory;
6061         GtkWidget *menuitem;
6062         GSList *systems, *cur;
6063         GList *amenu;
6064         GtkWidget *widget;
6065         GtkWidget *system_none;
6066         GSList *group;
6067
6068         ifactory = gtk_item_factory_from_widget(compose->menubar);
6069
6070         /* remove old entries */
6071         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
6072         g_return_if_fail(menuitem != NULL);
6073
6074         amenu = GTK_MENU_SHELL(menuitem)->children->next;
6075         while (amenu != NULL) {
6076                 GList *alist = amenu->next;
6077                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
6078                 amenu = alist;
6079         }
6080
6081         system_none = gtk_item_factory_get_widget(ifactory,
6082                 "/Options/Privacy System/None");
6083
6084         g_signal_connect(G_OBJECT(system_none), "activate",
6085                 G_CALLBACK(compose_set_privacy_system_cb), compose);
6086
6087         systems = privacy_get_system_ids();
6088         for (cur = systems; cur != NULL; cur = g_slist_next(cur)) {
6089                 gchar *systemid = cur->data;
6090
6091                 group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(system_none));
6092                 widget = gtk_radio_menu_item_new_with_label(group,
6093                         privacy_system_get_name(systemid));
6094                 g_object_set_data_full(G_OBJECT(widget), "privacy_system",
6095                                        g_strdup(systemid), g_free);
6096                 g_signal_connect(G_OBJECT(widget), "activate",
6097                         G_CALLBACK(compose_set_privacy_system_cb), compose);
6098
6099                 gtk_menu_append(GTK_MENU(system_none->parent), widget);
6100                 gtk_widget_show(widget);
6101                 g_free(systemid);
6102         }
6103         g_slist_free(systems);
6104 }
6105
6106 void compose_reflect_prefs_all(void)
6107 {
6108         GList *cur;
6109         Compose *compose;
6110
6111         for (cur = compose_list; cur != NULL; cur = cur->next) {
6112                 compose = (Compose *)cur->data;
6113                 compose_set_template_menu(compose);
6114         }
6115 }
6116
6117 void compose_reflect_prefs_pixmap_theme(void)
6118 {
6119         GList *cur;
6120         Compose *compose;
6121
6122         for (cur = compose_list; cur != NULL; cur = cur->next) {
6123                 compose = (Compose *)cur->data;
6124                 toolbar_update(TOOLBAR_COMPOSE, compose);
6125         }
6126 }
6127
6128 static void compose_template_apply(Compose *compose, Template *tmpl,
6129                                    gboolean replace)
6130 {
6131         GtkTextView *text;
6132         GtkTextBuffer *buffer;
6133         GtkTextMark *mark;
6134         GtkTextIter iter;
6135         gchar *qmark;
6136         gchar *parsed_str = NULL;
6137         gint cursor_pos = 0;
6138         if (!tmpl) return;
6139
6140         /* process the body */
6141
6142         text = GTK_TEXT_VIEW(compose->text);
6143         buffer = gtk_text_view_get_buffer(text);
6144
6145         if (replace)
6146                 gtk_text_buffer_set_text(buffer, "", -1);
6147
6148         mark = gtk_text_buffer_get_insert(buffer);
6149         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
6150
6151         if (tmpl->value) {
6152                 if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
6153                         parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
6154                                                        NULL, NULL, FALSE);
6155                 } else {
6156                         if (prefs_common.quotemark && *prefs_common.quotemark)
6157                                 qmark = prefs_common.quotemark;
6158                         else
6159                                 qmark = "> ";
6160
6161                         if (compose->replyinfo != NULL)
6162                                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
6163                                                                tmpl->value, qmark, NULL, FALSE);
6164                         else if (compose->fwdinfo != NULL)
6165                                 parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
6166                                                                tmpl->value, qmark, NULL, FALSE);
6167                         else
6168                                 parsed_str = NULL;
6169                 }
6170         }
6171         if (replace && parsed_str && compose->account->auto_sig)
6172                 compose_insert_sig(compose, FALSE);
6173
6174         if (replace && parsed_str) {
6175                 gtk_text_buffer_get_start_iter(buffer, &iter);
6176                 gtk_text_buffer_place_cursor(buffer, &iter);
6177         }
6178         
6179         if (parsed_str) {
6180                 cursor_pos = quote_fmt_get_cursor_pos();
6181                 compose->set_cursor_pos = cursor_pos;
6182                 if (cursor_pos == -1)
6183                         cursor_pos = 0;
6184                 gtk_text_buffer_get_start_iter(buffer, &iter);
6185                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
6186                 gtk_text_buffer_place_cursor(buffer, &iter);
6187         }
6188
6189         /* process the other fields */
6190         compose_template_apply_fields(compose, tmpl);
6191         
6192         compose_changed_cb(NULL, compose);
6193 }
6194
6195 void compose_template_apply_fields(Compose *compose, Template *tmpl)
6196 {
6197         static MsgInfo dummyinfo;
6198         MsgInfo *msginfo = NULL;
6199         gchar *buf = NULL;
6200
6201         if (compose->replyinfo != NULL)
6202                 msginfo = compose->replyinfo;
6203         else if (compose->fwdinfo != NULL)
6204                 msginfo = compose->fwdinfo;
6205         else
6206                 msginfo = &dummyinfo;
6207
6208         if (tmpl->to && *tmpl->to != '\0') {
6209                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6210                 quote_fmt_scan_string(tmpl->to);
6211                 quote_fmt_parse();
6212
6213                 buf = quote_fmt_get_buffer();
6214                 if (buf == NULL) {
6215                         alertpanel_error(_("Message To format error."));
6216                 } else {
6217                         compose_entry_append(compose, buf, COMPOSE_TO);
6218                 }
6219         }
6220
6221         if (tmpl->cc && *tmpl->cc != '\0') {
6222                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6223                 quote_fmt_scan_string(tmpl->cc);
6224                 quote_fmt_parse();
6225
6226                 buf = quote_fmt_get_buffer();
6227                 if (buf == NULL) {
6228                         alertpanel_error(_("Message Cc format error."));
6229                 } else {
6230                         compose_entry_append(compose, buf, COMPOSE_CC);
6231                 }
6232         }
6233
6234         if (tmpl->bcc && *tmpl->bcc != '\0') {
6235                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6236                 quote_fmt_scan_string(tmpl->bcc);
6237                 quote_fmt_parse();
6238
6239                 buf = quote_fmt_get_buffer();
6240                 if (buf == NULL) {
6241                         alertpanel_error(_("Message Bcc format error."));
6242                 } else {
6243                         compose_entry_append(compose, buf, COMPOSE_BCC);
6244                 }
6245         }
6246
6247         /* process the subject */
6248         if (tmpl->subject && *tmpl->subject != '\0') {
6249                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
6250                 quote_fmt_scan_string(tmpl->subject);
6251                 quote_fmt_parse();
6252
6253                 buf = quote_fmt_get_buffer();
6254                 if (buf == NULL) {
6255                         alertpanel_error(_("Message subject format error."));
6256                 } else {
6257                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf);
6258                 }
6259         }
6260 }
6261
6262 static void compose_destroy(Compose *compose)
6263 {
6264         compose_list = g_list_remove(compose_list, compose);
6265
6266         /* NOTE: address_completion_end() does nothing with the window
6267          * however this may change. */
6268         address_completion_end(compose->window);
6269
6270         slist_free_strings(compose->to_list);
6271         g_slist_free(compose->to_list);
6272         slist_free_strings(compose->newsgroup_list);
6273         g_slist_free(compose->newsgroup_list);
6274         slist_free_strings(compose->header_list);
6275         g_slist_free(compose->header_list);
6276
6277         procmsg_msginfo_free(compose->targetinfo);
6278         procmsg_msginfo_free(compose->replyinfo);
6279         procmsg_msginfo_free(compose->fwdinfo);
6280
6281         g_free(compose->replyto);
6282         g_free(compose->cc);
6283         g_free(compose->bcc);
6284         g_free(compose->newsgroups);
6285         g_free(compose->followup_to);
6286
6287         g_free(compose->ml_post);
6288
6289         g_free(compose->inreplyto);
6290         g_free(compose->references);
6291         g_free(compose->msgid);
6292         g_free(compose->boundary);
6293
6294         if (compose->redirect_filename)
6295                 g_free(compose->redirect_filename);
6296         if (compose->undostruct)
6297                 undo_destroy(compose->undostruct);
6298
6299         g_free(compose->sig_str);
6300
6301         g_free(compose->exteditor_file);
6302
6303         g_free(compose->orig_charset);
6304
6305         g_free(compose->privacy_system);
6306
6307         if (addressbook_get_target_compose() == compose)
6308                 addressbook_set_target_compose(NULL);
6309
6310 #if USE_ASPELL
6311         if (compose->gtkaspell) {
6312                 gtkaspell_delete(compose->gtkaspell);
6313                 compose->gtkaspell = NULL;
6314         }
6315 #endif
6316
6317         prefs_common.compose_width = compose->scrolledwin->allocation.width;
6318         prefs_common.compose_height = compose->window->allocation.height;
6319
6320         if (!gtk_widget_get_parent(compose->paned))
6321                 gtk_widget_destroy(compose->paned);
6322         gtk_widget_destroy(compose->popupmenu);
6323
6324         gtk_widget_destroy(compose->window);
6325         toolbar_destroy(compose->toolbar);
6326         g_free(compose->toolbar);
6327         g_mutex_free(compose->mutex);
6328         g_free(compose);
6329 }
6330
6331 static void compose_attach_info_free(AttachInfo *ainfo)
6332 {
6333         g_free(ainfo->file);
6334         g_free(ainfo->content_type);
6335         g_free(ainfo->name);
6336         g_free(ainfo);
6337 }
6338
6339 static void compose_attach_remove_selected(Compose *compose)
6340 {
6341         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6342         GtkTreeSelection *selection;
6343         GList *sel, *cur;
6344         GtkTreeModel *model;
6345
6346         selection = gtk_tree_view_get_selection(tree_view);
6347         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6348
6349         if (!sel) 
6350                 return;
6351
6352         for (cur = sel; cur != NULL; cur = cur->next) {
6353                 GtkTreePath *path = cur->data;
6354                 GtkTreeRowReference *ref = gtk_tree_row_reference_new
6355                                                 (model, cur->data);
6356                 cur->data = ref;
6357                 gtk_tree_path_free(path);
6358         }
6359
6360         for (cur = sel; cur != NULL; cur = cur->next) {
6361                 GtkTreeRowReference *ref = cur->data;
6362                 GtkTreePath *path = gtk_tree_row_reference_get_path(ref);
6363                 GtkTreeIter iter;
6364
6365                 if (gtk_tree_model_get_iter(model, &iter, path))
6366                         gtk_list_store_remove(GTK_LIST_STORE(model), &iter);
6367                 
6368                 gtk_tree_path_free(path);
6369                 gtk_tree_row_reference_free(ref);
6370         }
6371
6372         g_list_free(sel);
6373 }
6374
6375 static struct _AttachProperty
6376 {
6377         GtkWidget *window;
6378         GtkWidget *mimetype_entry;
6379         GtkWidget *encoding_optmenu;
6380         GtkWidget *path_entry;
6381         GtkWidget *filename_entry;
6382         GtkWidget *ok_btn;
6383         GtkWidget *cancel_btn;
6384 } attach_prop;
6385
6386 static void gtk_tree_path_free_(gpointer ptr, gpointer data)
6387 {       
6388         gtk_tree_path_free((GtkTreePath *)ptr);
6389 }
6390
6391 static void compose_attach_property(Compose *compose)
6392 {
6393         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6394         AttachInfo *ainfo;
6395         GtkOptionMenu *optmenu;
6396         GtkTreeSelection *selection;
6397         GList *sel;
6398         GtkTreeModel *model;
6399         GtkTreeIter iter;
6400         GtkTreePath *path;
6401         static gboolean cancelled;
6402
6403         /* only if one selected */
6404         selection = gtk_tree_view_get_selection(tree_view);
6405         if (gtk_tree_selection_count_selected_rows(selection) != 1) 
6406                 return;
6407
6408         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6409         if (!sel)
6410                 return;
6411
6412         path = (GtkTreePath *) sel->data;
6413         gtk_tree_model_get_iter(model, &iter, path);
6414         gtk_tree_model_get(model, &iter, COL_DATA, &ainfo, -1); 
6415         
6416         if (!ainfo) {
6417                 g_list_foreach(sel, gtk_tree_path_free_, NULL);
6418                 g_list_free(sel);
6419                 return;
6420         }               
6421         g_list_free(sel);
6422
6423         if (!attach_prop.window)
6424                 compose_attach_property_create(&cancelled);
6425         gtk_widget_grab_focus(attach_prop.ok_btn);
6426         gtk_widget_show(attach_prop.window);
6427         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
6428
6429         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
6430         if (ainfo->encoding == ENC_UNKNOWN)
6431                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6432                                     GINT_TO_POINTER(ENC_BASE64));
6433         else
6434                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6435                                     GINT_TO_POINTER(ainfo->encoding));
6436
6437         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
6438                            ainfo->content_type ? ainfo->content_type : "");
6439         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
6440                            ainfo->file ? ainfo->file : "");
6441         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
6442                            ainfo->name ? ainfo->name : "");
6443
6444         for (;;) {
6445                 const gchar *entry_text;
6446                 gchar *text;
6447                 gchar *cnttype = NULL;
6448                 gchar *file = NULL;
6449                 off_t size = 0;
6450                 GtkWidget *menu;
6451                 GtkWidget *menuitem;
6452
6453                 cancelled = FALSE;
6454                 gtk_main();
6455
6456                 gtk_widget_hide(attach_prop.window);
6457                 
6458                 if (cancelled) 
6459                         break;
6460
6461                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
6462                 if (*entry_text != '\0') {
6463                         gchar *p;
6464
6465                         text = g_strstrip(g_strdup(entry_text));
6466                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
6467                                 cnttype = g_strdup(text);
6468                                 g_free(text);
6469                         } else {
6470                                 alertpanel_error(_("Invalid MIME type."));
6471                                 g_free(text);
6472                                 continue;
6473                         }
6474                 }
6475
6476                 menu = gtk_option_menu_get_menu(optmenu);
6477                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
6478                 ainfo->encoding = GPOINTER_TO_INT
6479                         (g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID));
6480
6481                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
6482                 if (*entry_text != '\0') {
6483                         if (is_file_exist(entry_text) &&
6484                             (size = get_file_size(entry_text)) > 0)
6485                                 file = g_strdup(entry_text);
6486                         else {
6487                                 alertpanel_error
6488                                         (_("File doesn't exist or is empty."));
6489                                 g_free(cnttype);
6490                                 continue;
6491                         }
6492                 }
6493
6494                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
6495                 if (*entry_text != '\0') {
6496                         g_free(ainfo->name);
6497                         ainfo->name = g_strdup(entry_text);
6498                 }
6499
6500                 if (cnttype) {
6501                         g_free(ainfo->content_type);
6502                         ainfo->content_type = cnttype;
6503                 }
6504                 if (file) {
6505                         g_free(ainfo->file);
6506                         ainfo->file = file;
6507                 }
6508                 if (size)
6509                         ainfo->size = size;
6510
6511                 /* update tree store */
6512                 text = to_human_readable(ainfo->size);
6513                 gtk_tree_model_get_iter(model, &iter, path);
6514                 gtk_list_store_set(GTK_LIST_STORE(model), &iter,
6515                                    COL_MIMETYPE, ainfo->content_type,
6516                                    COL_SIZE, text,
6517                                    COL_NAME, ainfo->name,
6518                                    -1);
6519                 
6520                 break;
6521         }
6522
6523         gtk_tree_path_free(path);
6524 }
6525
6526 #define SET_LABEL_AND_ENTRY(str, entry, top) \
6527 { \
6528         label = gtk_label_new(str); \
6529         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
6530                          GTK_FILL, 0, 0, 0); \
6531         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
6532  \
6533         entry = gtk_entry_new(); \
6534         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
6535                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
6536 }
6537
6538 static void compose_attach_property_create(gboolean *cancelled)
6539 {
6540         GtkWidget *window;
6541         GtkWidget *vbox;
6542         GtkWidget *table;
6543         GtkWidget *label;
6544         GtkWidget *mimetype_entry;
6545         GtkWidget *hbox;
6546         GtkWidget *optmenu;
6547         GtkWidget *optmenu_menu;
6548         GtkWidget *menuitem;
6549         GtkWidget *path_entry;
6550         GtkWidget *filename_entry;
6551         GtkWidget *hbbox;
6552         GtkWidget *ok_btn;
6553         GtkWidget *cancel_btn;
6554         GList     *mime_type_list, *strlist;
6555
6556         debug_print("Creating attach_property window...\n");
6557
6558         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6559         gtk_widget_set_size_request(window, 480, -1);
6560         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
6561         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
6562         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
6563         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
6564         g_signal_connect(G_OBJECT(window), "delete_event",
6565                          G_CALLBACK(attach_property_delete_event),
6566                          cancelled);
6567         g_signal_connect(G_OBJECT(window), "key_press_event",
6568                          G_CALLBACK(attach_property_key_pressed),
6569                          cancelled);
6570
6571         vbox = gtk_vbox_new(FALSE, 8);
6572         gtk_container_add(GTK_CONTAINER(window), vbox);
6573
6574         table = gtk_table_new(4, 2, FALSE);
6575         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
6576         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
6577         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
6578
6579         label = gtk_label_new(_("MIME type")); 
6580         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
6581                          GTK_FILL, 0, 0, 0); 
6582         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
6583         mimetype_entry = gtk_combo_new(); 
6584         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
6585                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6586                          
6587         /* stuff with list */
6588         mime_type_list = procmime_get_mime_type_list();
6589         strlist = NULL;
6590         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
6591                 MimeType *type = (MimeType *) mime_type_list->data;
6592                 gchar *tmp;
6593
6594                 tmp = g_strdup_printf("%s/%s", type->type, type->sub_type);
6595
6596                 if (g_list_find_custom(strlist, tmp, (GCompareFunc)strcmp2))
6597                         g_free(tmp);
6598                 else
6599                         strlist = g_list_insert_sorted(strlist, (gpointer)tmp,
6600                                         (GCompareFunc)strcmp2);
6601         }
6602
6603         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
6604
6605         for (mime_type_list = strlist; mime_type_list != NULL; 
6606                 mime_type_list = mime_type_list->next)
6607                 g_free(mime_type_list->data);
6608         g_list_free(strlist);
6609                          
6610         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
6611
6612         label = gtk_label_new(_("Encoding"));
6613         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
6614                          GTK_FILL, 0, 0, 0);
6615         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
6616
6617         hbox = gtk_hbox_new(FALSE, 0);
6618         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
6619                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6620
6621         optmenu = gtk_option_menu_new();
6622         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
6623
6624         optmenu_menu = gtk_menu_new();
6625         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
6626         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6627         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
6628         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6629         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable",
6630                      ENC_QUOTED_PRINTABLE);
6631         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6632
6633         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
6634
6635         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6636
6637         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
6638         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
6639
6640         gtkut_stock_button_set_create(&hbbox, &cancel_btn, GTK_STOCK_CANCEL,
6641                                       &ok_btn, GTK_STOCK_OK,
6642                                       NULL, NULL);
6643         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
6644         gtk_widget_grab_default(ok_btn);
6645
6646         g_signal_connect(G_OBJECT(ok_btn), "clicked",
6647                          G_CALLBACK(attach_property_ok),
6648                          cancelled);
6649         g_signal_connect(G_OBJECT(cancel_btn), "clicked",
6650                          G_CALLBACK(attach_property_cancel),
6651                          cancelled);
6652
6653         gtk_widget_show_all(vbox);
6654
6655         attach_prop.window           = window;
6656         attach_prop.mimetype_entry   = mimetype_entry;
6657         attach_prop.encoding_optmenu = optmenu;
6658         attach_prop.path_entry       = path_entry;
6659         attach_prop.filename_entry   = filename_entry;
6660         attach_prop.ok_btn           = ok_btn;
6661         attach_prop.cancel_btn       = cancel_btn;
6662 }
6663
6664 #undef SET_LABEL_AND_ENTRY
6665
6666 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
6667 {
6668         *cancelled = FALSE;
6669         gtk_main_quit();
6670 }
6671
6672 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
6673 {
6674         *cancelled = TRUE;
6675         gtk_main_quit();
6676 }
6677
6678 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
6679                                          gboolean *cancelled)
6680 {
6681         *cancelled = TRUE;
6682         gtk_main_quit();
6683
6684         return TRUE;
6685 }
6686
6687 static gboolean attach_property_key_pressed(GtkWidget *widget,
6688                                             GdkEventKey *event,
6689                                             gboolean *cancelled)
6690 {
6691         if (event && event->keyval == GDK_Escape) {
6692                 *cancelled = TRUE;
6693                 gtk_main_quit();
6694         }
6695         return FALSE;
6696 }
6697
6698 static void compose_exec_ext_editor(Compose *compose)
6699 {
6700 #ifdef G_OS_UNIX
6701         gchar *tmp;
6702         pid_t pid;
6703         gint pipe_fds[2];
6704
6705         tmp = g_strdup_printf("%s%ctmpmsg.%p", get_tmp_dir(),
6706                               G_DIR_SEPARATOR, compose);
6707
6708         if (pipe(pipe_fds) < 0) {
6709                 perror("pipe");
6710                 g_free(tmp);
6711                 return;
6712         }
6713
6714         if ((pid = fork()) < 0) {
6715                 perror("fork");
6716                 g_free(tmp);
6717                 return;
6718         }
6719
6720         if (pid != 0) {
6721                 /* close the write side of the pipe */
6722                 close(pipe_fds[1]);
6723
6724                 compose->exteditor_file    = g_strdup(tmp);
6725                 compose->exteditor_pid     = pid;
6726
6727                 compose_set_ext_editor_sensitive(compose, FALSE);
6728
6729                 compose->exteditor_ch = g_io_channel_unix_new(pipe_fds[0]);
6730                 compose->exteditor_tag = g_io_add_watch(compose->exteditor_ch,
6731                                                         G_IO_IN,
6732                                                         compose_input_cb,
6733                                                         compose);
6734         } else {        /* process-monitoring process */
6735                 pid_t pid_ed;
6736
6737                 if (setpgid(0, 0))
6738                         perror("setpgid");
6739
6740                 /* close the read side of the pipe */
6741                 close(pipe_fds[0]);
6742
6743                 if (compose_write_body_to_file(compose, tmp) < 0) {
6744                         fd_write_all(pipe_fds[1], "2\n", 2);
6745                         _exit(1);
6746                 }
6747
6748                 pid_ed = compose_exec_ext_editor_real(tmp);
6749                 if (pid_ed < 0) {
6750                         fd_write_all(pipe_fds[1], "1\n", 2);
6751                         _exit(1);
6752                 }
6753
6754                 /* wait until editor is terminated */
6755                 waitpid(pid_ed, NULL, 0);
6756
6757                 fd_write_all(pipe_fds[1], "0\n", 2);
6758
6759                 close(pipe_fds[1]);
6760                 _exit(0);
6761         }
6762
6763         g_free(tmp);
6764 #endif /* G_OS_UNIX */
6765 }
6766
6767 #ifdef G_OS_UNIX
6768 static gint compose_exec_ext_editor_real(const gchar *file)
6769 {
6770         gchar buf[1024];
6771         gchar *p;
6772         gchar **cmdline;
6773         pid_t pid;
6774
6775         g_return_val_if_fail(file != NULL, -1);
6776
6777         if ((pid = fork()) < 0) {
6778                 perror("fork");
6779                 return -1;
6780         }
6781
6782         if (pid != 0) return pid;
6783
6784         /* grandchild process */
6785
6786         if (setpgid(0, getppid()))
6787                 perror("setpgid");
6788
6789         if (prefs_common.ext_editor_cmd &&
6790             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
6791             *(p + 1) == 's' && !strchr(p + 2, '%')) {
6792                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
6793         } else {
6794                 if (prefs_common.ext_editor_cmd)
6795                         g_warning("External editor command line is invalid: '%s'\n",
6796                                   prefs_common.ext_editor_cmd);
6797                 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, file);
6798         }
6799
6800         cmdline = strsplit_with_quote(buf, " ", 1024);
6801         execvp(cmdline[0], cmdline);
6802
6803         perror("execvp");
6804         g_strfreev(cmdline);
6805
6806         _exit(1);
6807 }
6808
6809 static gboolean compose_ext_editor_kill(Compose *compose)
6810 {
6811         pid_t pgid = compose->exteditor_pid * -1;
6812         gint ret;
6813
6814         ret = kill(pgid, 0);
6815
6816         if (ret == 0 || (ret == -1 && EPERM == errno)) {
6817                 AlertValue val;
6818                 gchar *msg;
6819
6820                 msg = g_strdup_printf
6821                         (_("The external editor is still working.\n"
6822                            "Force terminating the process?\n"
6823                            "process group id: %d"), -pgid);
6824                 val = alertpanel_full(_("Notice"), msg, GTK_STOCK_NO, GTK_STOCK_YES,
6825                                       NULL, FALSE, NULL, ALERT_WARNING, G_ALERTDEFAULT);
6826                         
6827                 g_free(msg);
6828
6829                 if (val == G_ALERTALTERNATE) {
6830                         g_source_remove(compose->exteditor_tag);
6831                         g_io_channel_shutdown(compose->exteditor_ch,
6832                                               FALSE, NULL);
6833                         g_io_channel_unref(compose->exteditor_ch);
6834
6835                         if (kill(pgid, SIGTERM) < 0) perror("kill");
6836                         waitpid(compose->exteditor_pid, NULL, 0);
6837
6838                         g_warning("Terminated process group id: %d", -pgid);
6839                         g_warning("Temporary file: %s",
6840                                   compose->exteditor_file);
6841
6842                         compose_set_ext_editor_sensitive(compose, TRUE);
6843
6844                         g_free(compose->exteditor_file);
6845                         compose->exteditor_file    = NULL;
6846                         compose->exteditor_pid     = -1;
6847                         compose->exteditor_ch      = NULL;
6848                         compose->exteditor_tag     = -1;
6849                 } else
6850                         return FALSE;
6851         }
6852
6853         return TRUE;
6854 }
6855
6856 static gboolean compose_input_cb(GIOChannel *source, GIOCondition condition,
6857                                  gpointer data)
6858 {
6859         gchar buf[3] = "3";
6860         Compose *compose = (Compose *)data;
6861         gsize bytes_read;
6862
6863         debug_print(_("Compose: input from monitoring process\n"));
6864
6865         g_io_channel_read_chars(source, buf, sizeof(buf), &bytes_read, NULL);
6866
6867         g_io_channel_shutdown(source, FALSE, NULL);
6868         g_io_channel_unref(source);
6869
6870         waitpid(compose->exteditor_pid, NULL, 0);
6871
6872         if (buf[0] == '0') {            /* success */
6873                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
6874                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
6875
6876                 gtk_text_buffer_set_text(buffer, "", -1);
6877                 compose_insert_file(compose, compose->exteditor_file);
6878                 compose_changed_cb(NULL, compose);
6879
6880                 if (g_unlink(compose->exteditor_file) < 0)
6881                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6882         } else if (buf[0] == '1') {     /* failed */
6883                 g_warning("Couldn't exec external editor\n");
6884                 if (g_unlink(compose->exteditor_file) < 0)
6885                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6886         } else if (buf[0] == '2') {
6887                 g_warning("Couldn't write to file\n");
6888         } else if (buf[0] == '3') {
6889                 g_warning("Pipe read failed\n");
6890         }
6891
6892         compose_set_ext_editor_sensitive(compose, TRUE);
6893
6894         g_free(compose->exteditor_file);
6895         compose->exteditor_file    = NULL;
6896         compose->exteditor_pid     = -1;
6897         compose->exteditor_ch      = NULL;
6898         compose->exteditor_tag     = -1;
6899
6900         return FALSE;
6901 }
6902
6903 static void compose_set_ext_editor_sensitive(Compose *compose,
6904                                              gboolean sensitive)
6905 {
6906         GtkItemFactory *ifactory;
6907
6908         ifactory = gtk_item_factory_from_widget(compose->menubar);
6909
6910         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
6911         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
6912         menu_set_sensitive(ifactory, "/Message/Insert file", sensitive);
6913         menu_set_sensitive(ifactory, "/Message/Insert signature", sensitive);
6914         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
6915         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
6916         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
6917                            sensitive);
6918
6919         gtk_widget_set_sensitive(compose->text,                       sensitive);
6920         if (compose->toolbar->send_btn)
6921                 gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
6922         if (compose->toolbar->sendl_btn)
6923                 gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
6924         if (compose->toolbar->draft_btn)
6925                 gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
6926         if (compose->toolbar->insert_btn)
6927                 gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
6928         if (compose->toolbar->sig_btn)
6929                 gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
6930         if (compose->toolbar->exteditor_btn)
6931                 gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
6932         if (compose->toolbar->linewrap_current_btn)
6933                 gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, sensitive);
6934         if (compose->toolbar->linewrap_all_btn)
6935                 gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, sensitive);
6936 }
6937 #endif /* G_OS_UNIX */
6938
6939 /**
6940  * compose_undo_state_changed:
6941  *
6942  * Change the sensivity of the menuentries undo and redo
6943  **/
6944 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
6945                                        gint redo_state, gpointer data)
6946 {
6947         GtkWidget *widget = GTK_WIDGET(data);
6948         GtkItemFactory *ifactory;
6949
6950         g_return_if_fail(widget != NULL);
6951
6952         ifactory = gtk_item_factory_from_widget(widget);
6953
6954         switch (undo_state) {
6955         case UNDO_STATE_TRUE:
6956                 if (!undostruct->undo_state) {
6957                         undostruct->undo_state = TRUE;
6958                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
6959                 }
6960                 break;
6961         case UNDO_STATE_FALSE:
6962                 if (undostruct->undo_state) {
6963                         undostruct->undo_state = FALSE;
6964                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
6965                 }
6966                 break;
6967         case UNDO_STATE_UNCHANGED:
6968                 break;
6969         case UNDO_STATE_REFRESH:
6970                 menu_set_sensitive(ifactory, "/Edit/Undo",
6971                                    undostruct->undo_state);
6972                 break;
6973         default:
6974                 g_warning("Undo state not recognized");
6975                 break;
6976         }
6977
6978         switch (redo_state) {
6979         case UNDO_STATE_TRUE:
6980                 if (!undostruct->redo_state) {
6981                         undostruct->redo_state = TRUE;
6982                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
6983                 }
6984                 break;
6985         case UNDO_STATE_FALSE:
6986                 if (undostruct->redo_state) {
6987                         undostruct->redo_state = FALSE;
6988                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
6989                 }
6990                 break;
6991         case UNDO_STATE_UNCHANGED:
6992                 break;
6993         case UNDO_STATE_REFRESH:
6994                 menu_set_sensitive(ifactory, "/Edit/Redo",
6995                                    undostruct->redo_state);
6996                 break;
6997         default:
6998                 g_warning("Redo state not recognized");
6999                 break;
7000         }
7001 }
7002
7003 /* callback functions */
7004
7005 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
7006  * includes "non-client" (windows-izm) in calculation, so this calculation
7007  * may not be accurate.
7008  */
7009 static gboolean compose_edit_size_alloc(GtkEditable *widget,
7010                                         GtkAllocation *allocation,
7011                                         GtkSHRuler *shruler)
7012 {
7013         if (prefs_common.show_ruler) {
7014                 gint char_width = 0, char_height = 0;
7015                 gint line_width_in_chars;
7016
7017                 gtkut_get_font_size(GTK_WIDGET(widget),
7018                                     &char_width, &char_height);
7019                 line_width_in_chars =
7020                         (allocation->width - allocation->x) / char_width;
7021
7022                 /* got the maximum */
7023                 gtk_ruler_set_range(GTK_RULER(shruler),
7024                                     0.0, line_width_in_chars, 0,
7025                                     /*line_width_in_chars*/ char_width);
7026         }
7027
7028         return TRUE;
7029 }
7030
7031 static void account_activated(GtkMenuItem *menuitem, gpointer data)
7032 {
7033         Compose *compose = (Compose *)data;
7034
7035         PrefsAccount *ac;
7036         gchar *folderidentifier;
7037
7038         ac = account_find_from_id(
7039                 GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID)));
7040         g_return_if_fail(ac != NULL);
7041
7042         if (ac != compose->account)
7043                 compose_select_account(compose, ac, FALSE);
7044
7045         /* Set message save folder */
7046         if (account_get_special_folder(compose->account, F_OUTBOX)) {
7047                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
7048         }
7049         g_signal_connect(G_OBJECT(compose->savemsg_checkbtn), "toggled",
7050                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
7051                            
7052         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
7053         if (account_get_special_folder(compose->account, F_OUTBOX)) {
7054                 folderidentifier = folder_item_get_identifier(account_get_special_folder
7055                                   (compose->account, F_OUTBOX));
7056                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
7057                 g_free(folderidentifier);
7058         }
7059 }
7060
7061 static void attach_selected(GtkTreeView *tree_view, GtkTreePath *tree_path,
7062                             GtkTreeViewColumn *column, Compose *compose)
7063 {
7064         compose_attach_property(compose);
7065 }
7066
7067 static gboolean attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
7068                                       gpointer data)
7069 {
7070         Compose *compose = (Compose *)data;
7071         GtkTreeSelection *attach_selection;
7072         gint attach_nr_selected;
7073         GtkItemFactory *ifactory;
7074         
7075         if (!event) return FALSE;
7076
7077         if (event->button == 3) {
7078                 attach_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
7079                 attach_nr_selected = gtk_tree_selection_count_selected_rows(attach_selection);
7080                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
7081                         
7082                 if (attach_nr_selected > 0)
7083                 {
7084                         menu_set_sensitive(ifactory, "/Remove", TRUE);
7085                         menu_set_sensitive(ifactory, "/Properties...", TRUE);
7086                 } else {
7087                         menu_set_sensitive(ifactory, "/Remove", FALSE);
7088                         menu_set_sensitive(ifactory, "/Properties...", FALSE);
7089                 }
7090                         
7091                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
7092                                NULL, NULL, event->button, event->time);
7093                 return TRUE;                           
7094         }
7095
7096         return FALSE;
7097 }
7098
7099 static gboolean attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
7100                                    gpointer data)
7101 {
7102         Compose *compose = (Compose *)data;
7103
7104         if (!event) return FALSE;
7105
7106         switch (event->keyval) {
7107         case GDK_Delete:
7108                 compose_attach_remove_selected(compose);
7109                 break;
7110         }
7111         return FALSE;
7112 }
7113
7114 static void compose_allow_user_actions (Compose *compose, gboolean allow)
7115 {
7116         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
7117         toolbar_comp_set_sensitive(compose, allow);
7118         menu_set_sensitive(ifactory, "/Message", allow);
7119         menu_set_sensitive(ifactory, "/Edit", allow);
7120 #if USE_ASPELL
7121         menu_set_sensitive(ifactory, "/Spelling", allow);
7122 #endif  
7123         menu_set_sensitive(ifactory, "/Options", allow);
7124         menu_set_sensitive(ifactory, "/Tools", allow);
7125         menu_set_sensitive(ifactory, "/Help", allow);
7126         
7127         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), allow);
7128
7129 }
7130
7131 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
7132 {
7133         Compose *compose = (Compose *)data;
7134         
7135         if (prefs_common.work_offline && 
7136             !inc_offline_should_override(
7137                 _("Sylpheed-Claws needs network access in order "
7138                   "to send this email.")))
7139                 return;
7140         
7141         if (compose->draft_timeout_tag != -1) { /* CLAWS: disable draft timeout */
7142                 gtk_timeout_remove(compose->draft_timeout_tag);
7143                 compose->draft_timeout_tag = -1;
7144         }
7145
7146         compose_send(compose);
7147 }
7148
7149 static void compose_send_later_cb(gpointer data, guint action,
7150                                   GtkWidget *widget)
7151 {
7152         Compose *compose = (Compose *)data;
7153         gint val;
7154
7155         val = compose_queue_sub(compose, NULL, NULL, NULL, TRUE);
7156         if (!val) 
7157                 compose_close(compose);
7158         else if (val == -2) {
7159                 alertpanel_error(_("Could not queue message:\n\n%s."), strerror(errno));
7160         }
7161 }
7162
7163 void compose_draft (gpointer data) 
7164 {
7165         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);     
7166 }
7167
7168 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
7169 {
7170         Compose *compose = (Compose *)data;
7171         FolderItem *draft;
7172         gchar *tmp;
7173         gint msgnum;
7174         MsgFlags flag = {0, 0};
7175         static gboolean lock = FALSE;
7176         MsgInfo *newmsginfo;
7177         FILE *fp;
7178         gboolean target_locked = FALSE;
7179         
7180         if (lock) return;
7181
7182         draft = account_get_special_folder(compose->account, F_DRAFT);
7183         g_return_if_fail(draft != NULL);
7184         
7185         if (!g_mutex_trylock(compose->mutex)) {
7186                 /* we don't want to lock the mutex once it's available,
7187                  * because as the only other part of compose.c locking
7188                  * it is compose_close - which means once unlocked,
7189                  * the compose struct will be freed */
7190                 debug_print("couldn't lock mutex, probably sending\n");
7191                 return;
7192         }
7193         
7194         lock = TRUE;
7195
7196         tmp = g_strdup_printf("%s%cdraft.%p", get_tmp_dir(),
7197                               G_DIR_SEPARATOR, compose);
7198         if ((fp = g_fopen(tmp, "wb")) == NULL) {
7199                 FILE_OP_ERROR(tmp, "fopen");
7200                 goto unlock;
7201         }
7202
7203         /* chmod for security */
7204         if (change_file_mode_rw(fp, tmp) < 0) {
7205                 FILE_OP_ERROR(tmp, "chmod");
7206                 g_warning("can't change file mode\n");
7207         }
7208
7209         /* Save draft infos */
7210         fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
7211         fprintf(fp, "S:%s\n", compose->account->address);
7212         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
7213                 gchar *savefolderid;
7214
7215                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
7216                 fprintf(fp, "SCF:%s\n", savefolderid);
7217                 g_free(savefolderid);
7218         }
7219         if (compose->return_receipt) {
7220                 fprintf(fp, "RRCPT:1\n");
7221         }
7222         if (compose->privacy_system) {
7223                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
7224                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
7225                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
7226         }
7227         fprintf(fp, "\n");
7228
7229         if (compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_STORE) < 0) {
7230                 fclose(fp);
7231                 g_unlink(tmp);
7232                 g_free(tmp);
7233                 goto unlock;
7234         }
7235         fclose(fp);
7236         
7237         if (compose->targetinfo) {
7238                 target_locked = MSG_IS_LOCKED(compose->targetinfo->flags);
7239                 flag.perm_flags = target_locked?MSG_LOCKED:0;
7240         }
7241         flag.tmp_flags = MSG_DRAFT;
7242
7243         folder_item_scan(draft);
7244         if ((msgnum = folder_item_add_msg(draft, tmp, &flag, TRUE)) < 0) {
7245                 g_unlink(tmp);
7246                 g_free(tmp);
7247                 if (action != COMPOSE_AUTO_SAVE)
7248                         alertpanel_error(_("Could not save draft."));
7249                 goto unlock;
7250         }
7251         g_free(tmp);
7252         draft->mtime = 0;       /* force updating */
7253
7254         if (compose->mode == COMPOSE_REEDIT) {
7255                 compose_remove_reedit_target(compose, TRUE);
7256         }
7257
7258         newmsginfo = folder_item_get_msginfo(draft, msgnum);
7259         if (newmsginfo) {
7260                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
7261                 if (target_locked)
7262                         procmsg_msginfo_set_flags(newmsginfo, MSG_LOCKED, MSG_DRAFT);
7263                 else
7264                         procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
7265                 if (compose_use_attach(compose))
7266                         procmsg_msginfo_set_flags(newmsginfo, 0,
7267                                                   MSG_HAS_ATTACHMENT);
7268
7269                 procmsg_msginfo_free(newmsginfo);
7270         }
7271         
7272         folder_item_scan(draft);
7273         
7274         if (action == COMPOSE_QUIT_EDITING) {
7275                 lock = FALSE;
7276                 g_mutex_unlock(compose->mutex); /* must be done before closing */
7277                 compose_close(compose);
7278                 return;
7279         } else {
7280                 struct stat s;
7281                 gchar *path;
7282
7283                 path = folder_item_fetch_msg(draft, msgnum);
7284                 if (path == NULL) {
7285                         debug_print("can't fetch %s:%d\n",draft->path, msgnum);
7286                         goto unlock;
7287                 }
7288                 if (g_stat(path, &s) < 0) {
7289                         FILE_OP_ERROR(path, "stat");
7290                         g_free(path);
7291                         goto unlock;
7292                 }
7293                 g_free(path);
7294
7295                 procmsg_msginfo_free(compose->targetinfo);
7296                 compose->targetinfo = procmsg_msginfo_new();
7297                 compose->targetinfo->msgnum = msgnum;
7298                 compose->targetinfo->size = s.st_size;
7299                 compose->targetinfo->mtime = s.st_mtime;
7300                 compose->targetinfo->folder = draft;
7301                 if (target_locked)
7302                         procmsg_msginfo_set_flags(compose->targetinfo, MSG_LOCKED, 0);
7303                 compose->mode = COMPOSE_REEDIT;
7304                 
7305                 if (action == COMPOSE_AUTO_SAVE) {
7306                         compose->autosaved_draft = compose->targetinfo;
7307                 }
7308                 compose->modified = FALSE;
7309                 compose_set_title(compose);
7310         }
7311 unlock:
7312         lock = FALSE;
7313         g_mutex_unlock(compose->mutex);
7314 }
7315
7316 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
7317 {
7318         Compose *compose = (Compose *)data;
7319         GList *file_list;
7320
7321         if (compose->redirect_filename != NULL)
7322                 return;
7323
7324         file_list = filesel_select_multiple_files_open(_("Select file"));
7325
7326         if (file_list) {
7327                 GList *tmp;
7328
7329                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7330                         gchar *file = (gchar *) tmp->data;
7331                         gchar *utf8_filename = conv_filename_to_utf8(file);
7332                         compose_attach_append(compose, file, utf8_filename, NULL);
7333                         compose_changed_cb(NULL, compose);
7334                         g_free(file);
7335                         g_free(utf8_filename);
7336                 }
7337                 g_list_free(file_list);
7338         }               
7339 }
7340
7341 static void compose_insert_file_cb(gpointer data, guint action,
7342                                    GtkWidget *widget)
7343 {
7344         Compose *compose = (Compose *)data;
7345         GList *file_list;
7346
7347         file_list = filesel_select_multiple_files_open(_("Select file"));
7348
7349         if (file_list) {
7350                 GList *tmp;
7351
7352                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7353                         gchar *file = (gchar *) tmp->data;
7354                         gchar *filedup = g_strdup(file);
7355                         gchar *shortfile = g_path_get_basename(filedup);
7356                         ComposeInsertResult res;
7357
7358                         res = compose_insert_file(compose, file);
7359                         if (res == COMPOSE_INSERT_READ_ERROR) {
7360                                 alertpanel_error(_("File '%s' could not be read."), shortfile);
7361                         } else if (res == COMPOSE_INSERT_INVALID_CHARACTER) {
7362                                 alertpanel_error(_("File '%s' contained invalid characters\n"
7363                                                    "for the current encoding, insertion may be incorrect."), shortfile);
7364                         }
7365                         g_free(shortfile);
7366                         g_free(filedup);
7367                         g_free(file);
7368                 }
7369                 g_list_free(file_list);
7370         }
7371 }
7372
7373 static void compose_insert_sig_cb(gpointer data, guint action,
7374                                   GtkWidget *widget)
7375 {
7376         Compose *compose = (Compose *)data;
7377
7378         compose_insert_sig(compose, FALSE);
7379 }
7380
7381 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
7382                               gpointer data)
7383 {
7384         gint x, y;
7385         Compose *compose = (Compose *)data;
7386
7387         gtkut_widget_get_uposition(widget, &x, &y);
7388         prefs_common.compose_x = x;
7389         prefs_common.compose_y = y;
7390
7391         if (compose->sending)
7392                 return TRUE;
7393         compose_close_cb(compose, 0, NULL);
7394         return TRUE;
7395 }
7396
7397 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
7398 {
7399         Compose *compose = (Compose *)data;
7400         AlertValue val;
7401
7402 #ifdef G_OS_UNIX
7403         if (compose->exteditor_tag != -1) {
7404                 if (!compose_ext_editor_kill(compose))
7405                         return;
7406         }
7407 #endif
7408
7409         if (compose->modified) {
7410                 val = alertpanel(_("Discard message"),
7411                                  _("This message has been modified. Discard it?"),
7412                                  _("_Discard"), _("_Save to Drafts"), GTK_STOCK_CANCEL);
7413
7414                 switch (val) {
7415                 case G_ALERTDEFAULT:
7416                         if (prefs_common.autosave)
7417                                 compose_remove_draft(compose);                  
7418                         break;
7419                 case G_ALERTALTERNATE:
7420                         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);
7421                         return;
7422                 default:
7423                         return;
7424                 }
7425         }
7426
7427         compose_close(compose);
7428 }
7429
7430 static void compose_set_encoding_cb(gpointer data, guint action,
7431                                     GtkWidget *widget)
7432 {
7433         Compose *compose = (Compose *)data;
7434
7435         if (GTK_CHECK_MENU_ITEM(widget)->active)
7436                 compose->out_encoding = (CharSet)action;
7437 }
7438
7439 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
7440 {
7441         Compose *compose = (Compose *)data;
7442
7443         addressbook_open(compose);
7444 }
7445
7446 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
7447 {
7448         Compose *compose = (Compose *)data;
7449         Template *tmpl;
7450         gchar *msg;
7451         AlertValue val;
7452
7453         tmpl = g_object_get_data(G_OBJECT(widget), "template");
7454         g_return_if_fail(tmpl != NULL);
7455
7456         msg = g_strdup_printf(_("Do you want to apply the template '%s' ?"),
7457                               tmpl->name);
7458         val = alertpanel(_("Apply template"), msg,
7459                          _("_Replace"), _("_Insert"), GTK_STOCK_CANCEL);
7460         g_free(msg);
7461
7462         if (val == G_ALERTDEFAULT)
7463                 compose_template_apply(compose, tmpl, TRUE);
7464         else if (val == G_ALERTALTERNATE)
7465                 compose_template_apply(compose, tmpl, FALSE);
7466 }
7467
7468 static void compose_ext_editor_cb(gpointer data, guint action,
7469                                   GtkWidget *widget)
7470 {
7471         Compose *compose = (Compose *)data;
7472
7473         compose_exec_ext_editor(compose);
7474 }
7475
7476 static void compose_undo_cb(Compose *compose)
7477 {
7478         gboolean prev_autowrap = compose->autowrap;
7479
7480         compose->autowrap = FALSE;
7481         undo_undo(compose->undostruct);
7482         compose->autowrap = prev_autowrap;
7483 }
7484
7485 static void compose_redo_cb(Compose *compose)
7486 {
7487         gboolean prev_autowrap = compose->autowrap;
7488         
7489         compose->autowrap = FALSE;
7490         undo_redo(compose->undostruct);
7491         compose->autowrap = prev_autowrap;
7492 }
7493
7494 static void entry_cut_clipboard(GtkWidget *entry)
7495 {
7496         if (GTK_IS_EDITABLE(entry))
7497                 gtk_editable_cut_clipboard (GTK_EDITABLE(entry));
7498         else if (GTK_IS_TEXT_VIEW(entry))
7499                 gtk_text_buffer_cut_clipboard(
7500                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7501                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),
7502                         TRUE);
7503 }
7504
7505 static void entry_copy_clipboard(GtkWidget *entry)
7506 {
7507         if (GTK_IS_EDITABLE(entry))
7508                 gtk_editable_copy_clipboard (GTK_EDITABLE(entry));
7509         else if (GTK_IS_TEXT_VIEW(entry))
7510                 gtk_text_buffer_copy_clipboard(
7511                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7512                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD));
7513 }
7514
7515 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, 
7516                                   gboolean wrap, GdkAtom clip)
7517 {
7518         if (GTK_IS_TEXT_VIEW(entry)) {
7519                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7520                 GtkTextMark *mark_start = gtk_text_buffer_get_insert(buffer);
7521                 GtkTextIter start_iter, end_iter;
7522                 gint start, end;
7523                 
7524                 gchar *contents = gtk_clipboard_wait_for_text(gtk_clipboard_get(clip));
7525
7526                 if (contents == NULL)
7527                         return;
7528
7529                 gtk_text_buffer_delete_selection(buffer, FALSE, TRUE);
7530                 gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7531                 
7532                 start = gtk_text_iter_get_offset(&start_iter);
7533
7534                 gtk_text_buffer_insert(buffer, &start_iter, contents, strlen(contents));
7535                 
7536                 if (!wrap) {
7537                         end = start + strlen(contents);
7538                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
7539                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
7540                         gtk_text_buffer_apply_tag_by_name(buffer, "no_wrap", &start_iter, &end_iter);
7541                 } else if (wrap && clip == GDK_SELECTION_PRIMARY) {
7542                         mark_start = gtk_text_buffer_get_insert(buffer);
7543                         gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7544                         gtk_text_iter_backward_char(&start_iter);
7545                         compose_beautify_paragraph(compose, &start_iter, TRUE);
7546                 }
7547                 
7548         } else if (GTK_IS_EDITABLE(entry))
7549                 gtk_editable_paste_clipboard (GTK_EDITABLE(entry));
7550         
7551 }
7552
7553 static void entry_allsel(GtkWidget *entry)
7554 {
7555         if (GTK_IS_EDITABLE(entry))
7556                 gtk_editable_select_region(GTK_EDITABLE(entry), 0, -1);
7557         else if (GTK_IS_TEXT_VIEW(entry)) {
7558                 GtkTextIter startiter, enditer;
7559                 GtkTextBuffer *textbuf;
7560
7561                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7562                 gtk_text_buffer_get_start_iter(textbuf, &startiter);
7563                 gtk_text_buffer_get_end_iter(textbuf, &enditer);
7564
7565                 gtk_text_buffer_move_mark_by_name(textbuf, 
7566                         "selection_bound", &startiter);
7567                 gtk_text_buffer_move_mark_by_name(textbuf, 
7568                         "insert", &enditer);
7569         }
7570 }
7571
7572 static void compose_cut_cb(Compose *compose)
7573 {
7574         if (compose->focused_editable &&
7575             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7576                 entry_cut_clipboard(compose->focused_editable);
7577 }
7578
7579 static void compose_copy_cb(Compose *compose)
7580 {
7581         if (compose->focused_editable &&
7582             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7583                 entry_copy_clipboard(compose->focused_editable);
7584 }
7585
7586 static void compose_paste_cb(Compose *compose)
7587 {
7588         gint prev_autowrap;
7589         GtkTextBuffer *buffer;
7590         BLOCK_WRAP();
7591         if (compose->focused_editable &&
7592             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7593                 entry_paste_clipboard(compose, compose->focused_editable, 
7594                                 prefs_common.linewrap_pastes,
7595                                 GDK_SELECTION_CLIPBOARD);
7596         UNBLOCK_WRAP();
7597 }
7598
7599 static void compose_paste_as_quote_cb(Compose *compose)
7600 {
7601         gint wrap_quote = prefs_common.linewrap_quote;
7602         if (compose->focused_editable &&
7603             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
7604                 /* let text_insert() (called directly or at a later time
7605                  * after the gtk_editable_paste_clipboard) know that 
7606                  * text is to be inserted as a quotation. implemented
7607                  * by using a simple refcount... */
7608                 gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data(
7609                                                 G_OBJECT(compose->focused_editable),
7610                                                 "paste_as_quotation"));
7611                 g_object_set_data(G_OBJECT(compose->focused_editable),
7612                                     "paste_as_quotation",
7613                                     GINT_TO_POINTER(paste_as_quotation + 1));
7614                 prefs_common.linewrap_quote = prefs_common.linewrap_pastes;
7615                 entry_paste_clipboard(compose, compose->focused_editable, 
7616                                 prefs_common.linewrap_pastes,
7617                                 GDK_SELECTION_CLIPBOARD);
7618                 prefs_common.linewrap_quote = wrap_quote;
7619         }
7620 }
7621
7622 static void compose_paste_no_wrap_cb(Compose *compose)
7623 {
7624         gint prev_autowrap;
7625         GtkTextBuffer *buffer;
7626         BLOCK_WRAP();
7627         if (compose->focused_editable &&
7628             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7629                 entry_paste_clipboard(compose, compose->focused_editable, FALSE,
7630                         GDK_SELECTION_CLIPBOARD);
7631         UNBLOCK_WRAP();
7632 }
7633
7634 static void compose_paste_wrap_cb(Compose *compose)
7635 {
7636         gint prev_autowrap;
7637         GtkTextBuffer *buffer;
7638         BLOCK_WRAP();
7639         if (compose->focused_editable &&
7640             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7641                 entry_paste_clipboard(compose, compose->focused_editable, TRUE,
7642                         GDK_SELECTION_CLIPBOARD);
7643         UNBLOCK_WRAP();
7644 }
7645
7646 static void compose_allsel_cb(Compose *compose)
7647 {
7648         if (compose->focused_editable &&
7649             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7650                 entry_allsel(compose->focused_editable);
7651 }
7652
7653 static void textview_move_beginning_of_line (GtkTextView *text)
7654 {
7655         GtkTextBuffer *buffer;
7656         GtkTextMark *mark;
7657         GtkTextIter ins;
7658
7659         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7660
7661         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7662         mark = gtk_text_buffer_get_insert(buffer);
7663         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7664         gtk_text_iter_set_line_offset(&ins, 0);
7665         gtk_text_buffer_place_cursor(buffer, &ins);
7666 }
7667
7668 static void textview_move_forward_character (GtkTextView *text)
7669 {
7670         GtkTextBuffer *buffer;
7671         GtkTextMark *mark;
7672         GtkTextIter ins;
7673
7674         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7675
7676         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7677         mark = gtk_text_buffer_get_insert(buffer);
7678         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7679         if (gtk_text_iter_forward_cursor_position(&ins))
7680                 gtk_text_buffer_place_cursor(buffer, &ins);
7681 }
7682
7683 static void textview_move_backward_character (GtkTextView *text)
7684 {
7685         GtkTextBuffer *buffer;
7686         GtkTextMark *mark;
7687         GtkTextIter ins;
7688
7689         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7690
7691         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7692         mark = gtk_text_buffer_get_insert(buffer);
7693         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7694         if (gtk_text_iter_backward_cursor_position(&ins))
7695                 gtk_text_buffer_place_cursor(buffer, &ins);
7696 }
7697
7698 static void textview_move_forward_word (GtkTextView *text)
7699 {
7700         GtkTextBuffer *buffer;
7701         GtkTextMark *mark;
7702         GtkTextIter ins;
7703         gint count;
7704
7705         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7706
7707         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7708         mark = gtk_text_buffer_get_insert(buffer);
7709         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7710         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7711         if (gtk_text_iter_forward_word_ends(&ins, count)) {
7712                 gtk_text_iter_backward_word_start(&ins);
7713                 gtk_text_buffer_place_cursor(buffer, &ins);
7714         }
7715 }
7716
7717 static void textview_move_backward_word (GtkTextView *text)
7718 {
7719         GtkTextBuffer *buffer;
7720         GtkTextMark *mark;
7721         GtkTextIter ins;
7722         gint count;
7723
7724         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7725
7726         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7727         mark = gtk_text_buffer_get_insert(buffer);
7728         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7729         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7730         if (gtk_text_iter_backward_word_starts(&ins, 1))
7731                 gtk_text_buffer_place_cursor(buffer, &ins);
7732 }
7733
7734 static void textview_move_end_of_line (GtkTextView *text)
7735 {
7736         GtkTextBuffer *buffer;
7737         GtkTextMark *mark;
7738         GtkTextIter ins;
7739
7740         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7741
7742         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7743         mark = gtk_text_buffer_get_insert(buffer);
7744         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7745         if (gtk_text_iter_forward_to_line_end(&ins))
7746                 gtk_text_buffer_place_cursor(buffer, &ins);
7747 }
7748
7749 static void textview_move_next_line (GtkTextView *text)
7750 {
7751         GtkTextBuffer *buffer;
7752         GtkTextMark *mark;
7753         GtkTextIter ins;
7754         gint offset;
7755
7756         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7757
7758         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7759         mark = gtk_text_buffer_get_insert(buffer);
7760         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7761         offset = gtk_text_iter_get_line_offset(&ins);
7762         if (gtk_text_iter_forward_line(&ins)) {
7763                 gtk_text_iter_set_line_offset(&ins, offset);
7764                 gtk_text_buffer_place_cursor(buffer, &ins);
7765         }
7766 }
7767
7768 static void textview_move_previous_line (GtkTextView *text)
7769 {
7770         GtkTextBuffer *buffer;
7771         GtkTextMark *mark;
7772         GtkTextIter ins;
7773         gint offset;
7774
7775         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7776
7777         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7778         mark = gtk_text_buffer_get_insert(buffer);
7779         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7780         offset = gtk_text_iter_get_line_offset(&ins);
7781         if (gtk_text_iter_backward_line(&ins)) {
7782                 gtk_text_iter_set_line_offset(&ins, offset);
7783                 gtk_text_buffer_place_cursor(buffer, &ins);
7784         }
7785 }
7786
7787 static void textview_delete_forward_character (GtkTextView *text)
7788 {
7789         GtkTextBuffer *buffer;
7790         GtkTextMark *mark;
7791         GtkTextIter ins, end_iter;
7792
7793         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7794
7795         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7796         mark = gtk_text_buffer_get_insert(buffer);
7797         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7798         end_iter = ins;
7799         if (gtk_text_iter_forward_char(&end_iter)) {
7800                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7801         }
7802 }
7803
7804 static void textview_delete_backward_character (GtkTextView *text)
7805 {
7806         GtkTextBuffer *buffer;
7807         GtkTextMark *mark;
7808         GtkTextIter ins, end_iter;
7809
7810         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7811
7812         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7813         mark = gtk_text_buffer_get_insert(buffer);
7814         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7815         end_iter = ins;
7816         if (gtk_text_iter_backward_char(&end_iter)) {
7817                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7818         }
7819 }
7820
7821 static void textview_delete_forward_word (GtkTextView *text)
7822 {
7823         GtkTextBuffer *buffer;
7824         GtkTextMark *mark;
7825         GtkTextIter ins, end_iter;
7826
7827         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7828
7829         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7830         mark = gtk_text_buffer_get_insert(buffer);
7831         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7832         end_iter = ins;
7833         if (gtk_text_iter_forward_word_end(&end_iter)) {
7834                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7835         }
7836 }
7837
7838 static void textview_delete_backward_word (GtkTextView *text)
7839 {
7840         GtkTextBuffer *buffer;
7841         GtkTextMark *mark;
7842         GtkTextIter ins, end_iter;
7843
7844         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7845
7846         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7847         mark = gtk_text_buffer_get_insert(buffer);
7848         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7849         end_iter = ins;
7850         if (gtk_text_iter_backward_word_start(&end_iter)) {
7851                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7852         }
7853 }
7854
7855 static void textview_delete_line (GtkTextView *text)
7856 {
7857         GtkTextBuffer *buffer;
7858         GtkTextMark *mark;
7859         GtkTextIter ins, start_iter, end_iter;
7860         gboolean found;
7861
7862         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7863
7864         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7865         mark = gtk_text_buffer_get_insert(buffer);
7866         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7867
7868         start_iter = ins;
7869         gtk_text_iter_set_line_offset(&start_iter, 0);
7870
7871         end_iter = ins;
7872         if (gtk_text_iter_ends_line(&end_iter))
7873                 found = gtk_text_iter_forward_char(&end_iter);
7874         else
7875                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7876
7877         if (found)
7878                 gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
7879 }
7880
7881 static void textview_delete_to_line_end (GtkTextView *text)
7882 {
7883         GtkTextBuffer *buffer;
7884         GtkTextMark *mark;
7885         GtkTextIter ins, end_iter;
7886         gboolean found;
7887
7888         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7889
7890         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7891         mark = gtk_text_buffer_get_insert(buffer);
7892         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7893         end_iter = ins;
7894         if (gtk_text_iter_ends_line(&end_iter))
7895                 found = gtk_text_iter_forward_char(&end_iter);
7896         else
7897                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7898         if (found)
7899                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7900 }
7901
7902 static void compose_advanced_action_cb(Compose *compose,
7903                                         ComposeCallAdvancedAction action)
7904 {
7905         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
7906         static struct {
7907                 void (*do_action) (GtkTextView *text);
7908         } action_table[] = {
7909                 {textview_move_beginning_of_line},
7910                 {textview_move_forward_character},
7911                 {textview_move_backward_character},
7912                 {textview_move_forward_word},
7913                 {textview_move_backward_word},
7914                 {textview_move_end_of_line},
7915                 {textview_move_next_line},
7916                 {textview_move_previous_line},
7917                 {textview_delete_forward_character},
7918                 {textview_delete_backward_character},
7919                 {textview_delete_forward_word},
7920                 {textview_delete_backward_word},
7921                 {textview_delete_line},
7922                 {NULL}, /* gtk_stext_delete_line_n */
7923                 {textview_delete_to_line_end}
7924         };
7925
7926         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
7927
7928         if (action >= COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE &&
7929             action <= COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END) {
7930                 if (action_table[action].do_action)
7931                         action_table[action].do_action(text);
7932                 else
7933                         g_warning("Not implemented yet.");
7934         }
7935 }
7936
7937 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
7938 {
7939         gchar *str = NULL;
7940         
7941         if (GTK_IS_EDITABLE(widget)) {
7942                 str = gtk_editable_get_chars(GTK_EDITABLE(widget), 0, -1);
7943                 gtk_editable_set_position(GTK_EDITABLE(widget), 
7944                         strlen(str));
7945                 g_free(str);
7946                 if (widget->parent && widget->parent->parent
7947                  && widget->parent->parent->parent) {
7948                         if (GTK_IS_SCROLLED_WINDOW(widget->parent->parent->parent)) {
7949                                 gint y = widget->allocation.y;
7950                                 gint height = widget->allocation.height;
7951                                 GtkAdjustment *shown = gtk_scrolled_window_get_vadjustment
7952                                         (GTK_SCROLLED_WINDOW(widget->parent->parent->parent));
7953
7954                                 if (y < (int)shown->value) {
7955                                         gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), y - 1);
7956                                 }
7957                                 if (y + height > (int)shown->value + (int)shown->page_size) {
7958                                         if (y - height - 1 < (int)shown->upper - (int)shown->page_size) {
7959                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7960                                                         y + height - (int)shown->page_size - 1);
7961                                         } else {
7962                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7963                                                         (int)shown->upper - (int)shown->page_size - 1);
7964                                         }
7965                                 }
7966                         }
7967                 }
7968         }
7969
7970         if (GTK_IS_EDITABLE(widget) || GTK_IS_TEXT_VIEW(widget))
7971                 compose->focused_editable = widget;
7972 }
7973
7974 static void compose_changed_cb(GtkTextBuffer *textbuf, Compose *compose)
7975 {
7976         compose->modified = TRUE;
7977         compose_set_title(compose);
7978 }
7979
7980 static void compose_wrap_cb(gpointer data, guint action, GtkWidget *widget)
7981 {
7982         Compose *compose = (Compose *)data;
7983
7984         if (action == 1)
7985                 compose_wrap_all_full(compose, TRUE);
7986         else
7987                 compose_beautify_paragraph(compose, NULL, TRUE);
7988 }
7989
7990 static void compose_find_cb(gpointer data, guint action, GtkWidget *widget)
7991 {
7992         Compose *compose = (Compose *)data;
7993
7994         message_search_compose(compose);
7995 }
7996
7997 static void compose_toggle_autowrap_cb(gpointer data, guint action,
7998                                        GtkWidget *widget)
7999 {
8000         Compose *compose = (Compose *)data;
8001         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
8002         if (compose->autowrap)
8003                 compose_wrap_all_full(compose, TRUE);
8004         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
8005 }
8006
8007 static void compose_toggle_sign_cb(gpointer data, guint action,
8008                                    GtkWidget *widget)
8009 {
8010         Compose *compose = (Compose *)data;
8011
8012         if (GTK_CHECK_MENU_ITEM(widget)->active)
8013                 compose->use_signing = TRUE;
8014         else
8015                 compose->use_signing = FALSE;
8016 }
8017
8018 static void compose_toggle_encrypt_cb(gpointer data, guint action,
8019                                       GtkWidget *widget)
8020 {
8021         Compose *compose = (Compose *)data;
8022
8023         if (GTK_CHECK_MENU_ITEM(widget)->active)
8024                 compose->use_encryption = TRUE;
8025         else
8026                 compose->use_encryption = FALSE;
8027 }
8028
8029 static void activate_privacy_system(Compose *compose, PrefsAccount *account, gboolean warn) 
8030 {
8031         g_free(compose->privacy_system);
8032
8033         compose->privacy_system = g_strdup(account->default_privacy_system);
8034         compose_update_privacy_system_menu_item(compose, warn);
8035 }
8036
8037 static void compose_toggle_ruler_cb(gpointer data, guint action,
8038                                     GtkWidget *widget)
8039 {
8040         Compose *compose = (Compose *)data;
8041
8042         if (GTK_CHECK_MENU_ITEM(widget)->active) {
8043                 gtk_widget_show(compose->ruler_hbox);
8044                 prefs_common.show_ruler = TRUE;
8045         } else {
8046                 gtk_widget_hide(compose->ruler_hbox);
8047                 gtk_widget_queue_resize(compose->edit_vbox);
8048                 prefs_common.show_ruler = FALSE;
8049         }
8050 }
8051
8052 static void compose_attach_drag_received_cb (GtkWidget          *widget,
8053                                              GdkDragContext     *context,
8054                                              gint                x,
8055                                              gint                y,
8056                                              GtkSelectionData   *data,
8057                                              guint               info,
8058                                              guint               time,
8059                                              gpointer            user_data)
8060 {
8061         Compose *compose = (Compose *)user_data;
8062         GList *list, *tmp;
8063
8064         if (gdk_atom_name(data->type) && 
8065             !strcmp(gdk_atom_name(data->type), "text/uri-list")
8066             && gtk_drag_get_source_widget(context) != 
8067                 mainwindow_get_mainwindow()->summaryview->ctree) {
8068                 list = uri_list_extract_filenames((const gchar *)data->data);
8069                 for (tmp = list; tmp != NULL; tmp = tmp->next)
8070                         compose_attach_append
8071                                 (compose, (const gchar *)tmp->data,
8072                                  (const gchar *)tmp->data, NULL);
8073                 if (list) compose_changed_cb(NULL, compose);
8074                 list_free_strings(list);
8075                 g_list_free(list);
8076         } else if (gtk_drag_get_source_widget(context) 
8077                    == mainwindow_get_mainwindow()->summaryview->ctree) {
8078                 /* comes from our summaryview */
8079                 SummaryView * summaryview = NULL;
8080                 GSList * list = NULL, *cur = NULL;
8081                 
8082                 if (mainwindow_get_mainwindow())
8083                         summaryview = mainwindow_get_mainwindow()->summaryview;
8084                 
8085                 if (summaryview)
8086                         list = summary_get_selected_msg_list(summaryview);
8087                 
8088                 for (cur = list; cur; cur = cur->next) {
8089                         MsgInfo *msginfo = (MsgInfo *)cur->data;
8090                         gchar *file = NULL;
8091                         if (msginfo)
8092                                 file = procmsg_get_message_file_full(msginfo, 
8093                                         TRUE, TRUE);
8094                         if (file) {
8095                                 compose_attach_append(compose, (const gchar *)file, 
8096                                         (const gchar *)file, "message/rfc822");
8097                                 g_free(file);
8098                         }
8099                 }
8100                 g_slist_free(list);
8101         }
8102 }
8103
8104 static gboolean compose_drag_drop(GtkWidget *widget,
8105                                   GdkDragContext *drag_context,
8106                                   gint x, gint y,
8107                                   guint time, gpointer user_data)
8108 {
8109         /* not handling this signal makes compose_insert_drag_received_cb
8110          * called twice */
8111         return TRUE;                                     
8112 }
8113
8114 static void compose_insert_drag_received_cb (GtkWidget          *widget,
8115                                              GdkDragContext     *drag_context,
8116                                              gint                x,
8117                                              gint                y,
8118                                              GtkSelectionData   *data,
8119                                              guint               info,
8120                                              guint               time,
8121                                              gpointer            user_data)
8122 {
8123         Compose *compose = (Compose *)user_data;
8124         GList *list, *tmp;
8125
8126         /* strangely, testing data->type == gdk_atom_intern("text/uri-list", TRUE)
8127          * does not work */
8128         if (gdk_atom_name(data->type) && !strcmp(gdk_atom_name(data->type), "text/uri-list")) {
8129                 list = uri_list_extract_filenames((const gchar *)data->data);
8130                 for (tmp = list; tmp != NULL; tmp = tmp->next) {
8131                         compose_insert_file(compose, (const gchar *)tmp->data);
8132                 }
8133                 list_free_strings(list);
8134                 g_list_free(list);
8135                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8136                 return;
8137         } else {
8138 #if GTK_CHECK_VERSION(2, 8, 0)
8139                 /* do nothing, handled by GTK */
8140 #else
8141                 gchar *tmpfile = get_tmp_file();
8142                 str_write_to_file((const gchar *)data->data, tmpfile);
8143                 compose_insert_file(compose, tmpfile);
8144                 g_unlink(tmpfile);
8145                 g_free(tmpfile);
8146                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8147 #endif
8148                 return;
8149         }
8150         gtk_drag_finish(drag_context, TRUE, FALSE, time);
8151 }
8152
8153 static void compose_header_drag_received_cb (GtkWidget          *widget,
8154                                              GdkDragContext     *drag_context,
8155                                              gint                x,
8156                                              gint                y,
8157                                              GtkSelectionData   *data,
8158                                              guint               info,
8159                                              guint               time,
8160                                              gpointer            user_data)
8161 {
8162         GtkEditable *entry = (GtkEditable *)user_data;
8163         gchar *email = (gchar *)data->data;
8164
8165         /* strangely, testing data->type == gdk_atom_intern("text/plain", TRUE)
8166          * does not work */
8167
8168         if (!strncmp(email, "mailto:", strlen("mailto:"))) {
8169                 gchar *decoded=g_new(gchar, strlen(email));
8170                 int start = 0;
8171
8172                 email += strlen("mailto:");
8173                 decode_uri(decoded, email); /* will fit */
8174                 gtk_editable_delete_text(entry, 0, -1);
8175                 gtk_editable_insert_text(entry, decoded, strlen(decoded), &start);
8176                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8177                 g_free(decoded);
8178                 return;
8179         }
8180         gtk_drag_finish(drag_context, TRUE, FALSE, time);
8181 }
8182
8183 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
8184                                              GtkWidget *widget)
8185 {
8186         Compose *compose = (Compose *)data;
8187
8188         if (GTK_CHECK_MENU_ITEM(widget)->active)
8189                 compose->return_receipt = TRUE;
8190         else
8191                 compose->return_receipt = FALSE;
8192 }
8193
8194 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
8195                                              GtkWidget *widget)
8196 {
8197         Compose *compose = (Compose *)data;
8198
8199         if (GTK_CHECK_MENU_ITEM(widget)->active)
8200                 compose->remove_references = TRUE;
8201         else
8202                 compose->remove_references = FALSE;
8203 }
8204
8205 gboolean compose_headerentry_key_press_event_cb(GtkWidget *entry,
8206                                             GdkEventKey *event,
8207                                             ComposeHeaderEntry *headerentry)
8208 {
8209         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
8210             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
8211             !(event->state & GDK_MODIFIER_MASK) &&
8212             (event->keyval == GDK_BackSpace) &&
8213             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
8214                 gtk_container_remove
8215                         (GTK_CONTAINER(headerentry->compose->header_table),
8216                          headerentry->combo);
8217                 gtk_container_remove
8218                         (GTK_CONTAINER(headerentry->compose->header_table),
8219                          headerentry->entry);
8220                 headerentry->compose->header_list =
8221                         g_slist_remove(headerentry->compose->header_list,
8222                                        headerentry);
8223                 g_free(headerentry);
8224         } else  if (event->keyval == GDK_Tab) {
8225                 if (headerentry->compose->header_last == headerentry) {
8226                         /* Override default next focus, and give it to subject_entry
8227                          * instead of notebook tabs
8228                          */
8229                         g_signal_stop_emission_by_name(G_OBJECT(entry), "key-press-event"); 
8230                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
8231                         return TRUE;
8232                 }
8233         }
8234         return FALSE;
8235 }
8236
8237 gboolean compose_headerentry_changed_cb(GtkWidget *entry,
8238                                     ComposeHeaderEntry *headerentry)
8239 {
8240         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
8241                 headerentry->compose->header_list =
8242                         g_slist_append(headerentry->compose->header_list,
8243                                        headerentry);
8244                 
8245                 compose_create_header_entry(headerentry->compose);
8246                 g_signal_handlers_disconnect_matched
8247                         (G_OBJECT(entry), G_SIGNAL_MATCH_DATA,
8248                          0, 0, NULL, NULL, headerentry);
8249                 
8250                 /* Automatically scroll down */
8251                 compose_show_first_last_header(headerentry->compose, FALSE);
8252                 
8253         }
8254         return FALSE;
8255 }
8256
8257 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
8258 {
8259         GtkAdjustment *vadj;
8260
8261         g_return_if_fail(compose);
8262         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
8263         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
8264
8265         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
8266         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
8267 }
8268
8269 static void text_inserted(GtkTextBuffer *buffer, GtkTextIter *iter,
8270                           const gchar *text, gint len, Compose *compose)
8271 {
8272         gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data
8273                                 (G_OBJECT(compose->text), "paste_as_quotation"));
8274         GtkTextMark *mark;
8275
8276         g_return_if_fail(text != NULL);
8277
8278         g_signal_handlers_block_by_func(G_OBJECT(buffer),
8279                                         G_CALLBACK(text_inserted),
8280                                         compose);
8281         if (paste_as_quotation) {
8282                 gchar *new_text;
8283                 gchar *qmark;
8284
8285                 if (len < 0)
8286                         len = strlen(text);
8287
8288                 new_text = g_strndup(text, len);
8289                 if (prefs_common.quotemark && *prefs_common.quotemark)
8290                         qmark = prefs_common.quotemark;
8291                 else
8292                         qmark = "> ";
8293
8294                 mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8295                 gtk_text_buffer_place_cursor(buffer, iter);
8296
8297                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text, TRUE);
8298                 g_free(new_text);
8299                 g_object_set_data(G_OBJECT(compose->text), "paste_as_quotation",
8300                                   GINT_TO_POINTER(paste_as_quotation - 1));
8301                                   
8302                 gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8303                 gtk_text_buffer_place_cursor(buffer, iter);
8304         } else {
8305                 if (strcmp(text, "\n") || automatic_break
8306                 || gtk_text_iter_starts_line(iter))
8307                         gtk_text_buffer_insert(buffer, iter, text, len);
8308                 else {
8309                         debug_print("insert nowrap \\n\n");
8310                         gtk_text_buffer_insert_with_tags_by_name(buffer, 
8311                                 iter, text, len, "no_join", NULL);
8312                 }
8313         }
8314         
8315         mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8316         
8317         compose_beautify_paragraph(compose, iter, FALSE);
8318
8319         gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8320         gtk_text_buffer_delete_mark(buffer, mark);
8321
8322         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
8323                                           G_CALLBACK(text_inserted),
8324                                           compose);
8325         g_signal_stop_emission_by_name(G_OBJECT(buffer), "insert-text");
8326
8327         if (prefs_common.autosave && 
8328             gtk_text_buffer_get_char_count(buffer) % prefs_common.autosave_length == 0)
8329                 compose->draft_timeout_tag = gtk_timeout_add
8330                         (500, (GtkFunction) compose_defer_auto_save_draft, compose);
8331 }
8332 static gint compose_defer_auto_save_draft(Compose *compose)
8333 {
8334         compose->draft_timeout_tag = -1;
8335         compose_draft_cb((gpointer)compose, COMPOSE_AUTO_SAVE, NULL);
8336         return FALSE;
8337 }
8338
8339 #if USE_ASPELL
8340 static void compose_check_all(Compose *compose)
8341 {
8342         if (compose->gtkaspell)
8343                 gtkaspell_check_all(compose->gtkaspell);
8344 }
8345
8346 static void compose_highlight_all(Compose *compose)
8347 {
8348         if (compose->gtkaspell)
8349                 gtkaspell_highlight_all(compose->gtkaspell);
8350 }
8351
8352 static void compose_check_backwards(Compose *compose)
8353 {
8354         if (compose->gtkaspell) 
8355                 gtkaspell_check_backwards(compose->gtkaspell);
8356         else {
8357                 GtkItemFactory *ifactory;
8358                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8359                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8360                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8361         }
8362 }
8363
8364 static void compose_check_forwards_go(Compose *compose)
8365 {
8366         if (compose->gtkaspell) 
8367                 gtkaspell_check_forwards_go(compose->gtkaspell);
8368         else {
8369                 GtkItemFactory *ifactory;
8370                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8371                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8372                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8373         }
8374 }
8375 #endif
8376
8377 /*!
8378  *\brief        Guess originating forward account from MsgInfo and several 
8379  *              "common preference" settings. Return NULL if no guess. 
8380  */
8381 static PrefsAccount *compose_guess_forward_account_from_msginfo(MsgInfo *msginfo)
8382 {
8383         PrefsAccount *account = NULL;
8384         
8385         g_return_val_if_fail(msginfo, NULL);
8386         g_return_val_if_fail(msginfo->folder, NULL);
8387         g_return_val_if_fail(msginfo->folder->prefs, NULL);
8388
8389         if (msginfo->folder->prefs->enable_default_account)
8390                 account = account_find_from_id(msginfo->folder->prefs->default_account);
8391                 
8392         if (!account) 
8393                 account = msginfo->folder->folder->account;
8394                 
8395         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
8396                 gchar *to;
8397                 Xstrdup_a(to, msginfo->to, return NULL);
8398                 extract_address(to);
8399                 account = account_find_from_address(to);
8400         }
8401
8402         if (!account && prefs_common.forward_account_autosel) {
8403                 gchar cc[BUFFSIZE];
8404                 if (!procheader_get_header_from_msginfo
8405                         (msginfo, cc,sizeof cc , "CC:")) { /* Found a CC header */
8406                         extract_address(cc);
8407                         account = account_find_from_address(cc);
8408                 }
8409         }
8410         
8411         return account;
8412 }
8413
8414 static gboolean compose_close(Compose *compose)
8415 {
8416         gint x, y;
8417
8418         if (!g_mutex_trylock(compose->mutex)) {
8419                 /* we have to wait for the (possibly deferred by auto-save)
8420                  * drafting to be done, before destroying the compose under
8421                  * it. */
8422                 debug_print("waiting for drafting to finish...\n");
8423                 g_timeout_add (500, (GSourceFunc) compose_close, compose);
8424                 return FALSE;
8425         }
8426         g_return_val_if_fail(compose, FALSE);
8427         gtkut_widget_get_uposition(compose->window, &x, &y);
8428         prefs_common.compose_x = x;
8429         prefs_common.compose_y = y;
8430         g_mutex_unlock(compose->mutex);
8431         compose_destroy(compose);
8432         return FALSE;
8433 }
8434
8435 /**
8436  * Add entry field for each address in list.
8437  * \param compose     E-Mail composition object.
8438  * \param listAddress List of (formatted) E-Mail addresses.
8439  */
8440 static void compose_add_field_list( Compose *compose, GList *listAddress ) {
8441         GList *node;
8442         gchar *addr;
8443         node = listAddress;
8444         while( node ) {
8445                 addr = ( gchar * ) node->data;
8446                 compose_entry_append( compose, addr, COMPOSE_TO );
8447                 node = g_list_next( node );
8448         }
8449 }
8450
8451 void compose_reply_from_messageview(MessageView *msgview, GSList *msginfo_list, 
8452                                     guint action)
8453 {
8454         gchar *body;
8455         GSList *new_msglist = NULL;
8456         MsgInfo *tmp_msginfo = NULL;
8457         gboolean originally_enc = FALSE;
8458         Compose *compose = NULL;
8459
8460         g_return_if_fail(msgview != NULL);
8461
8462         g_return_if_fail(msginfo_list != NULL);
8463
8464         if (g_slist_length(msginfo_list) == 1) {
8465                 MimeInfo *mimeinfo = messageview_get_selected_mime_part(msgview);
8466                 MsgInfo *orig_msginfo = (MsgInfo *)msginfo_list->data;
8467                 
8468                 if (mimeinfo != NULL && mimeinfo->type == MIMETYPE_MESSAGE && 
8469                     !g_ascii_strcasecmp(mimeinfo->subtype, "rfc822")) {
8470                         tmp_msginfo = procmsg_msginfo_new_from_mimeinfo(
8471                                                 orig_msginfo, mimeinfo);
8472                         if (tmp_msginfo != NULL) {
8473                                 new_msglist = g_slist_append(NULL, tmp_msginfo);
8474                                 if (procmime_msginfo_is_encrypted(orig_msginfo)) {
8475                                         originally_enc = TRUE;
8476                                 }
8477                         } 
8478                 }
8479         }
8480
8481         body = messageview_get_selection(msgview);
8482
8483         if (new_msglist) {
8484                 compose = compose_reply_mode((ComposeMode)action, new_msglist, body);
8485                 procmsg_msginfo_free(tmp_msginfo);
8486                 g_slist_free(new_msglist);
8487         } else
8488                 compose = compose_reply_mode((ComposeMode)action, msginfo_list, body);
8489
8490         if (originally_enc) {
8491                 compose_force_encryption(compose, compose->account, FALSE);
8492         }
8493
8494         g_free(body);
8495 }
8496
8497 void compose_set_position(Compose *compose, gint pos)
8498 {
8499         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
8500
8501         gtkut_text_view_set_position(text, pos);
8502 }
8503
8504 gboolean compose_search_string(Compose *compose,
8505                                 const gchar *str, gboolean case_sens)
8506 {
8507         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
8508
8509         return gtkut_text_view_search_string(text, str, case_sens);
8510 }
8511
8512 gboolean compose_search_string_backward(Compose *compose,
8513                                 const gchar *str, gboolean case_sens)
8514 {
8515         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
8516
8517         return gtkut_text_view_search_string_backward(text, str, case_sens);
8518 }
8519
8520 /*
8521  * End of Source.
8522  */