File: textutil.c

package info (click to toggle)
gretl 2016d-1
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 48,620 kB
  • ctags: 22,779
  • sloc: ansic: 345,830; sh: 4,648; makefile: 2,712; xml: 570; perl: 364
file content (979 lines) | stat: -rw-r--r-- 23,390 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
/* 
 *  gretl -- Gnu Regression, Econometrics and Time-series Library
 *  Copyright (C) 2001 Allin Cottrell and Riccardo "Jack" Lucchetti
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

#include "gretl.h"
#include "dlgutils.h"
#include "varprint.h"
#include "textutil.h"
#include "textbuf.h"
#include "guiprint.h"
#include "model_table.h"
#include "clipboard.h"
#include "fileselect.h"
#include "texprint.h"
#include "system.h"
#include "winstack.h"

#if USE_GTKSOURCEVIEW_2
# include <gtksourceview/gtksourceiter.h>
#endif

struct search_replace {
    GtkWidget *w;          /* the dialog box */
    GtkWidget *f_entry;    /* Find string entry */
    GtkWidget *r_entry;    /* Replace string entry */
    GtkWidget *r_button;   /* Replace button */
    gchar *find;           /* the Find string */
    gchar *replace;        /* the Replace string */
    GtkTextBuffer *buf;    
    GtkTextView *view;
    GtkTextMark *mark;
    GtkTextIter iter;
};

static gboolean destroy_replacer (GtkWidget *widget, 
				  struct search_replace *s)
{
    GtkTextMark *mark;
    
    mark = gtk_text_buffer_get_mark(s->buf, "srmark");
    if (mark != NULL) {
	gtk_text_buffer_delete_mark(s->buf, mark);
    }
    
    g_free(s->find);
    g_free(s->replace);
    
    gtk_main_quit();
    return FALSE;
}

/* here we simply find (or not) the given string */

static void replace_find_callback (GtkWidget *widget, 
				   struct search_replace *s)
{
    GtkTextIter f_start, f_end;
    gboolean found;

    g_free(s->find);
    s->find = gtk_editable_get_chars(GTK_EDITABLE(s->f_entry), 0, -1);

    if (s->find == NULL || *s->find == '\0') {
	return;
    }

    gtk_text_buffer_get_iter_at_mark(s->buf, &s->iter, s->mark);

#if USE_GTKSOURCEVIEW_2    
    found = gtk_source_iter_forward_search(&s->iter,
					   s->find, 
					   0,
					   &f_start, 
					   &f_end,
					   NULL);
#else /* GTK 3 */
    found = gtk_text_iter_forward_search(&s->iter,
					 s->find, 
					 0,
					 &f_start, 
					 &f_end,
					 NULL);
#endif

    if (found) {
	gtk_text_buffer_select_range(s->buf, &f_start, &f_end);
	gtk_text_buffer_move_mark(s->buf, s->mark, &f_end);
	gtk_text_view_scroll_to_mark(s->view, s->mark, 0.0, FALSE, 0, 0);
    } else {
	notify_string_not_found(s->f_entry);
    }

    gtk_widget_set_sensitive(s->r_button, found);
}

static void update_search_strings (struct search_replace *s)
{
    g_free(s->find);
    g_free(s->replace);

    s->find = gtk_editable_get_chars(GTK_EDITABLE(s->f_entry), 0, -1);
    s->replace = gtk_editable_get_chars(GTK_EDITABLE(s->r_entry), 0, -1);
}

/* replace an occurrence of the Find string that has just been
   found, and selected */

static void replace_single_callback (GtkWidget *button, 
				     struct search_replace *s)
{
    GtkTextIter r_start, r_end;
    gchar *text;

    update_search_strings(s);

    if (s->find == NULL || s->replace == NULL || *s->find == '\0') {
	return;
    }

    if (!gtk_text_buffer_get_selection_bounds(s->buf, &r_start, &r_end)) {
	return;
    }

    text = gtk_text_buffer_get_text(s->buf, &r_start, &r_end, FALSE);

    if (strcmp(text, s->find) == 0) {
	gtk_text_buffer_begin_user_action(s->buf);
	gtk_text_buffer_delete(s->buf, &r_start, &r_end);
	gtk_text_buffer_insert(s->buf, &r_start, s->replace, -1);
	gtk_text_buffer_move_mark(s->buf, s->mark, &r_start);
	gtk_text_buffer_end_user_action(s->buf);
    }

