-
Notifications
You must be signed in to change notification settings - Fork 586
/
document.c
2578 lines (2125 loc) · 71.9 KB
/
document.c
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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* document.c - this file is part of Geany, a fast and lightweight IDE
*
* Copyright 2005-2008 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
* Copyright 2006-2008 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* $Id$
*/
/*
* Document related actions: new, save, open, etc.
* Also Scintilla search actions.
*/
#include "geany.h"
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#include <ctype.h>
#include <stdlib.h>
/* gstdio.h also includes sys/stat.h */
#include <glib/gstdio.h>
#include "document.h"
#include "documentprivate.h"
#include "filetypes.h"
#include "support.h"
#include "sciwrappers.h"
#include "editor.h"
#include "dialogs.h"
#include "msgwindow.h"
#include "templates.h"
#include "treeviews.h"
#include "ui_utils.h"
#include "utils.h"
#include "encodings.h"
#include "notebook.h"
#include "main.h"
#include "vte.h"
#include "build.h"
#include "symbols.h"
#include "geanyobject.h"
#include "highlighting.h"
#include "navqueue.h"
#include "win32.h"
#include "search.h"
GeanyFilePrefs file_prefs;
GPtrArray *documents_array;
/* an undo action, also used for redo actions */
typedef struct
{
GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
guint type; /* to identify the action */
gpointer *data; /* the old value (before the change), in case of a redo action
* it contains the new value */
} undo_action;
static void document_undo_clear(GeanyDocument *doc);
static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
/* ignore the case of filenames and paths under WIN32, causes errors if not */
#ifdef G_OS_WIN32
#define filenamecmp(a,b) strcasecmp((a), (b))
#else
#define filenamecmp(a,b) strcmp((a), (b))
#endif
/**
* Find and retrieve the index of the given filename in the %document list.
*
* @param realname The filename to search, which should be identical to the
* string returned by @c tm_get_real_path().
*
* @return The matching document, or NULL.
* @note This is only really useful when passing a @c TMWorkObject::file_name.
* @see document_find_by_filename().
**/
GeanyDocument* document_find_by_real_path(const gchar *realname)
{
guint i;
if (! realname)
return NULL; /* file doesn't exist on disk */
for (i = 0; i < documents_array->len; i++)
{
GeanyDocument *doc = documents[i];
if (! documents[i]->is_valid || ! doc->real_path) continue;
if (filenamecmp(realname, doc->real_path) == 0)
{
return doc;
}
}
return NULL;
}
/* dereference symlinks, /../ junk in path and return locale encoding */
static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
{
gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
gchar *realname = tm_get_real_path(locale_name);
g_free(locale_name);
return realname;
}
/**
* Find and retrieve the index of the given filename in the %document list.
* This matches either an exact GeanyDocument::file_name string, or variant
* filenames with relative elements in the path (e.g. @c "/dir/..//name" will
* match @c "/name").
*
* @param utf8_filename The filename to search (in UTF-8 encoding).
*
* @return The matching document, or NULL.
* @see document_find_by_real_path().
**/
GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
{
guint i;
GeanyDocument *doc;
gchar *realname;
if (! utf8_filename)
return NULL;
/* First search GeanyDocument::file_name, so we can find documents with a
* filename set but not saved on disk, like vcdiff produces */
for (i = 0; i < documents_array->len; i++)
{
doc = documents[i];
if (! documents[i]->is_valid || doc->file_name == NULL) continue;
if (filenamecmp(utf8_filename, doc->file_name) == 0)
{
return doc;
}
}
/* Now try matching based on the realpath(), which is unique per file on disk */
realname = get_real_path_from_utf8(utf8_filename);
doc = document_find_by_real_path(realname);
g_free(realname);
return doc;
}
/* returns the document which has sci, or NULL. */
GeanyDocument *document_find_by_sci(ScintillaObject *sci)
{
guint i;
if (sci == NULL)
return NULL;
for (i = 0; i < documents_array->len; i++)
{
if (documents[i]->is_valid && documents[i]->editor->scintilla == sci)
return documents[i];
}
return NULL;
}
/* returns the index of the notebook page from the document index */
gint document_get_notebook_page(GeanyDocument *doc)
{
if (doc == NULL)
return -1;
return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
GTK_WIDGET(doc->editor->scintilla));
}
/**
* Find and retrieve the index of the given notebook page @a page_num in the %document list.
*
* @param page_num The notebook page number to search.
*
* @return The corresponding document for the given notebook page, or NULL.
**/
GeanyDocument *document_get_from_page(guint page_num)
{
ScintillaObject *sci;
if (page_num >= documents_array->len)
return NULL;
sci = (ScintillaObject*)gtk_notebook_get_nth_page(
GTK_NOTEBOOK(main_widgets.notebook), page_num);
return document_find_by_sci(sci);
}
/**
* Find and retrieve the current %document.
*
* @return A pointer to the current %document or @c NULL if there are no opened documents.
**/
GeanyDocument *document_get_current(void)
{
gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
if (cur_page == -1)
return NULL;
else
{
ScintillaObject *sci = (ScintillaObject*)
gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
return document_find_by_sci(sci);
}
}
void document_init_doclist()
{
documents_array = g_ptr_array_new();
}
void document_finalize()
{
g_ptr_array_free(documents_array, TRUE);
}
/**
* Update the tab labels, the status bar, the window title and some save-sensitive buttons
* according to the document's save state.
* This is called by Geany mostly when opening or saving files.
*
* @param doc The document to use.
* @param changed Whether the document state should indicate changes have been made.
**/
void document_set_text_changed(GeanyDocument *doc, gboolean changed)
{
if (doc == NULL)
return;
doc->changed = changed;
if (! main_status.quitting)
{
ui_update_tab_status(doc);
ui_save_buttons_toggle(changed);
ui_set_window_title(doc);
ui_update_statusbar(doc, -1);
}
}
/* Apply just the prefs that can change in the Preferences dialog */
void document_apply_update_prefs(GeanyDocument *doc)
{
ScintillaObject *sci;
g_return_if_fail(doc != NULL);
sci = doc->editor->scintilla;
sci_set_mark_long_lines(sci, editor_prefs.long_line_type,
editor_prefs.long_line_column, editor_prefs.long_line_color);
sci_set_tab_width(sci, editor_prefs.tab_width);
sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
sci_set_indentation_guides(sci, editor_prefs.show_indent_guide);
sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
sci_set_visible_eols(sci, editor_prefs.show_line_endings);
sci_set_folding_margin_visible(sci, editor_prefs.folding);
doc->editor->auto_indent = (editor_prefs.indent_mode != INDENT_NONE);
sci_assign_cmdkey(sci, SCK_HOME,
editor_prefs.smart_home_key ? SCI_VCHOMEWRAP : SCI_HOMEWRAP);
sci_assign_cmdkey(sci, SCK_END, SCI_LINEENDWRAP);
}
/* Sets is_valid to FALSE and initializes some members to NULL, to mark it uninitialized.
* The flag is_valid is set to TRUE in document_create(). */
static void init_doc_struct(GeanyDocument *new_doc)
{
Document *full_doc = DOCUMENT(new_doc);
GeanyEditor *editor = new_doc->editor;
memset(full_doc, 0, sizeof(Document));
new_doc->is_valid = FALSE;
new_doc->has_tags = FALSE;
editor->auto_indent = (editor_prefs.indent_mode != INDENT_NONE);
editor->line_wrapping = editor_prefs.line_wrapping;
new_doc->readonly = FALSE;
new_doc->file_name = NULL;
new_doc->file_type = NULL;
new_doc->tm_file = NULL;
new_doc->encoding = NULL;
new_doc->has_bom = FALSE;
new_doc->editor->scintilla = NULL;
editor->scroll_percent = -1.0F;
editor->line_breaking = FALSE;
new_doc->mtime = 0;
new_doc->changed = FALSE;
new_doc->last_check = time(NULL);
new_doc->real_path = NULL;
full_doc->tag_store = NULL;
full_doc->tag_tree = NULL;
full_doc->saved_encoding.encoding = NULL;
full_doc->saved_encoding.has_bom = FALSE;
full_doc->undo_actions = NULL;
full_doc->redo_actions = NULL;
}
/* returns the next free place in the document list,
* or -1 if the documents_array is full */
static gint document_get_new_idx(void)
{
guint i;
for (i = 0; i < documents_array->len; i++)
{
if (documents[i]->editor->scintilla == NULL)
{
return (gint) i;
}
}
return -1;
}
static void queue_colourise(GeanyDocument *doc)
{
/* Colourise the editor before it is next drawn */
DOCUMENT(doc)->colourise_needed = TRUE;
/* If the editor doesn't need drawing (e.g. after saving the current
* document), we need to force a redraw, so the expose event is triggered.
* This ensures we don't start colourising before all documents are opened/saved,
* only once the editor is drawn. */
gtk_widget_queue_draw(GTK_WIDGET(doc->editor->scintilla));
}
/* Creates a new document and editor, adding a tab in the notebook.
* @return The index of the created document */
static GeanyDocument *document_create(const gchar *utf8_filename)
{
PangoFontDescription *pfd;
gchar *fname;
GeanyDocument *this;
gint new_idx;
gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
if (cur_pages == 1)
{
GeanyDocument *doc = document_get_current();
/* remove the empty document and open a new one */
if (doc != NULL && doc->file_name == NULL && ! doc->changed)
document_remove_page(0);
}
new_idx = document_get_new_idx();
if (new_idx == -1) /* expand the array, no free places */
{
Document *new_doc = g_new0(Document, 1);
new_idx = documents_array->len;
g_ptr_array_add(documents_array, new_doc);
}
this = documents[new_idx];
init_doc_struct(this); /* initialize default document settings */
this->index = new_idx;
this->file_name = g_strdup(utf8_filename);
this->editor->scintilla = editor_create_new_sci(this);
document_apply_update_prefs(this);
pfd = pango_font_description_from_string(interface_prefs.editor_font);
fname = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
editor_set_font(this, fname, pango_font_description_get_size(pfd) / PANGO_SCALE);
pango_font_description_free(pfd);
g_free(fname);
treeviews_openfiles_add(this); /* sets this->iter */
notebook_new_tab(this);
/* select document in sidebar */
{
GtkTreeSelection *sel;
sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
gtk_tree_selection_select_iter(sel, &DOCUMENT(this)->iter);
}
ui_document_buttons_update();
this->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
return this;
}
/**
* Close the given document.
*
* @param doc The document to remove.
*
* @return @a TRUE if the document was actually removed or @a FALSE otherwise.
**/
gboolean document_close(GeanyDocument *doc)
{
g_return_val_if_fail(doc, FALSE);
return document_remove_page(document_get_notebook_page(doc));
}
/**
* Remove the given notebook tab at @a page_num and clear all related information
* in the document list.
*
* @param page_num The notebook page number to remove.
*
* @return @a TRUE if the document was actually removed or @a FALSE otherwise.
**/
gboolean document_remove_page(guint page_num)
{
GeanyDocument *doc = document_get_from_page(page_num);
if (doc != NULL)
{
Document *fdoc = DOCUMENT(doc);
if (doc->changed && ! dialogs_show_unsaved_file(doc))
{
return FALSE;
}
/* Checking real_path makes it likely the file exists on disk */
if (! main_status.closing_all && doc->real_path != NULL)
ui_add_recent_file(doc->file_name);
notebook_remove_page(page_num);
treeviews_remove_document(doc);
navqueue_remove_file(doc->file_name);
msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
g_free(doc->encoding);
g_free(fdoc->saved_encoding.encoding);
g_free(doc->file_name);
g_free(doc->real_path);
tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
doc->is_valid = FALSE;
doc->editor->scintilla = NULL;
doc->file_name = NULL;
doc->real_path = NULL;
doc->file_type = NULL;
doc->encoding = NULL;
doc->has_bom = FALSE;
doc->tm_file = NULL;
doc->editor->scroll_percent = -1.0F;
document_undo_clear(doc);
if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
{
treeviews_update_tag_list(NULL, FALSE);
/*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
ui_set_window_title(NULL);
ui_save_buttons_toggle(FALSE);
ui_document_buttons_update();
build_menu_update(NULL);
}
return TRUE;
}
geany_debug("Error: page_num: %d", page_num);
return FALSE;
}
/* used to keep a record of the unchanged document state encoding */
static void store_saved_encoding(GeanyDocument *doc)
{
Document *fdoc = DOCUMENT(doc);
g_free(fdoc->saved_encoding.encoding);
fdoc->saved_encoding.encoding = g_strdup(doc->encoding);
fdoc->saved_encoding.has_bom = doc->has_bom;
}
/* Opens a new empty document only if there are no other documents open */
GeanyDocument *document_new_file_if_non_open()
{
if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
return document_new_file(NULL, NULL, NULL);
return NULL;
}
/**
* Creates a new %document.
* After all, the "document-new" signal is emitted for plugins.
*
* @param filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
* @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
* @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
*
* @return The new document.
**/
GeanyDocument *document_new_file(const gchar *filename, GeanyFiletype *ft, const gchar *text)
{
GeanyDocument *doc = document_create(filename);
g_assert(doc != NULL);
sci_set_undo_collection(doc->editor->scintilla, FALSE); /* avoid creation of an undo action */
if (text)
sci_set_text(doc->editor->scintilla, text);
else
sci_clear_all(doc->editor->scintilla);
sci_set_eol_mode(doc->editor->scintilla, file_prefs.default_eol_character);
/* convert the eol chars in the template text in case they are different from
* from file_prefs.default_eol */
if (text != NULL)
sci_convert_eols(doc->editor->scintilla, file_prefs.default_eol_character);
editor_set_use_tabs(doc->editor, editor_prefs.use_tabs);
sci_set_undo_collection(doc->editor->scintilla, TRUE);
sci_empty_undo_buffer(doc->editor->scintilla);
doc->mtime = time(NULL);
doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
/* store the opened encoding for undo/redo */
store_saved_encoding(doc);
/*document_set_filetype(idx, (ft == NULL) ? filetypes[GEANY_FILETYPES_NONE] : ft);*/
if (ft == NULL && filename != NULL) /* guess the filetype from the filename if one is given */
ft = filetypes_detect_from_file(doc);
document_set_filetype(doc, ft); /* also clears taglist */
if (ft == NULL)
highlighting_set_styles(doc->editor->scintilla, GEANY_FILETYPES_NONE);
ui_set_window_title(doc);
build_menu_update(doc);
document_update_tag_list(doc, FALSE);
document_set_text_changed(doc, FALSE);
ui_document_show_hide(doc); /* update the document menu */
sci_set_line_numbers(doc->editor->scintilla, editor_prefs.show_linenumber_margin, 0);
sci_goto_pos(doc->editor->scintilla, 0, TRUE);
/* "the" SCI signal (connect after initial setup(i.e. adding text)) */
g_signal_connect((GtkWidget*) doc->editor->scintilla, "sci-notify", G_CALLBACK(on_editor_notification), doc);
if (geany_object)
{
g_signal_emit_by_name(geany_object, "document-new", doc);
}
msgwin_status_add(_("New file \"%s\" opened."),
DOC_FILENAME(doc));
return doc;
}
/**
* Open a %document specified by @a locale_filename.
* After all, the "document-open" signal is emitted for plugins.
*
* @param locale_filename The filename of the %document to load, in locale encoding.
* @param readonly Whether to open the %document in read-only mode.
* @param ft The %filetype for the %document or @c NULL to auto-detect the %filetype.
* @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
*
* @return The document opened or NULL.
**/
GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
GeanyFiletype *ft, const gchar *forced_enc)
{
return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
}
typedef struct
{
gchar *data; /* null-terminated file data */
gsize size; /* actual file size on disk */
gsize len; /* string length of data */
gchar *enc;
gboolean bom;
time_t mtime; /* modification time, read by stat::st_mtime */
gboolean readonly;
} FileData;
/* reload file with specified encoding */
static gboolean
handle_forced_encoding(FileData *filedata, const gchar *forced_enc)
{
GeanyEncodingIndex enc_idx;
if (utils_str_equal(forced_enc, "UTF-8"))
{
if (! g_utf8_validate(filedata->data, filedata->len, NULL))
{
return FALSE;
}
}
else
{
gchar *converted_text = encodings_convert_to_utf8_from_charset(
filedata->data, filedata->len, forced_enc, FALSE);
if (converted_text == NULL)
{
return FALSE;
}
else
{
g_free(filedata->data);
filedata->data = converted_text;
filedata->len = strlen(converted_text);
}
}
enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
filedata->bom = (enc_idx == GEANY_ENCODING_UTF_8);
filedata->enc = g_strdup(forced_enc);
return TRUE;
}
/* detect encoding and convert to UTF-8 if necessary */
static gboolean
handle_encoding(FileData *filedata)
{
g_return_val_if_fail(filedata->enc == NULL, FALSE);
g_return_val_if_fail(filedata->bom == FALSE, FALSE);
if (filedata->size == 0)
{
/* we have no data so assume UTF-8, filedata->len can be 0 even we have an empty
* e.g. UTF32 file with a BOM(so size is 4, len is 0) */
filedata->enc = g_strdup("UTF-8");
}
else
{
/* first check for a BOM */
GeanyEncodingIndex enc_idx =
encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
if (enc_idx != GEANY_ENCODING_NONE)
{
filedata->enc = g_strdup(encodings[enc_idx].charset);
filedata->bom = TRUE;
if (enc_idx != GEANY_ENCODING_UTF_8) /* the BOM indicated something else than UTF-8 */
{
gchar *converted_text = encodings_convert_to_utf8_from_charset(
filedata->data, filedata->size, filedata->enc, FALSE);
if (converted_text != NULL)
{
g_free(filedata->data);
filedata->data = converted_text;
filedata->len = strlen(converted_text);
}
else
{
/* there was a problem converting data from BOM encoding type */
g_free(filedata->enc);
filedata->enc = NULL;
filedata->bom = FALSE;
}
}
}
if (filedata->enc == NULL) /* either there was no BOM or the BOM encoding failed */
{
/* try UTF-8 first */
if (g_utf8_validate(filedata->data, filedata->len, NULL))
{
filedata->enc = g_strdup("UTF-8");
}
else
{
/* detect the encoding */
gchar *converted_text = encodings_convert_to_utf8(filedata->data,
filedata->size, &filedata->enc);
if (converted_text == NULL)
{
return FALSE;
}
g_free(filedata->data);
filedata->data = converted_text;
filedata->len = strlen(converted_text);
}
}
}
return TRUE;
}
static void
handle_bom(FileData *filedata)
{
guint bom_len;
encodings_scan_unicode_bom(filedata->data, filedata->size, &bom_len);
g_return_if_fail(bom_len != 0);
/* use filedata->len here because the contents are already converted into UTF-8 */
filedata->len -= bom_len;
/* overwrite the BOM with the remainder of the file contents, plus the NULL terminator. */
g_memmove(filedata->data, filedata->data + bom_len, filedata->len + 1);
filedata->data = g_realloc(filedata->data, filedata->len + 1);
}
/* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
static gboolean load_text_file(const gchar *locale_filename, const gchar *utf8_filename,
FileData *filedata, const gchar *forced_enc)
{
GError *err = NULL;
struct stat st;
GeanyEncodingIndex tmp_enc_idx;
filedata->data = NULL;
filedata->len = 0;
filedata->enc = NULL;
filedata->bom = FALSE;
filedata->readonly = FALSE;
if (g_stat(locale_filename, &st) != 0)
{
ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), utf8_filename, g_strerror(errno));
return FALSE;
}
filedata->mtime = st.st_mtime;
if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
{
ui_set_statusbar(TRUE, "%s", err->message);
g_error_free(err);
return FALSE;
}
/* use strlen to check for null chars */
filedata->size = (gsize) st.st_size;
filedata->len = strlen(filedata->data);
/* temporarily retrieve the encoding idx based on the BOM to suppress the following warning
* if we have a BOM */
tmp_enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
/* check whether the size of the loaded data is equal to the size of the file in the filesystem */
/* file size may be 0 to allow opening files in /proc/ which have typically a file size
* of 0 bytes */
if (filedata->len != filedata->size && filedata->size != 0 && (
tmp_enc_idx == GEANY_ENCODING_UTF_8 || /* tmp_enc_idx can be UTF-7/8/16/32, UCS and None */
tmp_enc_idx == GEANY_ENCODING_UTF_7 || /* filter out UTF-7/8 and None where no NULL bytes */
tmp_enc_idx == GEANY_ENCODING_NONE)) /* are allowed */
{
const gchar *warn_msg = _(
"The file \"%s\" could not be opened properly and has been truncated. " \
"This can occur if the file contains a NULL byte. " \
"Be aware that saving it can cause data loss.\nThe file was set to read-only.");
if (main_status.main_window_realized)
dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, utf8_filename);
ui_set_statusbar(TRUE, warn_msg, utf8_filename);
/* set the file to read-only mode because saving it is probably dangerous */
filedata->readonly = TRUE;
}
/* Determine character encoding and convert to UTF-8 */
if (forced_enc != NULL)
{
/* the encoding should be ignored(requested by user), so open the file "as it is" */
if (utils_str_equal(forced_enc, encodings[GEANY_ENCODING_NONE].charset))
{
filedata->bom = FALSE;
filedata->enc = g_strdup(encodings[GEANY_ENCODING_NONE].charset);
}
else if (! handle_forced_encoding(filedata, forced_enc))
{
ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."), utf8_filename, forced_enc);
utils_beep();
g_free(filedata->data);
return FALSE;
}
}
else if (! handle_encoding(filedata))
{
ui_set_statusbar(TRUE,
_("The file \"%s\" does not look like a text file or the file encoding is not supported."),
utf8_filename);
utils_beep();
g_free(filedata->data);
return FALSE;
}
if (filedata->bom)
handle_bom(filedata);
return TRUE;
}
/* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
* is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
* if cl_options.goto_column is set. */
static void set_cursor_position(GeanyEditor *editor, gint pos)
{
if (cl_options.goto_line >= 0)
{ /* goto line which was specified on command line and then undefine the line */
sci_goto_line(editor->scintilla, cl_options.goto_line - 1, TRUE);
editor->scroll_percent = 0.5F;
cl_options.goto_line = -1;
}
else if (pos > 0)
{
sci_set_current_position(editor->scintilla, pos, FALSE);
editor->scroll_percent = 0.5F;
}
if (cl_options.goto_column >= 0)
{ /* goto column which was specified on command line and then undefine the column */
gint cur_pos = sci_get_current_position(editor->scintilla);
sci_set_current_position(editor->scintilla, cur_pos + cl_options.goto_column, FALSE);
editor->scroll_percent = 0.5F;
cl_options.goto_column = -1;
}
}
static gboolean detect_use_tabs(ScintillaObject *sci)
{
gint line;
gsize tabs = 0, spaces = 0;
for (line = 0; line < sci_get_line_count(sci); line++)
{
gint pos = sci_get_position_from_line(sci, line);
gchar c;
c = sci_get_char_at(sci, pos);
if (c == '\t')
tabs++;
else
if (c == ' ')
{
/* check at least 2 spaces */
if (sci_get_char_at(sci, pos + 1) == ' ')
spaces++;
}
}
if (spaces == 0 && tabs == 0)
return editor_prefs.use_tabs;
/* Skew comparison by a factor of 2 in favour of default editor pref */
if (editor_prefs.use_tabs)
return ! (spaces > tabs * 2);
else
return (tabs > spaces * 2);
}
static void set_indentation(GeanyDocument *doc)
{
/* force using tabs for indentation for Makefiles */
if (FILETYPE_ID(doc->file_type) == GEANY_FILETYPES_MAKE)
editor_set_use_tabs(doc->editor, TRUE);
else if (! editor_prefs.detect_tab_mode)
editor_set_use_tabs(doc->editor, editor_prefs.use_tabs);
else
{ /* detect & set tabs/spaces */
gboolean use_tabs = detect_use_tabs(doc->editor->scintilla);
if (use_tabs != editor_prefs.use_tabs)
ui_set_statusbar(TRUE, _("Setting %s indentation mode."),
(use_tabs) ? _("Tabs") : _("Spaces"));
editor_set_use_tabs(doc->editor, use_tabs);
}
}
/* To open a new file, set doc to NULL; filename should be locale encoded.
* To reload a file, set the doc for the document to be reloaded; filename should be NULL.
* pos is the cursor position, which can be overridden by --line and --column.
* forced_enc can be NULL to detect the file encoding.
* Returns: doc of the opened file or NULL if an error occurred. */
GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
{
gint editor_mode;
gboolean reload = (doc == NULL) ? FALSE : TRUE;
gchar *utf8_filename = NULL;
gchar *locale_filename = NULL;
GeanyFiletype *use_ft;
FileData filedata;
/*struct timeval tv, tv1;*/
/*struct timezone tz;*/
/*gettimeofday(&tv, &tz);*/
if (reload)
{
utf8_filename = g_strdup(doc->file_name);
locale_filename = utils_get_locale_from_utf8(utf8_filename);
}
else
{
/* filename must not be NULL when opening a file */
if (filename == NULL)
{
ui_set_statusbar(FALSE, _("Invalid filename"));
return NULL;
}
#ifdef G_OS_WIN32
/* if filename is a shortcut, try to resolve it */
locale_filename = win32_get_shortcut_target(filename);
#else
locale_filename = g_strdup(filename);
#endif
/* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
utf8_filename = utils_get_utf8_from_locale(locale_filename);
/* if file is already open, switch to it and go */
doc = document_find_by_filename(utf8_filename);
if (doc != NULL)
{
ui_add_recent_file(utf8_filename); /* either add or reorder recent item */
gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
(GtkWidget*) doc->editor->scintilla));
g_free(utf8_filename);
g_free(locale_filename);
document_check_disk_status(doc, TRUE); /* force a file changed check */
set_cursor_position(doc->editor, pos);
return doc;
}
}
/* if default encoding for opening files is set, use it if no forced encoding is set */
if (file_prefs.default_open_encoding >= 0 && forced_enc == NULL)
forced_enc = encodings[file_prefs.default_open_encoding].charset;
if (! load_text_file(locale_filename, utf8_filename, &filedata, forced_enc))
{
g_free(utf8_filename);