forked from geany/geany
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocument.c
3159 lines (2598 loc) · 88.3 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-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
* Copyright 2006-2012 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.
*/
/*
* 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 <stdlib.h>
/* gstdio.h also includes sys/stat.h */
#include <glib/gstdio.h>
/* uncomment to use GIO based file monitoring, though it is not completely stable yet */
/*#define USE_GIO_FILEMON 1*/
#include <gio/gio.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 "sidebar.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 "highlighting.h"
#include "navqueue.h"
#include "win32.h"
#include "search.h"
#include "filetypesprivate.h"
#include "project.h"
#include "SciLexer.h"
GeanyFilePrefs file_prefs;
/** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
* Once a pointer is added to this, it is never freed. This means you can keep a pointer
* to a document over time, but it might no longer represent a notebook tab. To check this,
* check @c doc_ptr->is_valid. Of course, the pointer may represent a different
* file by then.
*
* You also need to check @c GeanyDocument::is_valid when iterating over this array,
* although usually you would just use the foreach_document() macro.
*
* Never assume that the order of document pointers is the same as the order of notebook tabs.
* Notebook tabs can be reordered. Use @c document_get_from_page(). */
GPtrArray *documents_array = NULL;
/* 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);
static gboolean remove_page(guint page_num);
/**
* Finds a document whose @c real_path field matches the given filename.
*
* @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 @c NULL.
* @note This is only really useful when passing a @c TMWorkObject::file_name.
* @see GeanyDocument::real_path.
* @see document_find_by_filename().
*
* @since 0.15
**/
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 (! doc->is_valid || ! doc->real_path)
continue;
if (utils_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;
}
/**
* Finds a document with the given filename.
* 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 @c NULL.
* @see document_find_by_real_path().
**/
GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
{
guint i;
GeanyDocument *doc;
gchar *realname;
g_return_val_if_fail(utf8_filename != NULL, 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 (! doc->is_valid || doc->file_name == NULL)
continue;
if (utils_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;
g_return_val_if_fail(sci != NULL, NULL);
for (i = 0; i < documents_array->len; i++)
{
if (documents[i]->is_valid && documents[i]->editor->sci == sci)
return documents[i];
}
return NULL;
}
/** Gets the notebook page index for a document.
* @param doc The document.
* @return The index.
* @since 0.19 */
gint document_get_notebook_page(GeanyDocument *doc)
{
g_return_val_if_fail(doc != NULL, -1);
return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
GTK_WIDGET(doc->editor->sci));
}
/**
* Finds the document for the given notebook page @a page_num.
*
* @param page_num The notebook page number to search.
*
* @return The corresponding document for the given notebook page, or @c 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);
}
/**
* Finds 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()
{
guint i;
for (i = 0; i < documents_array->len; i++)
g_free(documents[i]);
g_ptr_array_free(documents_array, TRUE);
}
/**
* Returns the last part of the filename of the given GeanyDocument. The result is also
* truncated to a maximum of @a length characters in case the filename is very long.
*
* @param doc The document to use.
* @param length The length of the resulting string or -1 to use a default value.
*
* @return The ellipsized last part of the filename of @a doc, should be freed when no
* longer needed.
*
* @since 0.17
*/
/* TODO make more use of this */
gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
{
gchar *base_name, *short_name;
g_return_val_if_fail(doc != NULL, NULL);
if (length < 0)
length = 30;
base_name = g_path_get_basename(DOC_FILENAME(doc));
short_name = utils_str_middle_truncate(base_name, (guint)length);
g_free(base_name);
return short_name;
}
void document_update_tab_label(GeanyDocument *doc)
{
gchar *short_name;
GtkWidget *parent;
g_return_if_fail(doc != NULL);
short_name = document_get_basename_for_display(doc, -1);
/* we need to use the event box for the tooltip, labels don't get the necessary events */
parent = gtk_widget_get_parent(doc->priv->tab_label);
parent = gtk_widget_get_parent(parent);
gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
g_free(short_name);
}
/**
* Updates 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)
{
g_return_if_fail(doc != NULL);
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);
}
}
/* 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 == NULL)
{
return (gint) i;
}
}
return -1;
}
static void queue_colourise(GeanyDocument *doc)
{
/* Colourise the editor before it is next drawn */
doc->priv->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->sci));
}
#ifdef USE_GIO_FILEMON
static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
GeanyDocument *doc)
{
g_return_if_fail(doc != NULL);
if (file_prefs.disk_check_timeout == 0)
return;
geany_debug("%s: event: %d previous file status: %d",
G_STRFUNC, event, doc->priv->file_disk_status);
switch (event)
{
case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
{
if (doc->priv->file_disk_status == FILE_IGNORE)
doc->priv->file_disk_status = FILE_OK;
else
doc->priv->file_disk_status = FILE_CHANGED;
g_message("%s: FILE_CHANGED", G_STRFUNC);
break;
}
case G_FILE_MONITOR_EVENT_DELETED:
{
doc->priv->file_disk_status = FILE_CHANGED;
g_message("%s: FILE_MISSING", G_STRFUNC);
break;
}
default:
break;
}
if (doc->priv->file_disk_status != FILE_OK)
{
ui_update_tab_status(doc);
}
}
#endif
static void document_stop_file_monitoring(GeanyDocument *doc)
{
g_return_if_fail(doc != NULL);
if (doc->priv->monitor != NULL)
{
g_object_unref(doc->priv->monitor);
doc->priv->monitor = NULL;
}
}
static void monitor_file_setup(GeanyDocument *doc)
{
g_return_if_fail(doc != NULL);
/* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
* doesn't work at all for remote files and legacy polling is too slow. */
if (! doc->priv->is_remote)
{
#ifdef USE_GIO_FILEMON
gchar *locale_filename;
/* stop any previous monitoring */
document_stop_file_monitoring(doc);
locale_filename = utils_get_locale_from_utf8(doc->file_name);
if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
{
/* get a file monitor and connect to the 'changed' signal */
GFile *file = g_file_new_for_path(locale_filename);
doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
g_signal_connect(doc->priv->monitor, "changed",
G_CALLBACK(monitor_file_changed_cb), doc);
/* we set the rate limit according to the GUI pref but it's most probably not used */
g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
g_object_unref(file);
}
g_free(locale_filename);
#endif
}
doc->priv->file_disk_status = FILE_OK;
}
void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
{
/* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
if (DOC_VALID(doc))
{
GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
if (source_widget == NULL)
source_widget = doc->priv->tag_tree;
if (focusw == source_widget)
gtk_widget_grab_focus(sci);
}
}
static gboolean on_idle_focus(gpointer doc)
{
document_try_focus(doc, NULL);
return FALSE;
}
/* Creates a new document and editor, adding a tab in the notebook.
* @return The created document */
static GeanyDocument *document_create(const gchar *utf8_filename)
{
GeanyDocument *doc;
gint new_idx;
gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
if (cur_pages == 1)
{
doc = document_get_current();
/* remove the empty document first */
if (doc != NULL && doc->file_name == NULL && ! doc->changed)
/* prevent immediately opening another new doc with
* new_document_after_close pref */
remove_page(0);
}
new_idx = document_get_new_idx();
if (new_idx == -1) /* expand the array, no free places */
{
doc = g_new0(GeanyDocument, 1);
new_idx = documents_array->len;
g_ptr_array_add(documents_array, doc);
}
doc = documents[new_idx];
/* initialize default document settings */
doc->priv = g_new0(GeanyDocumentPrivate, 1);
doc->index = new_idx;
doc->file_name = g_strdup(utf8_filename);
doc->editor = editor_create(doc);
#ifndef USE_GIO_FILEMON
doc->priv->last_check = time(NULL);
#endif
sidebar_openfiles_add(doc); /* sets doc->iter */
notebook_new_tab(doc);
/* select document in sidebar */
{
GtkTreeSelection *sel;
sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
gtk_tree_selection_select_iter(sel, &doc->priv->iter);
}
ui_document_buttons_update();
doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
return doc;
}
/**
* Closes the given document.
*
* @param doc The document to remove.
*
* @return @c TRUE if the document was actually removed or @c FALSE otherwise.
*
* @since 0.15
**/
gboolean document_close(GeanyDocument *doc)
{
g_return_val_if_fail(doc, FALSE);
return document_remove_page(document_get_notebook_page(doc));
}
/* Call document_remove_page() instead, this is only needed for document_create()
* to prevent re-opening a new document when the last document is closed (if enabled). */
static gboolean remove_page(guint page_num)
{
GeanyDocument *doc = document_get_from_page(page_num);
g_return_val_if_fail(doc != NULL, FALSE);
if (doc->changed && ! dialogs_show_unsaved_file(doc))
return FALSE;
/* tell any plugins that the document is about to be closed */
g_signal_emit_by_name(geany_object, "document-close", doc);
/* Checking real_path makes it likely the file exists on disk */
if (! main_status.closing_all && doc->real_path != NULL)
ui_add_recent_document(doc);
doc->is_valid = FALSE;
if (! main_status.quitting)
{
notebook_remove_page(page_num);
sidebar_remove_document(doc);
navqueue_remove_file(doc->file_name);
msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
}
g_free(doc->encoding);
g_free(doc->priv->saved_encoding.encoding);
g_free(doc->file_name);
g_free(doc->real_path);
tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
if (doc->priv->tag_tree)
gtk_widget_destroy(doc->priv->tag_tree);
editor_destroy(doc->editor);
doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
document_stop_file_monitoring(doc);
document_undo_clear(doc);
g_free(doc->priv);
/* reset document settings to defaults for re-use */
memset(doc, 0, sizeof(GeanyDocument));
if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
{
sidebar_update_tag_list(NULL, FALSE);
ui_set_window_title(NULL);
ui_save_buttons_toggle(FALSE);
ui_update_popup_reundo_items(NULL);
ui_document_buttons_update();
build_menu_update(NULL);
}
return TRUE;
}
/**
* Removes the given notebook tab at @a page_num and clears all related information
* in the document list.
*
* @param page_num The notebook page number to remove.
*
* @return @c TRUE if the document was actually removed or @c FALSE otherwise.
**/
gboolean document_remove_page(guint page_num)
{
gboolean done = remove_page(page_num);
if (done && ui_prefs.new_document_after_close)
document_new_file_if_non_open();
return done;
}
/* used to keep a record of the unchanged document state encoding */
static void store_saved_encoding(GeanyDocument *doc)
{
g_free(doc->priv->saved_encoding.encoding);
doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
doc->priv->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(void)
{
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.
* Line endings in @a text will be converted to the default setting.
* Afterwards, the @c "document-new" signal is emitted for plugins.
*
* @param utf8_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 *utf8_filename, GeanyFiletype *ft, const gchar *text)
{
GeanyDocument *doc;
if (utf8_filename && g_path_is_absolute(utf8_filename))
{
gchar *tmp;
tmp = utils_strdupa(utf8_filename); /* work around const */
utils_tidy_path(tmp);
utf8_filename = tmp;
}
doc = document_create(utf8_filename);
g_assert(doc != NULL);
sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
if (text)
{
GString *template = g_string_new(text);
utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
sci_set_text(doc->editor->sci, template->str);
g_string_free(template, TRUE);
}
else
sci_clear_all(doc->editor->sci);
sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
sci_set_undo_collection(doc->editor->sci, TRUE);
sci_empty_undo_buffer(doc->editor->sci);
doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
/* store the opened encoding for undo/redo */
store_saved_encoding(doc);
if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
ft = filetypes_detect_from_document(doc);
document_set_filetype(doc, ft); /* also re-parses tags */
ui_set_window_title(doc);
build_menu_update(doc);
document_set_text_changed(doc, FALSE);
ui_document_show_hide(doc); /* update the document menu */
sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
/* bring it in front, jump to the start and grab the focus */
editor_goto_pos(doc->editor, 0, FALSE);
document_try_focus(doc, NULL);
#ifdef USE_GIO_FILEMON
monitor_file_setup(doc);
#else
doc->priv->mtime = time(NULL);
#endif
/* "the" SCI signal (connect after initial setup(i.e. adding text)) */
g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
g_signal_emit_by_name(geany_object, "document-new", doc);
msgwin_status_add(_("New file \"%s\" opened."),
DOC_FILENAME(doc));
return doc;
}
/**
* Opens a document specified by @a locale_filename.
* Afterwards, the @c "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 @c 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 len; /* string length of data */
gchar *enc;
gboolean bom;
time_t mtime; /* modification time, read by stat::st_mtime */
gboolean readonly;
} FileData;
/* 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 *display_filename,
FileData *filedata, const gchar *forced_enc)
{
GError *err = NULL;
struct stat st;
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)"),
display_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;
}
filedata->len = (gsize) st.st_size;
if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
&filedata->enc, &filedata->bom, &filedata->readonly))
{
if (forced_enc)
{
ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
display_filename, forced_enc);
}
else
{
ui_set_statusbar(TRUE,
_("The file \"%s\" does not look like a text file or the file encoding is not supported."),
display_filename);
}
g_free(filedata->data);
return FALSE;
}
if (filedata->readonly)
{
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, display_filename);
ui_set_statusbar(TRUE, warn_msg, display_filename);
}
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.
*
* returns the new position which may have changed */
static gint 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->sci, 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->sci, 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 new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
sci_set_current_position(editor->sci, new_pos, FALSE);
editor->scroll_percent = 0.5F;
cl_options.goto_column = -1;
return new_pos;
}
return sci_get_current_position(editor->sci);
}
/* Count lines that start with some hard tabs then a soft tab. */
static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
{
const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
ScintillaObject *sci = editor->sci;
gsize count = 0;
struct Sci_TextToFind ttf;
gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
g_free(soft_tab);
ttf.chrg.cpMin = 0;
ttf.chrg.cpMax = sci_get_length(sci);
ttf.lpstrText = regex;
while (1)
{
gint pos;
pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
if (pos == -1)
break; /* no more matches */
count++;
ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
}
g_free(regex);
/* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
return count > sci_get_line_count(sci) * 0.02;
}
/* Detect the indent type based on counting the leading indent characters for each line.
* Returns whether detection succeeded, and the detected type in *type_ upon success */
gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
{
GeanyEditor *editor = doc->editor;
ScintillaObject *sci = editor->sci;
gint line, line_count;
gsize tabs = 0, spaces = 0;
if (detect_tabs_and_spaces(editor))
{
*type_ = GEANY_INDENT_TYPE_BOTH;
return TRUE;
}
line_count = sci_get_line_count(sci);
for (line = 0; line < line_count; line++)
{
gint pos = sci_get_position_from_line(sci, line);
gchar c;
/* most code will have indent total <= 24, otherwise it's more likely to be
* alignment than indentation */
if (sci_get_line_indentation(sci, line) > 24)
continue;
c = sci_get_char_at(sci, pos);
if (c == '\t')
tabs++;
/* check for at least 2 spaces */
else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
spaces++;
}
if (spaces == 0 && tabs == 0)
return FALSE;
/* the factors may need to be tweaked */
if (spaces > tabs * 4)
*type_ = GEANY_INDENT_TYPE_SPACES;
else if (tabs > spaces * 4)
*type_ = GEANY_INDENT_TYPE_TABS;
else
*type_ = GEANY_INDENT_TYPE_BOTH;
return TRUE;
}
/* Detect the indent width based on counting the leading indent characters for each line.
* Returns whether detection succeeded, and the detected width in *width_ upon success */
static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
{
const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
ScintillaObject *sci = editor->sci;
gint line, line_count;
gint widths[7] = { 0 }; /* width can be from 2 to 8 */
gint count, width, i;
/* can't easily detect the supposed width of a tab, guess the default is OK */
if (type == GEANY_INDENT_TYPE_TABS)
return FALSE;
/* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
sci_set_tab_width(sci, 8);
line_count = sci_get_line_count(sci);
for (line = 0; line < line_count; line++)
{
gint pos = sci_get_line_indent_position(sci, line);
/* We probably don't have style info yet, because we're generally called just after
* the document got created, so we can't use highlighting_is_code_style().
* That's not good, but the assumption below that concerning lines start with an
* asterisk (common continuation character for C/C++/Java/...) should do the trick
* without removing too much legitimate lines. */
if (sci_get_char_at(sci, pos) == '*')
continue;
width = sci_get_line_indentation(sci, line);
/* most code will have indent total <= 24, otherwise it's more likely to be
* alignment than indentation */
if (width > 24)
continue;
/* < 2 is no indentation */
if (width < 2)
continue;
for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
{
if ((width % (i + 2)) == 0)