    gtk_widget_set_sensitive(button, FALSE);
    g_free(text);
}

/* replace all occurrences of the Find string in the text
   buffer, or in the current selection if there is one
*/

static void replace_all_callback (GtkWidget *button, 
				  struct search_replace *s)
{
#if USE_GTKSOURCEVIEW_2
    GtkSourceSearchFlags search_flags;
#else
    GtkTextSearchFlags search_flags;
#endif
    GtkTextIter start, selstart, end;
    GtkTextIter r_start, r_end;
    GtkTextMark *mark;
    gint init_pos[2];
    gint replace_len;
    gboolean selected = FALSE;
    gboolean found = TRUE;
    gboolean do_brackets;
    int count = 0;

    update_search_strings(s);

    if (s->find == NULL || s->replace == NULL || *s->find == '\0') {
	return;
    }

    /* record the initial cursor position */
    mark = gtk_text_buffer_get_insert(s->buf);
    gtk_text_buffer_get_iter_at_mark(s->buf, &s->iter, mark);
    init_pos[0] = gtk_text_iter_get_line(&s->iter);
    init_pos[1] = gtk_text_iter_get_line_index(&s->iter);

    /* if there's a selection in place, respect it, otherwise work
       on the whole buffer */
    if (gtk_text_buffer_get_selection_bounds(s->buf, &start, &end)) {
	selected = TRUE;
    } else {
	gtk_text_buffer_get_start_iter(s->buf, &start);
	gtk_text_buffer_get_end_iter(s->buf, &end);
    } 

#if USE_GTKSOURCEVIEW_2
    search_flags = GTK_SOURCE_SEARCH_VISIBLE_ONLY | GTK_SOURCE_SEARCH_TEXT_ONLY;
#else
    search_flags = GTK_TEXT_SEARCH_VISIBLE_ONLY | GTK_TEXT_SEARCH_TEXT_ONLY;
#endif
    replace_len = strlen(s->replace);

    /* avoid spending time matching brackets */
    do_brackets = gtk_source_buffer_get_highlight_matching_brackets(GTK_SOURCE_BUFFER(s->buf));
    gtk_source_buffer_set_highlight_matching_brackets(GTK_SOURCE_BUFFER(s->buf), FALSE);

    gtk_text_buffer_begin_user_action(s->buf);

    do {
#if USE_GTKSOURCEVIEW_2
	found = gtk_source_iter_forward_search(&start,
					       s->find, 
					       search_flags,
					       &r_start, 
					       &r_end,
					       selected ? &end : NULL);
#else /* GTK 3 */
	found = gtk_text_iter_forward_search(&start,
					     s->find, 
					     search_flags,
					     &r_start, 
					     &r_end,
					     selected ? &end : NULL);
#endif
	if (found) {
	    count++;
	    gtk_text_buffer_delete(s->buf, &r_start, &r_end);
	    gtk_text_buffer_insert(s->buf, &r_start,
				   s->replace,
				   replace_len);
	    start = r_start;
	    if (selected) {
		gtk_text_buffer_get_selection_bounds(s->buf, 
						     &selstart, 
						     &end);
	    }
	}		
    } while (found);

#if 0
    fprintf(stderr, "replaced %d occurrences\n", count);
#endif

    gtk_text_buffer_end_user_action(s->buf);

    gtk_source_buffer_set_highlight_matching_brackets(GTK_SOURCE_BUFFER(s->buf),
						      do_brackets);

    /* put the cursor back where we found it */
    gtk_text_buffer_get_start_iter(s->buf, &s->iter);
    gtk_text_iter_set_line(&s->iter, init_pos[0]);
    gtk_text_iter_set_line_index(&s->iter, init_pos[1]);
    gtk_text_buffer_place_cursor(s->buf, &s->iter);
    gtk_text_buffer_move_mark(s->buf, s->mark, &s->iter);
}

static void replace_string_dialog (windata_t *vwin)
{
    GtkWidget *label, *button;
    GtkWidget *vbox, *abox;
    GtkWidget *table;
    struct search_replace sr_t;
    struct search_replace *s = &sr_t;

    s->find = s->replace = NULL;

    s->view = GTK_TEXT_VIEW(vwin->text);
    s->buf = gtk_text_view_get_buffer(s->view);
    gtk_text_buffer_get_start_iter(s->buf, &s->iter);
    s->mark = gtk_text_buffer_create_mark(s->buf, "srmark",
					  &s->iter, FALSE);

    s->w = gtk_dialog_new();
    gretl_dialog_set_destruction(s->w, vwin_toplevel(vwin));
    g_signal_connect(G_OBJECT(s->w), "destroy",
		     G_CALLBACK(destroy_replacer), s);

    gtk_window_set_title(GTK_WINDOW(s->w), _("gretl: replace"));
    gtk_container_set_border_width(GTK_CONTAINER(s->w), 5);

    table = gtk_table_new(2, 2, FALSE);

    /* 'Find' label and entry */
    label = gtk_label_new(_("Find:"));
    s->f_entry = gtk_entry_new();
    gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, 0, 0,
		     5, 5);
    gtk_table_attach(GTK_TABLE(table), s->f_entry, 1, 2, 0, 1, 
		     GTK_EXPAND | GTK_FILL, 0, 5, 5);

    /* 'Replace' label and entry */
    label = gtk_label_new(_("Replace with:"));
    s->r_entry = gtk_entry_new();
    gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2, 0, 0,
		     5, 5);
    gtk_table_attach(GTK_TABLE(table), s->r_entry, 1, 2, 1, 2,
		     GTK_EXPAND | GTK_FILL, 0, 5, 5);

    vbox = gtk_dialog_get_content_area(GTK_DIALOG(s->w));
    gtk_box_pack_start(GTK_BOX(vbox), table, TRUE, TRUE, 5);

    abox = gtk_dialog_get_action_area(GTK_DIALOG(s->w));

    gtk_box_set_spacing(GTK_BOX(abox), 15);
    gtk_box_set_homogeneous(GTK_BOX(abox), TRUE);
    gtk_window_set_position(GTK_WINDOW(s->w), GTK_WIN_POS_MOUSE);

    /* Close button */
    button = gtk_button_new_from_stock(GTK_STOCK_CLOSE);
    gtk_widget_set_can_default(button, TRUE);
    gtk_box_pack_start(GTK_BOX(abox), button, TRUE, TRUE, 0);
    g_signal_connect(G_OBJECT(button), "clicked",
		     G_CALLBACK(delete_widget), s->w);

    /* Replace All button */
    button = gtk_button_new_with_mnemonic(_("Replace _All"));
    gtk_widget_set_can_default(button, TRUE);
    gtk_box_pack_start(GTK_BOX(abox), button, TRUE, TRUE, 0);
    g_signal_connect(G_OBJECT(button), "clicked",
		     G_CALLBACK(replace_all_callback), s);

    /* Replace button */
    button = gtk_button_new_with_mnemonic(_("_Replace"));
    gtk_widget_set_can_default(button, TRUE);
    gtk_box_pack_start(GTK_BOX(abox), button, TRUE, TRUE, 0);
    g_signal_connect(G_OBJECT(button), "clicked",
		     G_CALLBACK(replace_single_callback), s);
    gtk_widget_set_sensitive(button, FALSE);
    s->r_button = button;

    /* Find button -- make this the default */
    button = gtk_button_new_from_stock(GTK_STOCK_FIND);
    gtk_widget_set_can_default(button, TRUE);
    gtk_box_pack_start(GTK_BOX(abox), button, TRUE, TRUE, 0);
    g_signal_connect(G_OBJECT(button), "clicked",
		     G_CALLBACK(replace_find_callback), s);
    gtk_widget_grab_default(button);

    gtk_widget_grab_focus(s->f_entry);
    gtk_widget_show_all(s->w);

    /* we need to block so that the search/replace
       struct (above) doesn't drop out of scope */
    gtk_main();
}

void text_replace (GtkWidget *w, windata_t *vwin)
{
    replace_string_dialog(vwin);
}

static int prep_prn_for_file_save (PRN *prn, int fmt)
{
    const char *orig = gretl_print_get_buffer(prn);
    char *modbuf;
    int err;
    
    err = maybe_post_process_buffer(orig, fmt, W_SAVE, &modbuf);

    if (!err && modbuf != NULL) {
	gretl_print_replace_buffer(prn, modbuf);
    }

    return err;
}

static int special_text_handler (windata_t *vwin, guint fmt, int what)
{
    int cmd = vwin->role;
    PRN *prn = NULL;
    int err = 0;

    if (bufopen(&prn)) {
	return 1;
    }

    gretl_print_set_format(prn, fmt);

    if (cmd == SUMMARY) {
	Summary *summ = (Summary *) vwin->data;

	special_print_summary(summ, dataset, prn);
    } else if (cmd == CORR || cmd == COVAR) {
	VMatrix *corr = (VMatrix *) vwin->data;

	special_print_vmatrix(corr, dataset, prn);
    } else if (cmd == AFR) {
	FITRESID *fr = (FITRESID *) vwin->data;

	special_print_fit_resid(fr, dataset, prn);
    } else if (cmd == FCAST) {
	FITRESID *fr = (FITRESID *) vwin->data;

	special_print_forecast(fr, dataset, prn);
    } else if (cmd == COEFFINT) {
	CoeffIntervals *cf = (CoeffIntervals *) vwin->data;

	special_print_confints(cf, prn);
    } else if (cmd == VIEW_MODEL) { 
	MODEL *pmod = (MODEL *) vwin->data;

	if (pmod->errcode) { 
	    err = pmod->errcode;
	} else if (tex_format(prn)) {
	    err = tex_print_model(pmod, dataset, 
				  get_tex_eqn_opt(), 
				  prn);
	} else {
	    /* RTF or CSV */
	    err = printmodel(pmod, dataset, OPT_NONE, prn);
	}
    } else if (cmd == VAR || cmd == VECM) {
	GRETL_VAR *var = (GRETL_VAR *) vwin->data;

	err = gretl_VAR_print(var, dataset, OPT_NONE, prn);
    } else if (cmd == VAR_IRF || cmd == VAR_DECOMP) {
	windata_t *parent = vwin->gretl_parent;

	if (parent == NULL) {
	    err = E_DATA;
	} else {
	    GRETL_VAR *var = (GRETL_VAR *) parent->data;
	    /* here active_var records preferred horizon */
	    int h = vwin->active_var;

	    if (cmd == VAR_IRF) {
		gretl_VAR_print_all_impulse_responses(var, dataset, h, prn);
	    } else {
		gretl_VAR_print_all_fcast_decomps(var, dataset, h, prn);
	    }
	}
    } else if (cmd == SYSTEM) {
	equation_system *sys = (equation_system *) vwin->data;

	err = gretl_system_print(sys, dataset, OPT_NONE, prn);
    } else if (cmd == VIEW_MODELTABLE) {
	err = special_print_model_table(prn);
    } 

    if (!err && what == W_SAVE) {
	err = prep_prn_for_file_save(prn, fmt);
    }

    if (err) {
	gui_errmsg(err);
    } else {
	if (what == W_PREVIEW) {
	    /* TeX only: there's no RTF preview option */
	    view_latex(prn);
	} else if (what == W_COPY) {
	    prn_to_clipboard(prn, fmt);
	} else if (what == W_SAVE) {
	    int action;

	    if (fmt & GRETL_FORMAT_TEX) {
		action = SAVE_TEX;
	    } else if (fmt & GRETL_FORMAT_CSV) {
		action = EXPORT_CSV;
	    } else {
		action = SAVE_RTF;
	    }

	    file_selector_with_parent(action, FSEL_DATA_PRN, 
				      prn, vwin_toplevel(vwin));
	}
    }

    gretl_print_destroy(prn);

    return err;
}

void window_tex_callback (GtkWidget *w, windata_t *vwin)
{
    const char *opts[] = {
	N_("View"),
	N_("Copy"),
	N_("Save")
    };
    int opt;

    if (vwin->role == VAR_IRF || vwin->role == VAR_DECOMP) {
	if (vwin->gretl_parent == NULL) {
	    warnbox(_("Not available"));
	    gtk_widget_set_sensitive(w, FALSE);
	    return;
	}
    }

    opt = radio_dialog("gretl: LaTeX", NULL, opts, 3, 0, 0,
		       vwin_toplevel(vwin));

    if (opt >= 0) {
	int fmt = GRETL_FORMAT_TEX;

	if (vwin->role == VIEW_MODELTABLE) {
	    fmt |= GRETL_FORMAT_MODELTAB;

	    if (model_table_landscape()) {
		fmt |= GRETL_FORMAT_LANDSCAPE;
	    }
	}

	special_text_handler(vwin, fmt, opt);
    }
}

static int tex_format_code (GtkAction *action)
{
    const gchar *s = gtk_action_get_name(action);
    int fmt = GRETL_FORMAT_TEX;

    if (strstr(s, "Eqn")) {
	fmt |= GRETL_FORMAT_EQN;
    }

    return fmt;
}

void model_tex_view (GtkAction *action, gpointer data)
{
    windata_t *vwin = (windata_t *) data;
    int fmt = tex_format_code(action);

    special_text_handler(vwin, fmt, W_PREVIEW);
}

void model_tex_save (GtkAction *action, gpointer data)
{
    windata_t *vwin = (windata_t *) data;
    int fmt = tex_format_code(action);

    special_text_handler(vwin, fmt, W_SAVE);
}

void model_tex_copy (GtkAction *action, gpointer data) 
{
    windata_t *vwin = (windata_t *) data;
    int fmt = tex_format_code(action);

    special_text_handler(vwin, fmt, W_COPY);
}

static gchar *text_window_get_copy_buf (windata_t *vwin, int select)
{
    gchar *cpy = NULL;

    if (select) {
	GtkTextBuffer *buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(vwin->text));
	GtkTextIter start, end;

	if (gtk_text_buffer_get_selection_bounds(buf, &start, &end)) {
	    cpy = gtk_text_buffer_get_text(buf, &start, &end, FALSE);
	}
    } else {	
	cpy = textview_get_text(vwin->text); 
    }

    return cpy;
}

int multiple_formats_ok (windata_t *vwin)
{
    int r = vwin->role;

    if (r == SUMMARY || r == VAR_SUMMARY || 
	r == ALL_SUMMARY || r == AFR || 
	r == CORR || r == ALL_CORR || 
	r == FCAST || r == COEFFINT || 
	r == COVAR || r == VIEW_MODELTABLE || 
	r == VAR || r == VECM || 
	r == VAR_IRF || r == VAR_DECOMP) {
	return 1;
    } else if (r == VIEW_MODEL) {
	MODEL *pmod = (MODEL *) vwin->data;

	return !RQ_SPECIAL_MODEL(pmod);
    } else {
	return 0;
    }
}

static PRN *make_prn_for_buf (gchar *buf, int fmt, int action,
			      int *err)
{
    char *modbuf = NULL;
    PRN *prn = NULL;

    if (action == W_SAVE) {
	*err = maybe_post_process_buffer(buf, fmt, action, &modbuf);
    }

    if (*err) {
	g_free(buf);
    } else {
	if (modbuf != NULL) {
	    prn = gretl_print_new_with_buffer(modbuf);
	    g_free(buf);
	} else {
	    prn = gretl_print_new_with_buffer(buf);
	}
	if (prn == NULL) {
	    *err = E_ALLOC;
	}
    }

    return prn;
}

/* copying text from gretl windows */

#define SPECIAL_FORMAT(f) ((f & GRETL_FORMAT_TEX) || \
                           (f & GRETL_FORMAT_RTF)) 

static void window_copy_or_save (windata_t *vwin, guint fmt, int action) 
{
    gchar *buf = NULL;

    if (vwin->role == VIEW_MODEL && fmt == GRETL_FORMAT_CSV) {
	special_text_handler(vwin, fmt, action);
    } else if (multiple_formats_ok(vwin) && SPECIAL_FORMAT(fmt)) {
	special_text_handler(vwin, fmt, action);
    } else if (fmt == GRETL_FORMAT_CSV || fmt == GRETL_FORMAT_TAB ||
	       fmt == GRETL_FORMAT_RTF) {
	copy_vars_formatted(vwin, fmt, action);
    } else if (fmt == GRETL_FORMAT_TXT || fmt == GRETL_FORMAT_RTF_TXT) {
	buf = text_window_get_copy_buf(vwin, 0);
    } else if (fmt == GRETL_FORMAT_SELECTION) {
	buf = text_window_get_copy_buf(vwin, 1);
	fmt = GRETL_FORMAT_TXT;
    }

    if (buf != NULL) {
	/* handle the last two cases above */
	PRN *prn;
	int err = 0;

	prn = make_prn_for_buf(buf, fmt, action, &err);

	if (!err) {
	    if (action == W_COPY) {
		prn_to_clipboard(prn, fmt);
	    } else {
		/* saving to file */
		int fcode = (fmt == GRETL_FORMAT_RTF_TXT)? 
		    SAVE_RTF : SAVE_OUTPUT;

		file_selector_with_parent(fcode, FSEL_DATA_PRN, prn, 
					  vwin_toplevel(vwin));
	    }
	    gretl_print_destroy(prn);
	}
    }	
}

void window_copy (windata_t *vwin, guint fmt) 
{
    window_copy_or_save(vwin, fmt, W_COPY);
}

void window_save (windata_t *vwin, guint fmt) 
{
    window_copy_or_save(vwin, fmt, W_SAVE);
}

/* "native" printing from gretl windows */

void window_print (GtkAction *action, windata_t *vwin) 
{
    gchar *buf, *selbuf = NULL;
    const char *filename = NULL;
    GtkTextBuffer *tbuf;
    GtkTextIter start, end;

    tbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(vwin->text));
    buf = textview_get_text(vwin->text);

    if (gtk_text_buffer_get_selection_bounds(tbuf, &start, &end)) {
	selbuf = gtk_text_buffer_get_text(tbuf, &start, &end, FALSE);
    }

    if (vwin->role == EDIT_SCRIPT ||
	vwin->role == VIEW_SCRIPT) {
	const char *p = strrchr(vwin->fname, SLASH);
	
	if (p != NULL) {
	    filename = p + 1;
	} else {
	    filename = vwin->fname;
	}
    }

    print_window_content(buf, selbuf, filename, vwin);

    g_free(buf);
    g_free(selbuf);
}

#define U_MINUS(u,i) (u[i] == 0xE2 && u[i+1] == 0x88 && u[i+2] == 0x92)

/* check @s for Unicode minus signs (U+2212), and if any are found do an
   in-place replacement with ASCII dashes
*/

char *strip_unicode_minus (char *s)
{
    unsigned char *u = (unsigned char *) s;
    int i, n = strlen(s);
    int got_minus = 0;

    for (i=0; i<n-3; i++) {
	if (U_MINUS(u, i)) {
	    got_minus = 1;
	    break;
	}
    }

    if (got_minus) {
	char *tmp = calloc(n, 1);

	if (tmp != NULL) {
	    int j = 0;

	    for (i=0; i<n; i++) {
		if (i < n - 3 && U_MINUS(u, i)) {
		    tmp[j++] = '-';
		    i += 2;
		} else {
		    tmp[j++] = u[i];
		}
	    }
	    strcpy(s, tmp);
	    free(tmp);
	} 
    }

    return s;
}

int has_unicode_minus (const unsigned char *s)
{
    int i, n = strlen((const char *) s);
    int has_minus = 0;

    for (i=0; i<n-3; i++) {
	if (U_MINUS(s, i)) {
	    has_minus = 1;
	    break;
	}
    }

    return has_minus;
}

/* print buf to file, trying to ensure it's not messed up */

void system_print_buf (const gchar *buf, FILE *fp)
{
    const char *p = buf;
    int cbak = 0;

    while (*p) {
	if (*p == '\r') {
	    if (*(p+1) != '\n') {
		fputc('\n', fp);
	    } 
	} else {
	    fputc(*p, fp);
	}
	cbak = *p;
	p++;
    }

    /* ensure file ends with newline */
    if (cbak != '\n') {
	fputc('\n', fp);
    }
}

/* Convert a buffer to DOS/Windows text format, optionally
   adding minimal RTF formatting. This function does not
   take charge of text re-encoding, it just handles CR + LF
   endings and (optional) RTF monospaced font spec.
*/

static char *dosify_buffer (const char *buf, int format)
{
#ifdef G_OS_WIN32 /* alt font not working with lowriter */
    const char *rtf_preamble = "{\\rtf1\r\n"
	"{\\fonttbl{\\f0\\fnil\\fprq1\\fcharset1 Consolas{\\*\\falt Courier New};}}\r\n"
	"\\f0\\fs18\r\n";
#else    
    const char *rtf_preamble = "{\\rtf1\r\n"
	"{\\fonttbl{\\f0\\fnil\\fprq1\\fcharset1 Courier New;}}\r\n"
	"\\f0\\fs18\r\n";
#endif    
    int extra = 0, nlines = 0;
    int add_rtf = 0;
    char *targ, *q;
    const char *p;

    if (buf == NULL || *buf == '\0') {
	return NULL;
    }

    if (format == GRETL_FORMAT_RTF_TXT) {
	add_rtf = 1;
    }

    p = buf;
    while (*p) {
	if (*p++ == '\n') nlines++;
    }
    extra = nlines + 1;

    if (add_rtf) {
	extra *= 5;
	extra += strlen(rtf_preamble) + 5;
    }

    targ = malloc(strlen(buf) + extra);
    if (targ == NULL) {
	return NULL;
    }

    if (add_rtf) {
	strcpy(targ, rtf_preamble);
	q = targ + strlen(targ);
    } else {
	q = targ;
    }

    p = buf;

    while (*p) {
	int pplus = 1;
	int nl = 0;

	if (*p == '\r' && *(p+1) == '\n') {
	    nl = 1; pplus = 2;
	} else if (*p == '\n') {
	    nl = 1;
	}

	if (nl) {
	    if (add_rtf) {
		*q++ = '\\';
		*q++ = 'p';
		*q++ = 'a';
		*q++ = 'r';
	    }
	    *q++ = '\r';
	    *q++ = '\n';
	} else {
	    *q++ = *p;
	}

	p += pplus;
    }
 
    *q = '\0';

    if (add_rtf) {
	strcat(q, "}\r\n");
    }

    return targ;
}

#ifdef G_OS_WIN32

#define plain_text(f) (f & (GRETL_FORMAT_TXT | GRETL_FORMAT_CSV | GRETL_FORMAT_TAB))

static int want_bom (int fmt, int action)
{
    /* Note sure about this, but for now if we're saving 
       "plain text" to file in UTF-8, we'll leave it in
       UTF-8 and prepend the UTF-8 BOM.
    */
    if (action == W_SAVE && fmt == GRETL_FORMAT_TXT) {
	return 1;
    } else {
	return 0;
    }
}

static char *prepend_bom (const char *orig)
{
    char *buf = malloc(strlen(orig) + 4);

    if (buf != NULL) {
	buf[0] = 0xEF;
	buf[1] = 0xBB;
	buf[2] = 0xBF;
	buf[3] = 0;
	strcat(buf, orig);
    }
 
    return buf;
}

#endif

int maybe_post_process_buffer (const char *buf, int fmt, 
			       int action, char **modbuf)
{
    int rtf_output = 0;
    int utf8_coded = 0;
    char *trbuf = NULL;
    char *final = NULL;
    int err = 0;

    if (fmt & (GRETL_FORMAT_RTF | GRETL_FORMAT_RTF_TXT)) {
	rtf_output = 1;
    }

    if (string_is_utf8((const unsigned char *) buf)) {
	utf8_coded = 1;
    }

    if (rtf_output) {
	/* When writing RTF, recode if required and ensure
	   CR + LF.
	*/
	if (utf8_coded) {
	    trbuf = utf8_to_rtf(buf);
	    if (trbuf == NULL) {
		err = E_ALLOC;
	    }
	}
	if (!err) {
	    if (trbuf != NULL) {
		final = dosify_buffer(trbuf, fmt);
	    } else {
		final = dosify_buffer(buf, fmt);
	    }
	    if (final == NULL) {
		err = E_ALLOC;
	    }
	}
	goto finish;
    }

#ifdef G_OS_WIN32
    if (plain_text(fmt)) {
	if (utf8_coded && want_bom(fmt, action)) {
	    trbuf = prepend_bom(buf);
	    if (trbuf == NULL) {
		err = E_ALLOC;
	    }	    
	}
	if (!err && action == W_COPY) {
	    if (trbuf != NULL) {
		final = dosify_buffer(trbuf, fmt);
	    } else {
		final = dosify_buffer(buf, fmt);
	    }
	    if (final == NULL) {
		err = E_ALLOC;
	    }
	} else {
	    final = trbuf;
	}
    }
#endif

 finish:

    if (trbuf != NULL && trbuf != final) {
	free(trbuf);
    }

    *modbuf = final;
	
    return err;
}