1 /*
2  *      document.c - this file is part of Geany, a fast and lightweight IDE
3  *
4  *      Copyright 2005 The Geany contributors
5  *
6  *      This program is free software; you can redistribute it and/or modify
7  *      it under the terms of the GNU General Public License as published by
8  *      the Free Software Foundation; either version 2 of the License, or
9  *      (at your option) any later version.
10  *
11  *      This program is distributed in the hope that it will be useful,
12  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *      GNU General Public License for more details.
15  *
16  *      You should have received a copy of the GNU General Public License along
17  *      with this program; if not, write to the Free Software Foundation, Inc.,
18  *      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 
21 /*
22  *  Document related actions: new, save, open, etc.
23  *  Also Scintilla search actions.
24  */
25 
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29 
30 #include "document.h"
31 
32 #include "app.h"
33 #include "callbacks.h" /* for ignore_callback */
34 #include "dialogs.h"
35 #include "documentprivate.h"
36 #include "encodings.h"
37 #include "encodingsprivate.h"
38 #include "filetypesprivate.h"
39 #include "geany.h" /* FIXME: why is this needed for DOC_FILENAME()? should come from documentprivate.h/document.h */
40 #include "geanyobject.h"
41 #include "geanywraplabel.h"
42 #include "highlighting.h"
43 #include "main.h"
44 #include "msgwindow.h"
45 #include "navqueue.h"
46 #include "notebook.h"
47 #include "project.h"
48 #include "sciwrappers.h"
49 #include "sidebar.h"
50 #include "support.h"
51 #include "symbols.h"
52 #include "ui_utils.h"
53 #include "utils.h"
54 #include "vte.h"
55 #include "win32.h"
56 
57 #include "gtkcompat.h"
58 
59 #ifdef HAVE_SYS_TIME_H
60 # include <sys/time.h>
61 #endif
62 #include <time.h>
63 
64 #include <unistd.h>
65 #include <string.h>
66 #include <errno.h>
67 
68 #ifdef HAVE_SYS_TYPES_H
69 # include <sys/types.h>
70 #endif
71 
72 #include <stdlib.h>
73 
74 /* gstdio.h also includes sys/stat.h */
75 #include <glib/gstdio.h>
76 
77 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
78 /*#define USE_GIO_FILEMON 1*/
79 #include <gio/gio.h>
80 
81 #include <gdk/gdkkeysyms.h>
82 
83 
84 #define USE_GIO_FILE_OPERATIONS (!file_prefs.use_safe_file_saving && file_prefs.use_gio_unsafe_file_saving)
85 
86 
87 GeanyFilePrefs file_prefs;
88 GPtrArray *documents_array = NULL;
89 
90 
91 /* an undo action, also used for redo actions */
92 typedef struct
93 {
94 	GTrashStack *next;	/* pointer to the next stack element(required for the GTrashStack) */
95 	guint type;			/* to identify the action */
96 	gpointer *data; 	/* the old value (before the change), in case of a redo action
97 						 * it contains the new value */
98 } undo_action;
99 
100 /* Custom document info bar response IDs */
101 enum
102 {
103 	RESPONSE_DOCUMENT_RELOAD = 1,
104 	RESPONSE_DOCUMENT_SAVE,
105 };
106 
107 
108 static guint doc_id_counter = 0;
109 
110 
111 static void document_undo_clear_stack(GTrashStack **stack);
112 static void document_undo_clear(GeanyDocument *doc);
113 static void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data);
114 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
115 static gboolean remove_page(guint page_num);
116 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
117 	void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
118 	const gchar *btn_1, GtkResponseType response_1,
119 	const gchar *btn_2, GtkResponseType response_2,
120 	const gchar *btn_3, GtkResponseType response_3,
121 	const gchar *extra_text, const gchar *format, ...) G_GNUC_PRINTF(11, 12);
122 
123 
124 /**
125  * Finds a document whose @c real_path field matches the given filename.
126  *
127  * @param realname The filename to search, which should be identical to the
128  * string returned by @c utils_get_real_path().
129  *
130  * @return @transfer{none} @nullable The matching document, or @c NULL.
131  * @note This is only really useful when passing a @c TMSourceFile::file_name.
132  * @see GeanyDocument::real_path.
133  * @see document_find_by_filename().
134  *
135  * @since 0.15
136  **/
137 GEANY_API_SYMBOL
document_find_by_real_path(const gchar * realname)138 GeanyDocument* document_find_by_real_path(const gchar *realname)
139 {
140 	guint i;
141 
142 	if (! realname)
143 		return NULL;	/* file doesn't exist on disk */
144 
145 	for (i = 0; i < documents_array->len; i++)
146 	{
147 		GeanyDocument *doc = documents[i];
148 
149 		if (! doc->is_valid || ! doc->real_path)
150 			continue;
151 
152 		if (utils_filenamecmp(realname, doc->real_path) == 0)
153 		{
154 			return doc;
155 		}
156 	}
157 	return NULL;
158 }
159 
160 
161 /* dereference symlinks, /../ junk in path and return locale encoding */
get_real_path_from_utf8(const gchar * utf8_filename)162 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
163 {
164 	gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
165 	gchar *realname = utils_get_real_path(locale_name);
166 
167 	g_free(locale_name);
168 	return realname;
169 }
170 
171 
172 /**
173  *  Finds a document with the given filename.
174  *  This matches either an exact GeanyDocument::file_name string, or variant
175  *  filenames with relative elements in the path (e.g. @c "/dir/..//name" will
176  *  match @c "/name").
177  *
178  *  @param utf8_filename The filename to search (in UTF-8 encoding).
179  *
180  *  @return @transfer{none} @nullable The matching document, or @c NULL.
181  *  @see document_find_by_real_path().
182  **/
183 GEANY_API_SYMBOL
document_find_by_filename(const gchar * utf8_filename)184 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
185 {
186 	guint i;
187 	GeanyDocument *doc;
188 	gchar *realname;
189 
190 	g_return_val_if_fail(utf8_filename != NULL, NULL);
191 
192 	/* First search GeanyDocument::file_name, so we can find documents with a
193 	 * filename set but not saved on disk, like vcdiff produces */
194 	for (i = 0; i < documents_array->len; i++)
195 	{
196 		doc = documents[i];
197 
198 		if (! doc->is_valid || doc->file_name == NULL)
199 			continue;
200 
201 		if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
202 		{
203 			return doc;
204 		}
205 	}
206 	/* Now try matching based on the realpath(), which is unique per file on disk */
207 	realname = get_real_path_from_utf8(utf8_filename);
208 	doc = document_find_by_real_path(realname);
209 	g_free(realname);
210 	return doc;
211 }
212 
213 
214 /* returns the document which has sci, or NULL. */
document_find_by_sci(ScintillaObject * sci)215 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
216 {
217 	guint i;
218 
219 	g_return_val_if_fail(sci != NULL, NULL);
220 
221 	for (i = 0; i < documents_array->len; i++)
222 	{
223 		if (documents[i]->is_valid && documents[i]->editor->sci == sci)
224 			return documents[i];
225 	}
226 	return NULL;
227 }
228 
229 
230 /** Lookup an old document by its ID.
231  * Useful when the corresponding document may have been closed since the
232  * ID was retrieved.
233  * @param id The ID of the document to find
234  * @return @transfer{none} @c NULL if the document is no longer open.
235  *
236  * Example:
237  * @code
238  * static guint id;
239  * GeanyDocument *doc = ...;
240  * id = doc->id;	// store ID
241  * ...
242  * // time passes - the document may have been closed by now
243  * GeanyDocument *doc = document_find_by_id(id);
244  * gboolean still_open = (doc != NULL);
245  * @endcode
246  * @since 1.25. */
247 GEANY_API_SYMBOL
document_find_by_id(guint id)248 GeanyDocument *document_find_by_id(guint id)
249 {
250 	guint i;
251 
252 	if (!id)
253 		return NULL;
254 
255 	foreach_document(i)
256 	{
257 		if (documents[i]->id == id)
258 			return documents[i];
259 	}
260 	return NULL;
261 }
262 
263 
264 /* gets the widget the main_widgets.notebook consider is its child for this document */
document_get_notebook_child(GeanyDocument * doc)265 static GtkWidget *document_get_notebook_child(GeanyDocument *doc)
266 {
267 	GtkWidget *parent;
268 	GtkWidget *child;
269 
270 	g_return_val_if_fail(doc != NULL, NULL);
271 
272 	child = GTK_WIDGET(doc->editor->sci);
273 	parent = gtk_widget_get_parent(child);
274 	/* search for the direct notebook child, mirroring document_get_from_page() */
275 	while (parent && ! GTK_IS_NOTEBOOK(parent))
276 	{
277 		child = parent;
278 		parent = gtk_widget_get_parent(child);
279 	}
280 
281 	return child;
282 }
283 
284 
285 /** Gets the notebook page index for a document.
286  * @param doc The document.
287  * @return The index.
288  * @since 0.19 */
289 GEANY_API_SYMBOL
document_get_notebook_page(GeanyDocument * doc)290 gint document_get_notebook_page(GeanyDocument *doc)
291 {
292 	GtkWidget *child = document_get_notebook_child(doc);
293 
294 	return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
295 }
296 
297 
298 /*
299  * Recursively searches a containers children until it finds a
300  * Scintilla widget, or NULL if one was not found.
301  */
locate_sci_in_container(GtkWidget * container)302 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
303 {
304 	ScintillaObject *sci = NULL;
305 	GList *children, *iter;
306 
307 	g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
308 
309 	children = gtk_container_get_children(GTK_CONTAINER(container));
310 	for (iter = children; iter != NULL; iter = g_list_next(iter))
311 	{
312 		if (IS_SCINTILLA(iter->data))
313 		{
314 			sci = SCINTILLA(iter->data);
315 			break;
316 		}
317 		else if (GTK_IS_CONTAINER(iter->data))
318 		{
319 			sci = locate_sci_in_container(iter->data);
320 			if (IS_SCINTILLA(sci))
321 				break;
322 			sci = NULL;
323 		}
324 	}
325 	g_list_free(children);
326 
327 	return sci;
328 }
329 
330 
331 /* Finds the document for the given notebook page widget */
document_get_from_notebook_child(GtkWidget * page)332 GeanyDocument *document_get_from_notebook_child(GtkWidget *page)
333 {
334 	ScintillaObject *sci;
335 
336 	g_return_val_if_fail(GTK_IS_BOX(page), NULL);
337 
338 	sci = locate_sci_in_container(page);
339 	g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
340 
341 	return document_find_by_sci(sci);
342 }
343 
344 
345 /**
346  *  Finds the document for the given notebook page @a page_num.
347  *
348  *  @param page_num The notebook page number to search.
349  *
350  *  @return @transfer{none} @nullable The corresponding document for the given notebook page, or @c NULL.
351  **/
352 GEANY_API_SYMBOL
document_get_from_page(guint page_num)353 GeanyDocument *document_get_from_page(guint page_num)
354 {
355 	GtkWidget *parent;
356 
357 	if (page_num >= documents_array->len)
358 		return NULL;
359 
360 	parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
361 
362 	return document_get_from_notebook_child(parent);
363 }
364 
365 
366 /**
367  *  Finds the current document.
368  *
369  *  @return @transfer{none} @nullable A pointer to the current document or @c NULL if there are no opened documents.
370  **/
371 GEANY_API_SYMBOL
document_get_current(void)372 GeanyDocument *document_get_current(void)
373 {
374 	gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
375 
376 	if (cur_page == -1)
377 		return NULL;
378 	else
379 		return document_get_from_page((guint) cur_page);
380 }
381 
382 
document_init_doclist(void)383 void document_init_doclist(void)
384 {
385 	documents_array = g_ptr_array_new();
386 }
387 
388 
document_finalize(void)389 void document_finalize(void)
390 {
391 	guint i;
392 
393 	for (i = 0; i < documents_array->len; i++)
394 		g_free(documents[i]);
395 	g_ptr_array_free(documents_array, TRUE);
396 }
397 
398 
399 /**
400  *  Returns the last part of the filename of the given GeanyDocument. The result is also
401  *  truncated to a maximum of @a length characters in case the filename is very long.
402  *
403  *  @param doc The document to use.
404  *  @param length The length of the resulting string or -1 to use a default value.
405  *
406  *  @return The ellipsized last part of the filename of @a doc, should be freed when no
407  *          longer needed.
408  *
409  *  @since 0.17
410  */
411 /* TODO make more use of this */
412 GEANY_API_SYMBOL
document_get_basename_for_display(GeanyDocument * doc,gint length)413 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
414 {
415 	gchar *base_name, *short_name;
416 
417 	g_return_val_if_fail(doc != NULL, NULL);
418 
419 	if (length < 0)
420 		length = 30;
421 
422 	base_name = g_path_get_basename(DOC_FILENAME(doc));
423 	short_name = utils_str_middle_truncate(base_name, (guint)length);
424 
425 	g_free(base_name);
426 
427 	return short_name;
428 }
429 
430 
document_update_tab_label(GeanyDocument * doc)431 void document_update_tab_label(GeanyDocument *doc)
432 {
433 	gchar *short_name;
434 	GtkWidget *parent;
435 
436 	g_return_if_fail(doc != NULL);
437 
438 	short_name = document_get_basename_for_display(doc, -1);
439 
440 	/* we need to use the event box for the tooltip, labels don't get the necessary events */
441 	parent = gtk_widget_get_parent(doc->priv->tab_label);
442 	parent = gtk_widget_get_parent(parent);
443 
444 	gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
445 
446 	gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
447 
448 	g_free(short_name);
449 }
450 
451 
452 /**
453  *  Updates the tab labels, the status bar, the window title and some save-sensitive buttons
454  *  according to the document's save state.
455  *  This is called by Geany mostly when opening or saving files.
456  *
457  * @param doc The document to use.
458  * @param changed Whether the document state should indicate changes have been made.
459  **/
460 GEANY_API_SYMBOL
document_set_text_changed(GeanyDocument * doc,gboolean changed)461 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
462 {
463 	g_return_if_fail(doc != NULL);
464 
465 	doc->changed = changed;
466 
467 	if (! main_status.quitting)
468 	{
469 		ui_update_tab_status(doc);
470 		ui_save_buttons_toggle(changed);
471 		ui_set_window_title(doc);
472 		ui_update_statusbar(doc, -1);
473 	}
474 }
475 
476 
477 /* returns the next free place in the document list,
478  * or -1 if the documents_array is full */
document_get_new_idx(void)479 static gint document_get_new_idx(void)
480 {
481 	guint i;
482 
483 	for (i = 0; i < documents_array->len; i++)
484 	{
485 		if (documents[i]->editor == NULL)
486 		{
487 			return (gint) i;
488 		}
489 	}
490 	return -1;
491 }
492 
493 
queue_colourise(GeanyDocument * doc)494 static void queue_colourise(GeanyDocument *doc)
495 {
496 	if (doc->priv->colourise_needed)
497 		return;
498 
499 	/* Colourise the editor before it is next drawn */
500 	doc->priv->colourise_needed = TRUE;
501 
502 	/* If the editor doesn't need drawing (e.g. after saving the current
503 	 * document), we need to force a redraw, so the expose event is triggered.
504 	 * This ensures we don't start colourising before all documents are opened/saved,
505 	 * only once the editor is drawn. */
506 	gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
507 }
508 
509 
510 #ifdef USE_GIO_FILEMON
monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor * monitor,G_GNUC_UNUSED GFile * file,G_GNUC_UNUSED GFile * other_file,GFileMonitorEvent event,GeanyDocument * doc)511 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
512 									G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
513 									GeanyDocument *doc)
514 {
515 	g_return_if_fail(doc != NULL);
516 
517 	if (file_prefs.disk_check_timeout == 0)
518 		return;
519 
520 	geany_debug("%s: event: %d previous file status: %d",
521 		G_STRFUNC, event, doc->priv->file_disk_status);
522 	switch (event)
523 	{
524 		case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
525 		{
526 			if (doc->priv->file_disk_status == FILE_IGNORE)
527 				doc->priv->file_disk_status = FILE_OK;
528 			else
529 				doc->priv->file_disk_status = FILE_CHANGED;
530 			g_message("%s: FILE_CHANGED", G_STRFUNC);
531 			break;
532 		}
533 		case G_FILE_MONITOR_EVENT_DELETED:
534 		{
535 			doc->priv->file_disk_status = FILE_CHANGED;
536 			g_message("%s: FILE_MISSING", G_STRFUNC);
537 			break;
538 		}
539 		default:
540 			break;
541 	}
542 	if (doc->priv->file_disk_status != FILE_OK)
543 	{
544 		ui_update_tab_status(doc);
545 	}
546 }
547 #endif
548 
549 
document_stop_file_monitoring(GeanyDocument * doc)550 static void document_stop_file_monitoring(GeanyDocument *doc)
551 {
552 	g_return_if_fail(doc != NULL);
553 
554 	if (doc->priv->monitor != NULL)
555 	{
556 		g_object_unref(doc->priv->monitor);
557 		doc->priv->monitor = NULL;
558 	}
559 }
560 
561 
monitor_file_setup(GeanyDocument * doc)562 static void monitor_file_setup(GeanyDocument *doc)
563 {
564 	g_return_if_fail(doc != NULL);
565 	/* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
566 	 * doesn't work at all for remote files and legacy polling is too slow. */
567 	if (! doc->priv->is_remote)
568 	{
569 #ifdef USE_GIO_FILEMON
570 		gchar *locale_filename;
571 
572 		/* stop any previous monitoring */
573 		document_stop_file_monitoring(doc);
574 
575 		locale_filename = utils_get_locale_from_utf8(doc->file_name);
576 		if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
577 		{
578 			/* get a file monitor and connect to the 'changed' signal */
579 			GFile *file = g_file_new_for_path(locale_filename);
580 			doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
581 			g_signal_connect(doc->priv->monitor, "changed",
582 				G_CALLBACK(monitor_file_changed_cb), doc);
583 
584 			/* we set the rate limit according to the GUI pref but it's most probably not used */
585 			g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
586 
587 			g_object_unref(file);
588 		}
589 		g_free(locale_filename);
590 #endif
591 	}
592 	doc->priv->file_disk_status = FILE_OK;
593 }
594 
595 
document_try_focus(GeanyDocument * doc,GtkWidget * source_widget)596 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
597 {
598 	/* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
599 	if (DOC_VALID(doc))
600 	{
601 		GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
602 		GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
603 
604 		if (source_widget == NULL)
605 			source_widget = doc->priv->tag_tree;
606 
607 		if (focusw == source_widget)
608 			gtk_widget_grab_focus(sci);
609 	}
610 }
611 
612 
on_idle_focus(gpointer doc)613 static gboolean on_idle_focus(gpointer doc)
614 {
615 	document_try_focus(doc, NULL);
616 	return FALSE;
617 }
618 
619 
620 /* Creates a new document and editor, adding a tab in the notebook.
621  * @return The created document */
document_create(const gchar * utf8_filename)622 static GeanyDocument *document_create(const gchar *utf8_filename)
623 {
624 	GeanyDocument *doc;
625 	gint new_idx;
626 	gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
627 
628 	if (cur_pages == 1)
629 	{
630 		doc = document_get_current();
631 		/* remove the empty document first */
632 		if (doc != NULL && doc->file_name == NULL && ! doc->changed)
633 			/* prevent immediately opening another new doc with
634 			 * new_document_after_close pref */
635 			remove_page(0);
636 	}
637 
638 	new_idx = document_get_new_idx();
639 	if (new_idx == -1)	/* expand the array, no free places */
640 	{
641 		doc = g_new0(GeanyDocument, 1);
642 
643 		new_idx = documents_array->len;
644 		g_ptr_array_add(documents_array, doc);
645 	}
646 
647 	doc = documents[new_idx];
648 
649 	/* initialize default document settings */
650 	doc->priv = g_new0(GeanyDocumentPrivate, 1);
651 	doc->id = ++doc_id_counter;
652 	doc->index = new_idx;
653 	doc->file_name = g_strdup(utf8_filename);
654 	doc->editor = editor_create(doc);
655 #ifndef USE_GIO_FILEMON
656 	doc->priv->last_check = time(NULL);
657 #endif
658 
659 	g_datalist_init(&doc->priv->data);
660 
661 	sidebar_openfiles_add(doc);	/* sets doc->iter */
662 
663 	notebook_new_tab(doc);
664 
665 	/* select document in sidebar */
666 	{
667 		GtkTreeSelection *sel;
668 
669 		sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
670 		gtk_tree_selection_select_iter(sel, &doc->priv->iter);
671 	}
672 
673 	ui_document_buttons_update();
674 
675 	doc->is_valid = TRUE;	/* do this last to prevent UI updating with NULL items. */
676 	return doc;
677 }
678 
679 
680 /**
681  *  Closes the given document.
682  *
683  *  @param doc The document to remove.
684  *
685  *  @return @c TRUE if the document was actually removed or @c FALSE otherwise.
686  *
687  * @since 0.15
688  **/
689 GEANY_API_SYMBOL
document_close(GeanyDocument * doc)690 gboolean document_close(GeanyDocument *doc)
691 {
692 	g_return_val_if_fail(doc, FALSE);
693 
694 	return document_remove_page(document_get_notebook_page(doc));
695 }
696 
697 
698 /* Call document_remove_page() instead, this is only needed for document_create()
699  * to prevent re-opening a new document when the last document is closed (if enabled). */
remove_page(guint page_num)700 static gboolean remove_page(guint page_num)
701 {
702 	GeanyDocument *doc = document_get_from_page(page_num);
703 
704 	g_return_val_if_fail(doc != NULL, FALSE);
705 
706 	/* if we're closing all, document_account_for_unsaved() has been called already, no need to ask again. */
707 	if (! main_status.closing_all && doc->changed && ! dialogs_show_unsaved_file(doc))
708 		return FALSE;
709 
710 	/* tell any plugins that the document is about to be closed */
711 	g_signal_emit_by_name(geany_object, "document-close", doc);
712 
713 	/* Checking real_path makes it likely the file exists on disk */
714 	if (! main_status.closing_all && doc->real_path != NULL)
715 		ui_add_recent_document(doc);
716 
717 	g_datalist_clear(&doc->priv->data);
718 
719 	doc->is_valid = FALSE;
720 	doc->id = 0;
721 
722 	if (main_status.quitting)
723 	{
724 		/* we need to destroy the ScintillaWidget so our handlers on it are
725 		 * disconnected before we free any data they may use (like the editor).
726 		 * when not quitting, this is handled by removing the notebook page. */
727 		gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
728 	}
729 	else
730 	{
731 		notebook_remove_page(page_num);
732 		sidebar_remove_document(doc);
733 		navqueue_remove_file(doc->file_name);
734 		msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
735 	}
736 	g_free(doc->encoding);
737 	g_free(doc->priv->saved_encoding.encoding);
738 	g_free(doc->file_name);
739 	g_free(doc->real_path);
740 	if (doc->tm_file)
741 	{
742 		tm_workspace_remove_source_file(doc->tm_file);
743 		tm_source_file_free(doc->tm_file);
744 	}
745 
746 	if (doc->priv->tag_tree)
747 		gtk_widget_destroy(doc->priv->tag_tree);
748 
749 	editor_destroy(doc->editor);
750 	doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
751 
752 	document_stop_file_monitoring(doc);
753 
754 	document_undo_clear(doc);
755 
756 	g_free(doc->priv);
757 
758 	/* reset document settings to defaults for re-use */
759 	memset(doc, 0, sizeof(GeanyDocument));
760 
761 	if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
762 	{
763 		sidebar_update_tag_list(NULL, FALSE);
764 		ui_set_window_title(NULL);
765 		ui_save_buttons_toggle(FALSE);
766 		ui_update_popup_reundo_items(NULL);
767 		ui_document_buttons_update();
768 		build_menu_update(NULL);
769 	}
770 	return TRUE;
771 }
772 
773 
774 /**
775  *  Removes the given notebook tab at @a page_num and clears all related information
776  *  in the document list.
777  *
778  *  @param page_num The notebook page number to remove.
779  *
780  *  @return @c TRUE if the document was actually removed or @c FALSE otherwise.
781  **/
782 GEANY_API_SYMBOL
document_remove_page(guint page_num)783 gboolean document_remove_page(guint page_num)
784 {
785 	gboolean done = remove_page(page_num);
786 
787 	if (done && ui_prefs.new_document_after_close)
788 		document_new_file_if_non_open();
789 
790 	return done;
791 }
792 
793 
794 /* used to keep a record of the unchanged document state encoding */
store_saved_encoding(GeanyDocument * doc)795 static void store_saved_encoding(GeanyDocument *doc)
796 {
797 	g_free(doc->priv->saved_encoding.encoding);
798 	doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
799 	doc->priv->saved_encoding.has_bom = doc->has_bom;
800 }
801 
802 
803 /* Opens a new empty document only if there are no other documents open */
document_new_file_if_non_open(void)804 GeanyDocument *document_new_file_if_non_open(void)
805 {
806 	if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
807 		return document_new_file(NULL, NULL, NULL);
808 
809 	return NULL;
810 }
811 
812 
813 /**
814  *  Creates a new document.
815  *  Line endings in @a text will be converted to the default setting.
816  *  Afterwards, the @c "document-new" signal is emitted for plugins.
817  *
818  *  @param utf8_filename @nullable The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
819  *  @param ft @nullable The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
820  *  @param text @nullable The initial content of the file (in UTF-8 encoding), or @c NULL.
821  *
822  *  @return @transfer{none} The new document.
823  **/
824 GEANY_API_SYMBOL
document_new_file(const gchar * utf8_filename,GeanyFiletype * ft,const gchar * text)825 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
826 {
827 	GeanyDocument *doc;
828 
829 	if (utf8_filename && g_path_is_absolute(utf8_filename))
830 	{
831 		gchar *tmp;
832 		tmp = utils_strdupa(utf8_filename);	/* work around const */
833 		utils_tidy_path(tmp);
834 		utf8_filename = tmp;
835 	}
836 	doc = document_create(utf8_filename);
837 
838 	g_assert(doc != NULL);
839 
840 	sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
841 	if (text)
842 	{
843 		GString *template = g_string_new(text);
844 		utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
845 
846 		sci_set_text(doc->editor->sci, template->str);
847 		g_string_free(template, TRUE);
848 	}
849 	else
850 		sci_clear_all(doc->editor->sci);
851 
852 	sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
853 
854 	sci_set_undo_collection(doc->editor->sci, TRUE);
855 	sci_empty_undo_buffer(doc->editor->sci);
856 
857 	doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
858 	/* store the opened encoding for undo/redo */
859 	store_saved_encoding(doc);
860 
861 	if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
862 		ft = filetypes_detect_from_document(doc);
863 
864 	document_set_filetype(doc, ft); /* also re-parses tags */
865 
866 	/* now the document is fully ready, display it (see notebook_new_tab()) */
867 	gtk_widget_show(document_get_notebook_child(doc));
868 
869 	ui_set_window_title(doc);
870 	build_menu_update(doc);
871 	document_set_text_changed(doc, FALSE);
872 	ui_document_show_hide(doc); /* update the document menu */
873 
874 	sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
875 	/* bring it in front, jump to the start and grab the focus */
876 	editor_goto_pos(doc->editor, 0, FALSE);
877 	document_try_focus(doc, NULL);
878 
879 #ifdef USE_GIO_FILEMON
880 	monitor_file_setup(doc);
881 #else
882 	doc->priv->mtime = 0;
883 #endif
884 
885 	/* "the" SCI signal (connect after initial setup(i.e. adding text)) */
886 	g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
887 
888 	g_signal_emit_by_name(geany_object, "document-new", doc);
889 
890 	msgwin_status_add(_("New file \"%s\" opened."),
891 		DOC_FILENAME(doc));
892 
893 	return doc;
894 }
895 
896 
897 /**
898  *  Opens a document specified by @a locale_filename.
899  *  Afterwards, the @c "document-open" signal is emitted for plugins.
900  *
901  *  @param locale_filename The filename of the document to load, in locale encoding.
902  *  @param readonly Whether to open the document in read-only mode.
903  *  @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
904  *  @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
905  *
906  *  @return @transfer{none} @nullable The document opened or @c NULL.
907  **/
908 GEANY_API_SYMBOL
document_open_file(const gchar * locale_filename,gboolean readonly,GeanyFiletype * ft,const gchar * forced_enc)909 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
910 		GeanyFiletype *ft, const gchar *forced_enc)
911 {
912 	return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
913 }
914 
915 
916 typedef struct
917 {
918 	gchar		*data;	/* null-terminated file data */
919 	gsize		 len;	/* string length of data */
920 	gchar		*enc;
921 	gboolean	 bom;
922 	time_t		 mtime;	/* modification time, read by stat::st_mtime */
923 	gboolean	 readonly;
924 } FileData;
925 
926 
get_mtime(const gchar * locale_filename,time_t * time)927 static gboolean get_mtime(const gchar *locale_filename, time_t *time)
928 {
929 	GError *error = NULL;
930 	const gchar *err_msg = NULL;
931 
932 	if (USE_GIO_FILE_OPERATIONS)
933 	{
934 		GFile *file = g_file_new_for_path(locale_filename);
935 		GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, NULL, &error);
936 
937 		if (info)
938 		{
939 			GTimeVal timeval;
940 
941 			g_file_info_get_modification_time(info, &timeval);
942 			g_object_unref(info);
943 			*time = timeval.tv_sec;
944 		}
945 		else if (error)
946 			err_msg = error->message;
947 
948 		g_object_unref(file);
949 	}
950 	else
951 	{
952 		GStatBuf st;
953 
954 		if (g_stat(locale_filename, &st) == 0)
955 			*time = st.st_mtime;
956 		else
957 			err_msg = g_strerror(errno);
958 	}
959 
960 	if (err_msg)
961 	{
962 		gchar *utf8_filename = utils_get_utf8_from_locale(locale_filename);
963 
964 		ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
965 			utf8_filename, err_msg);
966 		g_free(utf8_filename);
967 	}
968 
969 	if (error)
970 		g_error_free(error);
971 
972 	return err_msg == NULL;
973 }
974 
975 
976 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
load_text_file(const gchar * locale_filename,const gchar * display_filename,FileData * filedata,const gchar * forced_enc)977 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
978 	FileData *filedata, const gchar *forced_enc)
979 {
980 	GError *err = NULL;
981 
982 	filedata->data = NULL;
983 	filedata->len = 0;
984 	filedata->enc = NULL;
985 	filedata->bom = FALSE;
986 	filedata->readonly = FALSE;
987 
988 	if (!get_mtime(locale_filename, &filedata->mtime))
989 		return FALSE;
990 
991 	if (USE_GIO_FILE_OPERATIONS)
992 	{
993 		GFile *file = g_file_new_for_path(locale_filename);
994 
995 		g_file_load_contents(file, NULL, &filedata->data, &filedata->len, NULL, &err);
996 		g_object_unref(file);
997 	}
998 	else
999 		g_file_get_contents(locale_filename, &filedata->data, &filedata->len, &err);
1000 
1001 	if (err)
1002 	{
1003 		ui_set_statusbar(TRUE, "%s", err->message);
1004 		g_error_free(err);
1005 		return FALSE;
1006 	}
1007 
1008 	if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
1009 				&filedata->enc, &filedata->bom, &filedata->readonly))
1010 	{
1011 		if (forced_enc)
1012 		{
1013 			ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
1014 				display_filename, forced_enc);
1015 		}
1016 		else
1017 		{
1018 			ui_set_statusbar(TRUE,
1019 	_("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1020 			display_filename);
1021 		}
1022 		g_free(filedata->data);
1023 		return FALSE;
1024 	}
1025 
1026 	if (filedata->readonly)
1027 	{
1028 		const gchar *warn_msg = _(
1029 			"The file \"%s\" could not be opened properly and has been truncated. " \
1030 			"This can occur if the file contains a NULL byte. " \
1031 			"Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1032 
1033 		if (main_status.main_window_realized)
1034 			dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
1035 
1036 		ui_set_statusbar(TRUE, warn_msg, display_filename);
1037 	}
1038 
1039 	return TRUE;
1040 }
1041 
1042 
1043 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1044  * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1045  * if cl_options.goto_column is set.
1046  *
1047  * returns the new position which may have changed */
set_cursor_position(GeanyEditor * editor,gint pos)1048 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1049 {
1050 	if (cl_options.goto_line >= 0)
1051 	{	/* goto line which was specified on command line and then undefine the line */
1052 		sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1053 		editor->scroll_percent = 0.5F;
1054 		cl_options.goto_line = -1;
1055 	}
1056 	else if (pos > 0)
1057 	{
1058 		sci_set_current_position(editor->sci, pos, FALSE);
1059 		editor->scroll_percent = 0.5F;
1060 	}
1061 
1062 	if (cl_options.goto_column >= 0)
1063 	{	/* goto column which was specified on command line and then undefine the column */
1064 
1065 		gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1066 		sci_set_current_position(editor->sci, new_pos, FALSE);
1067 		editor->scroll_percent = 0.5F;
1068 		cl_options.goto_column = -1;
1069 		return new_pos;
1070 	}
1071 	return sci_get_current_position(editor->sci);
1072 }
1073 
1074 
1075 /* Count lines that start with some hard tabs then a soft tab. */
detect_tabs_and_spaces(GeanyEditor * editor)1076 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1077 {
1078 	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1079 	ScintillaObject *sci = editor->sci;
1080 	gsize count = 0;
1081 	struct Sci_TextToFind ttf;
1082 	gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
1083 	gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1084 
1085 	g_free(soft_tab);
1086 
1087 	ttf.chrg.cpMin = 0;
1088 	ttf.chrg.cpMax = sci_get_length(sci);
1089 	ttf.lpstrText = regex;
1090 	while (1)
1091 	{
1092 		gint pos;
1093 
1094 		pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1095 		if (pos == -1)
1096 			break;	/* no more matches */
1097 		count++;
1098 		ttf.chrg.cpMin = ttf.chrgText.cpMax + 1;	/* search after this match */
1099 	}
1100 	g_free(regex);
1101 	/* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1102 	return count > sci_get_line_count(sci) * 0.02;
1103 }
1104 
1105 
1106 /* Detect the indent type based on counting the leading indent characters for each line.
1107  * Returns whether detection succeeded, and the detected type in *type_ upon success */
document_detect_indent_type(GeanyDocument * doc,GeanyIndentType * type_)1108 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
1109 {
1110 	GeanyEditor *editor = doc->editor;
1111 	ScintillaObject *sci = editor->sci;
1112 	gint line, line_count;
1113 	gsize tabs = 0, spaces = 0;
1114 
1115 	if (detect_tabs_and_spaces(editor))
1116 	{
1117 		*type_ = GEANY_INDENT_TYPE_BOTH;
1118 		return TRUE;
1119 	}
1120 
1121 	line_count = sci_get_line_count(sci);
1122 	for (line = 0; line < line_count; line++)
1123 	{
1124 		gint pos = sci_get_position_from_line(sci, line);
1125 		gchar c;
1126 
1127 		/* most code will have indent total <= 24, otherwise it's more likely to be
1128 		 * alignment than indentation */
1129 		if (sci_get_line_indentation(sci, line) > 24)
1130 			continue;
1131 
1132 		c = sci_get_char_at(sci, pos);
1133 		if (c == '\t')
1134 			tabs++;
1135 		/* check for at least 2 spaces */
1136 		else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1137 			spaces++;
1138 	}
1139 	if (spaces == 0 && tabs == 0)
1140 		return FALSE;
1141 
1142 	/* the factors may need to be tweaked */
1143 	if (spaces > tabs * 4)
1144 		*type_ = GEANY_INDENT_TYPE_SPACES;
1145 	else if (tabs > spaces * 4)
1146 		*type_ = GEANY_INDENT_TYPE_TABS;
1147 	else
1148 		*type_ = GEANY_INDENT_TYPE_BOTH;
1149 
1150 	return TRUE;
1151 }
1152 
1153 
1154 /* Detect the indent width based on counting the leading indent characters for each line.
1155  * Returns whether detection succeeded, and the detected width in *width_ upon success */
detect_indent_width(GeanyEditor * editor,GeanyIndentType type,gint * width_)1156 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1157 {
1158 	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1159 	ScintillaObject *sci = editor->sci;
1160 	gint line, line_count;
1161 	gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1162 	gint count, width, i;
1163 
1164 	/* can't easily detect the supposed width of a tab, guess the default is OK */
1165 	if (type == GEANY_INDENT_TYPE_TABS)
1166 		return FALSE;
1167 
1168 	/* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1169 	sci_set_tab_width(sci, 8);
1170 
1171 	line_count = sci_get_line_count(sci);
1172 	for (line = 0; line < line_count; line++)
1173 	{
1174 		gint pos = sci_get_line_indent_position(sci, line);
1175 
1176 		/* We probably don't have style info yet, because we're generally called just after
1177 		 * the document got created, so we can't use highlighting_is_code_style().
1178 		 * That's not good, but the assumption below that concerning lines start with an
1179 		 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1180 		 * without removing too much legitimate lines. */
1181 		if (sci_get_char_at(sci, pos) == '*')
1182 			continue;
1183 
1184 		width = sci_get_line_indentation(sci, line);
1185 		/* most code will have indent total <= 24, otherwise it's more likely to be
1186 		 * alignment than indentation */
1187 		if (width > 24)
1188 			continue;
1189 		/* < 2 is no indentation */
1190 		if (width < 2)
1191 			continue;
1192 
1193 		for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1194 		{
1195 			if ((width % (i + 2)) == 0)
1196 				widths[i]++;
1197 		}
1198 	}
1199 	count = 0;
1200 	width = iprefs->width;
1201 	for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1202 	{
1203 		/* give large indents higher weight not to be fooled by spurious indents */
1204 		if (widths[i] >= count * 1.5)
1205 		{
1206 			width = i + 2;
1207 			count = widths[i];
1208 		}
1209 	}
1210 
1211 	if (count == 0)
1212 		return FALSE;
1213 
1214 	*width_ = width;
1215 	return TRUE;
1216 }
1217 
1218 
1219 /* same as detect_indent_width() but uses editor's indent type */
document_detect_indent_width(GeanyDocument * doc,gint * width_)1220 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1221 {
1222 	return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1223 }
1224 
1225 
document_apply_indent_settings(GeanyDocument * doc)1226 void document_apply_indent_settings(GeanyDocument *doc)
1227 {
1228 	const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1229 	GeanyIndentType type = iprefs->type;
1230 	gint width = iprefs->width;
1231 
1232 	if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1233 	{
1234 		if (type != iprefs->type)
1235 		{
1236 			const gchar *name = NULL;
1237 
1238 			switch (type)
1239 			{
1240 				case GEANY_INDENT_TYPE_SPACES:
1241 					name = _("Spaces");
1242 					break;
1243 				case GEANY_INDENT_TYPE_TABS:
1244 					name = _("Tabs");
1245 					break;
1246 				case GEANY_INDENT_TYPE_BOTH:
1247 					name = _("Tabs and Spaces");
1248 					break;
1249 			}
1250 			/* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1251 			 * and Spaces), the second one is the filename */
1252 			ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1253 				DOC_FILENAME(doc));
1254 		}
1255 	}
1256 	else if (doc->file_type->indent_type > -1)
1257 		type = doc->file_type->indent_type;
1258 
1259 	if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1260 	{
1261 		if (width != iprefs->width)
1262 		{
1263 			ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1264 				DOC_FILENAME(doc));
1265 		}
1266 	}
1267 	else if (doc->file_type->indent_width > -1)
1268 		width = doc->file_type->indent_width;
1269 
1270 	editor_set_indent(doc->editor, type, width);
1271 }
1272 
1273 
document_show_tab(GeanyDocument * doc)1274 void document_show_tab(GeanyDocument *doc)
1275 {
1276 	gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1277 		document_get_notebook_page(doc));
1278 }
1279 
1280 
1281 /* To open a new file, set doc to NULL; filename should be locale encoded.
1282  * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1283  * pos is the cursor position, which can be overridden by --line and --column.
1284  * forced_enc can be NULL to detect the file encoding.
1285  * Returns: doc of the opened file or NULL if an error occurred. */
document_open_file_full(GeanyDocument * doc,const gchar * filename,gint pos,gboolean readonly,GeanyFiletype * ft,const gchar * forced_enc)1286 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1287 		gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1288 {
1289 	gint editor_mode;
1290 	gboolean reload = (doc == NULL) ? FALSE : TRUE;
1291 	gchar *utf8_filename = NULL;
1292 	gchar *display_filename = NULL;
1293 	gchar *locale_filename = NULL;
1294 	GeanyFiletype *use_ft;
1295 	FileData filedata;
1296 	UndoReloadData *undo_reload_data;
1297 	gboolean add_undo_reload_action;
1298 
1299 	g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1300 
1301 	if (reload)
1302 	{
1303 		utf8_filename = g_strdup(doc->file_name);
1304 		locale_filename = utils_get_locale_from_utf8(utf8_filename);
1305 	}
1306 	else
1307 	{
1308 		/* filename must not be NULL when opening a file */
1309 		g_return_val_if_fail(filename, NULL);
1310 
1311 #ifdef G_OS_WIN32
1312 		/* if filename is a shortcut, try to resolve it */
1313 		locale_filename = win32_get_shortcut_target(filename);
1314 #else
1315 		locale_filename = g_strdup(filename);
1316 #endif
1317 		/* remove relative junk */
1318 		utils_tidy_path(locale_filename);
1319 
1320 		/* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1321 		utf8_filename = utils_get_utf8_from_locale(locale_filename);
1322 
1323 		/* if file is already open, switch to it and go */
1324 		doc = document_find_by_filename(utf8_filename);
1325 		if (doc != NULL)
1326 		{
1327 			ui_add_recent_document(doc);	/* either add or reorder recent item */
1328 			/* show the doc before reload dialog */
1329 			document_show_tab(doc);
1330 			document_check_disk_status(doc, TRUE);	/* force a file changed check */
1331 		}
1332 	}
1333 	if (reload || doc == NULL)
1334 	{	/* doc possibly changed */
1335 		display_filename = utils_str_middle_truncate(utf8_filename, 100);
1336 
1337 		if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1338 		{
1339 			g_free(display_filename);
1340 			g_free(utf8_filename);
1341 			g_free(locale_filename);
1342 			return NULL;
1343 		}
1344 
1345 		if (! reload)
1346 		{
1347 			doc = document_create(utf8_filename);
1348 			g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1349 
1350 			/* file exists on disk, set real_path */
1351 			SETPTR(doc->real_path, utils_get_real_path(locale_filename));
1352 
1353 			doc->priv->is_remote = utils_is_remote_path(locale_filename);
1354 			monitor_file_setup(doc);
1355 		}
1356 
1357 		if (! reload || ! file_prefs.keep_edit_history_on_reload)
1358 		{
1359 			sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1360 			sci_empty_undo_buffer(doc->editor->sci);
1361 			undo_reload_data = NULL;
1362 		}
1363 		else
1364 		{
1365 			undo_reload_data = (UndoReloadData*) g_malloc(sizeof(UndoReloadData));
1366 
1367 			/* We will be adding a UNDO_RELOAD action to the undo stack that undoes
1368 			 * this reload. To do that, we keep collecting undo actions during
1369 			 * reloading, and at the end add an UNDO_RELOAD action that performs
1370 			 * all these actions in bulk. To keep track of how many undo actions
1371 			 * were added during this time, we compare the current undo-stack height
1372 			 * with its height at the end of the process. Note that g_trash_stack_height()
1373 			 * is O(N), which is a little ugly, but this seems like the most maintainable
1374 			 * option. */
1375 			undo_reload_data->actions_count = g_trash_stack_height(&doc->priv->undo_actions);
1376 
1377 			/* We use add_undo_reload_action to track any changes to the document that
1378 			 * require adding an undo action to revert the reload, but that do not
1379 			 * generate an undo action themselves. */
1380 			add_undo_reload_action = FALSE;
1381 		}
1382 
1383 		/* add the text to the ScintillaObject */
1384 		sci_set_readonly(doc->editor->sci, FALSE);	/* to allow replacing text */
1385 		sci_set_text(doc->editor->sci, filedata.data);	/* NULL terminated data */
1386 		queue_colourise(doc);	/* Ensure the document gets colourised. */
1387 
1388 		/* detect & set line endings */
1389 		editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1390 		if (undo_reload_data)
1391 		{
1392 			undo_reload_data->eol_mode = editor_get_eol_char_mode(doc->editor);
1393 			/* Force adding an undo-reload action if the EOL mode changed. */
1394 			if (editor_mode != undo_reload_data->eol_mode)
1395 				add_undo_reload_action = TRUE;
1396 		}
1397 		sci_set_eol_mode(doc->editor->sci, editor_mode);
1398 		g_free(filedata.data);
1399 
1400 		sci_set_undo_collection(doc->editor->sci, TRUE);
1401 
1402 		/* If reloading and the current and new encodings or BOM states differ,
1403 		 * add appropriate undo actions. */
1404 		if (undo_reload_data)
1405 		{
1406 			if (! utils_str_equal(doc->encoding, filedata.enc))
1407 				document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
1408 			if (doc->has_bom != filedata.bom)
1409 				document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
1410 		}
1411 
1412 		doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1413 		g_free(doc->encoding);	/* if reloading, free old encoding */
1414 		doc->encoding = filedata.enc;
1415 		doc->has_bom = filedata.bom;
1416 		store_saved_encoding(doc);	/* store the opened encoding for undo/redo */
1417 
1418 		doc->readonly = readonly || filedata.readonly;
1419 		sci_set_readonly(doc->editor->sci, doc->readonly);
1420 		doc->priv->protected = 0;
1421 
1422 		/* update line number margin width */
1423 		doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1424 		sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1425 
1426 		if (! reload)
1427 		{
1428 
1429 			/* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1430 			g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1431 				doc->editor);
1432 
1433 			use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1434 		}
1435 		else
1436 		{	/* reloading */
1437 			if (undo_reload_data)
1438 			{
1439 				/* Calculate the number of undo actions that are part of the reloading
1440 				 * process, and add the UNDO_RELOAD action. */
1441 				undo_reload_data->actions_count =
1442 					g_trash_stack_height(&doc->priv->undo_actions) - undo_reload_data->actions_count;
1443 
1444 				/* We only add an undo-reload action if the document has actually changed.
1445 				 * At the time of writing, this condition is moot because sci_set_text
1446 				 * generates an undo action even when the text hasn't really changed, so
1447 				 * actions_count is always greater than zero. In the future this might change.
1448 				 * It's arguable whether we should add an undo-reload action unconditionally,
1449 				 * especially since it's possible (if unlikely) that there had only
1450 				 * been "invisible" changes to the document, such as changes in encoding and
1451 				 * EOL mode, but for the time being that's how we roll. */
1452 				if (undo_reload_data->actions_count > 0 || add_undo_reload_action)
1453 					document_undo_add(doc, UNDO_RELOAD, undo_reload_data);
1454 				else
1455 					g_free(undo_reload_data);
1456 
1457 				/* We didn't save the document per-se, but its contents are now
1458 				 * synchronized with the file on disk, hence set a save point here.
1459 				 * We need to do this in this case only, because we don't clear
1460 				 * Scintilla's undo stack. */
1461 				sci_set_savepoint(doc->editor->sci);
1462 			}
1463 			else
1464 				document_undo_clear(doc);
1465 
1466 			use_ft = ft;
1467 		}
1468 		/* update taglist, typedef keywords and build menu if necessary */
1469 		document_set_filetype(doc, use_ft);
1470 
1471 		/* set indentation settings after setting the filetype */
1472 		if (reload)
1473 			editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1474 		else
1475 			document_apply_indent_settings(doc);
1476 
1477 		document_set_text_changed(doc, FALSE);	/* also updates tab state */
1478 		ui_document_show_hide(doc);	/* update the document menu */
1479 
1480 		/* finally add current file to recent files menu, but not the files from the last session */
1481 		if (! main_status.opening_session_files)
1482 			ui_add_recent_document(doc);
1483 
1484 		if (reload)
1485 		{
1486 			g_signal_emit_by_name(geany_object, "document-reload", doc);
1487 			ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1488 		}
1489 		else
1490 		{
1491 			g_signal_emit_by_name(geany_object, "document-open", doc);
1492 			/* For translators: this is the status window message for opening a file. %d is the number
1493 			 * of the newly opened file, %s indicates whether the file is opened read-only
1494 			 * (it is replaced with the string ", read-only"). */
1495 			msgwin_status_add(_("File %s opened (%d%s)."),
1496 				display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1497 				(readonly) ? _(", read-only") : "");
1498 		}
1499 
1500 		/* now the document is fully ready, display it (see notebook_new_tab()) */
1501 		gtk_widget_show(document_get_notebook_child(doc));
1502 	}
1503 
1504 	g_free(display_filename);
1505 	g_free(utf8_filename);
1506 	g_free(locale_filename);
1507 
1508 	/* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1509 	pos = set_cursor_position(doc->editor, pos);
1510 	/* now bring the file in front */
1511 	editor_goto_pos(doc->editor, pos, FALSE);
1512 
1513 	/* finally, let the editor widget grab the focus so you can start coding
1514 	 * right away */
1515 	g_idle_add(on_idle_focus, doc);
1516 	return doc;
1517 }
1518 
1519 
1520 /* Takes a new line separated list of filename URIs and opens each file.
1521  * length is the length of the string */
document_open_file_list(const gchar * data,gsize length)1522 void document_open_file_list(const gchar *data, gsize length)
1523 {
1524 	guint i;
1525 	gchar **list;
1526 
1527 	g_return_if_fail(data != NULL);
1528 
1529 	list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1530 
1531 	/* stop at the end or first empty item, because last item is empty but not null */
1532 	for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1533 	{
1534 		gchar *filename = utils_get_path_from_uri(list[i]);
1535 
1536 		if (filename == NULL)
1537 			continue;
1538 		document_open_file(filename, FALSE, NULL, NULL);
1539 		g_free(filename);
1540 	}
1541 
1542 	g_strfreev(list);
1543 }
1544 
1545 
1546 /**
1547  *  Opens each file in the list @a filenames.
1548  *  Internally, document_open_file() is called for every list item.
1549  *
1550  *  @param filenames @elementtype{filename} A list of filenames to load, in locale encoding.
1551  *  @param readonly Whether to open the document in read-only mode.
1552  *  @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
1553  *  @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1554  **/
1555 GEANY_API_SYMBOL
document_open_files(const GSList * filenames,gboolean readonly,GeanyFiletype * ft,const gchar * forced_enc)1556 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1557 		const gchar *forced_enc)
1558 {
1559 	const GSList *item;
1560 
1561 	for (item = filenames; item != NULL; item = g_slist_next(item))
1562 	{
1563 		document_open_file(item->data, readonly, ft, forced_enc);
1564 	}
1565 }
1566 
1567 
on_keep_edit_history_on_reload_response(GtkWidget * bar,gint response_id,GeanyDocument * doc)1568 static void on_keep_edit_history_on_reload_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
1569 {
1570 	if (response_id == GTK_RESPONSE_NO)
1571 	{
1572 		file_prefs.keep_edit_history_on_reload = FALSE;
1573 		document_reload_force(doc, doc->encoding);
1574 	}
1575 	else if (response_id == GTK_RESPONSE_CANCEL)
1576 	{
1577 		/* this condition cannot be reached via info bar buttons, but by our code
1578 		 * to replace this bar with a higher priority one */
1579 		file_prefs.show_keep_edit_history_on_reload_msg = TRUE;
1580 	}
1581 	doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = NULL;
1582 	gtk_widget_destroy(bar);
1583 }
1584 
1585 
1586 /**
1587  *  Reloads the document with the specified file encoding.
1588  *  @a forced_enc or @c NULL to auto-detect the file encoding.
1589  *
1590  *  @param doc The document to reload.
1591  *  @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1592  *
1593  *  @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1594  **/
1595 GEANY_API_SYMBOL
document_reload_force(GeanyDocument * doc,const gchar * forced_enc)1596 gboolean document_reload_force(GeanyDocument *doc, const gchar *forced_enc)
1597 {
1598 	gint pos = 0;
1599 	GeanyDocument *new_doc;
1600 	GtkWidget *bar;
1601 
1602 	g_return_val_if_fail(doc != NULL, FALSE);
1603 
1604 	/* Cancel resave bar if still open from previous file deletion */
1605 	if (doc->priv->info_bars[MSG_TYPE_RESAVE] != NULL)
1606 		gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RESAVE]), GTK_RESPONSE_CANCEL);
1607 
1608 	/* Use cancel because the response handler would call this recursively */
1609 	if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1610 		gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1611 
1612 	/* try to set the cursor to the position before reloading */
1613 	pos = sci_get_current_position(doc->editor->sci);
1614 	new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1615 
1616 	if (file_prefs.keep_edit_history_on_reload && file_prefs.show_keep_edit_history_on_reload_msg)
1617 	{
1618 		bar = document_show_message(doc, GTK_MESSAGE_INFO,
1619 						on_keep_edit_history_on_reload_response,
1620 						GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1621 						_("Discard history"), GTK_RESPONSE_NO,
1622 						NULL, 0, _("The buffer's previous state is stored in the history and "
1623 						"undoing restores it. You can disable this by discarding the history upon "
1624 						"reload. This message will not be displayed again but "
1625 						"your choice can be changed in the various preferences."),
1626 						_("The file has been reloaded."));
1627 		doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = bar;
1628 		file_prefs.show_keep_edit_history_on_reload_msg = FALSE;
1629 	}
1630 
1631 	return (new_doc != NULL);
1632 }
1633 
1634 
1635 /* also used for reloading when forced_enc is NULL */
document_reload_prompt(GeanyDocument * doc,const gchar * forced_enc)1636 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1637 {
1638 	gchar *base_name;
1639 	gboolean prompt, result = FALSE;
1640 
1641 	g_return_val_if_fail(doc != NULL, FALSE);
1642 
1643 	/* No need to reload "untitled" (non-file-backed) documents */
1644 	if (doc->file_name == NULL)
1645 		return FALSE;
1646 
1647 	if (forced_enc == NULL)
1648 		forced_enc = doc->encoding;
1649 
1650 	base_name = g_path_get_basename(doc->file_name);
1651 	/* don't prompt if edit history is maintained, or if file hasn't been edited at all */
1652 	prompt = !file_prefs.keep_edit_history_on_reload &&
1653 			(doc->changed || (document_can_undo(doc) || document_can_redo(doc)));
1654 
1655 	if (!prompt || dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1656 		doc->changed ? _("Any unsaved changes will be lost.") :
1657 			_("Undo history will be lost."),
1658 		_("Are you sure you want to reload '%s'?"), base_name))
1659 	{
1660 		result = document_reload_force(doc, forced_enc);
1661 		if (forced_enc != NULL)
1662 			ui_update_statusbar(doc, -1);
1663 	}
1664 	g_free(base_name);
1665 	return result;
1666 }
1667 
1668 
document_update_timestamp(GeanyDocument * doc,const gchar * locale_filename)1669 static void document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1670 {
1671 #ifndef USE_GIO_FILEMON
1672 	g_return_if_fail(doc != NULL);
1673 
1674 	get_mtime(locale_filename, &doc->priv->mtime); /* get the modification time from file and keep it */
1675 #endif
1676 }
1677 
1678 
1679 /* Sets line and column to the given position byte_pos in the document.
1680  * byte_pos is the position counted in bytes, not characters */
get_line_column_from_pos(GeanyDocument * doc,guint byte_pos,gint * line,gint * column)1681 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1682 {
1683 	gint i;
1684 	gint line_start;
1685 
1686 	/* for some reason we can use byte count instead of character count here */
1687 	*line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1688 	line_start = sci_get_position_from_line(doc->editor->sci, *line);
1689 	/* get the column in the line */
1690 	*column = byte_pos - line_start;
1691 
1692 	/* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1693 	 * skip one byte(i++) and decrease the column number which is based on byte count */
1694 	for (i = line_start; i < (line_start + *column); i++)
1695 	{
1696 		if (sci_get_char_at(doc->editor->sci, i) < 0)
1697 		{
1698 			(*column)--;
1699 			i++;
1700 		}
1701 	}
1702 }
1703 
1704 
replace_header_filename(GeanyDocument * doc)1705 static void replace_header_filename(GeanyDocument *doc)
1706 {
1707 	gchar *filebase;
1708 	gchar *filename;
1709 	struct Sci_TextToFind ttf;
1710 
1711 	g_return_if_fail(doc != NULL);
1712 	g_return_if_fail(doc->file_type != NULL);
1713 
1714 	filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1715 	if (doc->file_type->extension)
1716 		SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1717 	else
1718 		SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1719 
1720 	filename = g_path_get_basename(doc->file_name);
1721 
1722 	/* only search the first 3 lines */
1723 	ttf.chrg.cpMin = 0;
1724 	ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1725 	ttf.lpstrText = filebase;
1726 
1727 	if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1728 	{
1729 		sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1730 		sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1731 		sci_replace_target(doc->editor->sci, filename, FALSE);
1732 	}
1733 	g_free(filebase);
1734 	g_free(filename);
1735 }
1736 
1737 
1738 /**
1739  *  Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1740  *  you still have to call @ref document_save_file_as() to change the @a doc object.
1741  *  It also stops monitoring for file changes to prevent receiving too many file change events
1742  *  while renaming. File monitoring is setup again in @ref document_save_file_as().
1743  *
1744  *  @param doc The current document which should be renamed.
1745  *  @param new_filename The new filename in UTF-8 encoding.
1746  *
1747  *  @since 0.16
1748  **/
1749 GEANY_API_SYMBOL
document_rename_file(GeanyDocument * doc,const gchar * new_filename)1750 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1751 {
1752 	gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1753 	gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1754 	gint result;
1755 
1756 	/* stop file monitoring to avoid getting events for deleting/creating files,
1757 	 * it's re-setup in document_save_file_as() */
1758 	document_stop_file_monitoring(doc);
1759 
1760 	result = g_rename(old_locale_filename, new_locale_filename);
1761 	if (result != 0)
1762 	{
1763 		dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1764 			_("Error renaming file."), g_strerror(errno));
1765 	}
1766 	g_free(old_locale_filename);
1767 	g_free(new_locale_filename);
1768 }
1769 
1770 
protect_document(GeanyDocument * doc)1771 static void protect_document(GeanyDocument *doc)
1772 {
1773 	/* do not call queue_colourise because to we want to keep the text-changed indication! */
1774 	if (!doc->priv->protected++)
1775 		sci_set_readonly(doc->editor->sci, TRUE);
1776 
1777 	ui_update_tab_status(doc);
1778 }
1779 
1780 
unprotect_document(GeanyDocument * doc)1781 static void unprotect_document(GeanyDocument *doc)
1782 {
1783 	g_return_if_fail(doc->priv->protected > 0);
1784 
1785 	if (!--doc->priv->protected && doc->readonly == FALSE)
1786 		sci_set_readonly(doc->editor->sci, FALSE);
1787 
1788 	ui_update_tab_status(doc);
1789 }
1790 
1791 
1792 /* Return TRUE if the document doesn't have a full filename set.
1793  * This makes filenames without a path show the save as dialog, e.g. for file templates.
1794  * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1795  * new files. */
document_need_save_as(GeanyDocument * doc)1796 gboolean document_need_save_as(GeanyDocument *doc)
1797 {
1798 	g_return_val_if_fail(doc != NULL, FALSE);
1799 
1800 	return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1801 }
1802 
1803 
1804 /**
1805  * Saves the document, detecting the filetype.
1806  *
1807  * @param doc The document for the file to save.
1808  * @param utf8_fname @nullable The new name for the document, in UTF-8, or @c NULL.
1809  * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1810  *
1811  * @see document_save_file().
1812  *
1813  *  @since 0.16
1814  **/
1815 GEANY_API_SYMBOL
document_save_file_as(GeanyDocument * doc,const gchar * utf8_fname)1816 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1817 {
1818 	gboolean ret;
1819 	gboolean new_file;
1820 
1821 	g_return_val_if_fail(doc != NULL, FALSE);
1822 
1823 	new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1824 	if (utf8_fname != NULL)
1825 		SETPTR(doc->file_name, g_strdup(utf8_fname));
1826 
1827 	/* reset real path, it's retrieved again in document_save() */
1828 	SETPTR(doc->real_path, NULL);
1829 
1830 	/* detect filetype */
1831 	if (doc->file_type->id == GEANY_FILETYPES_NONE)
1832 	{
1833 		GeanyFiletype *ft = filetypes_detect_from_document(doc);
1834 
1835 		document_set_filetype(doc, ft);
1836 		if (document_get_current() == doc)
1837 		{
1838 			ignore_callback = TRUE;
1839 			filetypes_select_radio_item(doc->file_type);
1840 			ignore_callback = FALSE;
1841 		}
1842 	}
1843 
1844 	if (new_file)
1845 	{
1846 		// assume user wants to throw away read-only setting
1847 		sci_set_readonly(doc->editor->sci, FALSE);
1848 		doc->readonly = FALSE;
1849 		if (doc->priv->protected > 0)
1850 			unprotect_document(doc);
1851 	}
1852 
1853 	replace_header_filename(doc);
1854 
1855 	ret = document_save_file(doc, TRUE);
1856 
1857 	/* file monitoring support, add file monitoring after the file has been saved
1858 	 * to ignore any earlier events */
1859 	monitor_file_setup(doc);
1860 	doc->priv->file_disk_status = FILE_IGNORE;
1861 
1862 	if (ret)
1863 		ui_add_recent_document(doc);
1864 	return ret;
1865 }
1866 
1867 
save_convert_to_encoding(GeanyDocument * doc,gchar ** data,gsize * len)1868 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1869 {
1870 	GError *conv_error = NULL;
1871 	gchar* conv_file_contents = NULL;
1872 	gsize bytes_read;
1873 	gsize conv_len;
1874 
1875 	g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1876 	g_return_val_if_fail(len != NULL, FALSE);
1877 
1878 	/* try to convert it from UTF-8 to original encoding */
1879 	conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1880 												&bytes_read, &conv_len, &conv_error);
1881 
1882 	if (conv_error != NULL)
1883 	{
1884 		gchar *text = g_strdup_printf(
1885 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1886 			doc->encoding);
1887 		gchar *error_text;
1888 
1889 		if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1890 		{
1891 			gint line, column;
1892 			gint context_len;
1893 			gunichar unic;
1894 			/* don't read over the doc length */
1895 			gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1896 			gchar context[7]; /* read 6 bytes from Sci + '\0' */
1897 			sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1898 
1899 			/* take only one valid Unicode character from the context and discard the leftover */
1900 			unic = g_utf8_get_char_validated(context, -1);
1901 			context_len = g_unichar_to_utf8(unic, context);
1902 			context[context_len] = '\0';
1903 			get_line_column_from_pos(doc, bytes_read, &line, &column);
1904 
1905 			error_text = g_strdup_printf(
1906 				_("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1907 				conv_error->message, context, line + 1, column);
1908 		}
1909 		else
1910 			error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1911 
1912 		geany_debug("encoding error: %s", conv_error->message);
1913 		dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1914 		g_error_free(conv_error);
1915 		g_free(text);
1916 		g_free(error_text);
1917 		return FALSE;
1918 	}
1919 	else
1920 	{
1921 		g_free(*data);
1922 		*data = conv_file_contents;
1923 		*len = conv_len;
1924 	}
1925 	return TRUE;
1926 }
1927 
1928 
write_data_to_disk(const gchar * locale_filename,const gchar * data,gsize len)1929 static gchar *write_data_to_disk(const gchar *locale_filename,
1930 								 const gchar *data, gsize len)
1931 {
1932 	GError *error = NULL;
1933 
1934 	if (file_prefs.use_safe_file_saving)
1935 	{
1936 		/* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1937 		 * This is the only option that handles disk space exhaustion. */
1938 		if (g_file_set_contents(locale_filename, data, len, &error))
1939 			geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1940 	}
1941 	else if (USE_GIO_FILE_OPERATIONS)
1942 	{
1943 		GFile *fp;
1944 
1945 		/* Use GIO API to save file (GVFS-safe)
1946 		 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1947 		 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1948 		fp = g_file_new_for_path(locale_filename);
1949 		g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1950 			G_FILE_CREATE_NONE, NULL, NULL, &error);
1951 		g_object_unref(fp);
1952 	}
1953 	else
1954 	{
1955 		FILE *fp;
1956 		int save_errno;
1957 		gchar *display_name = g_filename_display_name(locale_filename);
1958 
1959 		/* Use POSIX API for unsafe saving (GVFS-unsafe) */
1960 		/* The error handling is taken from glib-2.26.0 gfileutils.c */
1961 		errno = 0;
1962 		fp = g_fopen(locale_filename, "wb");
1963 		if (fp == NULL)
1964 		{
1965 			save_errno = errno;
1966 
1967 			g_set_error(&error,
1968 				G_FILE_ERROR,
1969 				g_file_error_from_errno(save_errno),
1970 				_("Failed to open file '%s' for writing: fopen() failed: %s"),
1971 				display_name,
1972 				g_strerror(save_errno));
1973 		}
1974 		else
1975 		{
1976 			gsize bytes_written;
1977 
1978 			errno = 0;
1979 			bytes_written = fwrite(data, sizeof(gchar), len, fp);
1980 
1981 			if (len != bytes_written)
1982 			{
1983 				save_errno = errno;
1984 
1985 				g_set_error(&error,
1986 					G_FILE_ERROR,
1987 					g_file_error_from_errno(save_errno),
1988 					_("Failed to write file '%s': fwrite() failed: %s"),
1989 					display_name,
1990 					g_strerror(save_errno));
1991 			}
1992 
1993 			errno = 0;
1994 			/* preserve the fwrite() error if any */
1995 			if (fclose(fp) != 0 && error == NULL)
1996 			{
1997 				save_errno = errno;
1998 
1999 				g_set_error(&error,
2000 					G_FILE_ERROR,
2001 					g_file_error_from_errno(save_errno),
2002 					_("Failed to close file '%s': fclose() failed: %s"),
2003 					display_name,
2004 					g_strerror(save_errno));
2005 			}
2006 		}
2007 
2008 		g_free(display_name);
2009 	}
2010 	if (error != NULL)
2011 	{
2012 		gchar *msg = g_strdup(error->message);
2013 		g_error_free(error);
2014 		/* geany will warn about file truncation for unsafe saving below */
2015 		return msg;
2016 	}
2017 	return NULL;
2018 }
2019 
2020 
save_doc(GeanyDocument * doc,const gchar * locale_filename,const gchar * data,gsize len)2021 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
2022 								 const gchar *data, gsize len)
2023 {
2024 	gchar *err;
2025 
2026 	g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
2027 	g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
2028 
2029 	err = write_data_to_disk(locale_filename, data, len);
2030 	if (err)
2031 		return err;
2032 
2033 	/* now the file is on disk, set real_path */
2034 	if (doc->real_path == NULL)
2035 	{
2036 		doc->real_path = utils_get_real_path(locale_filename);
2037 		doc->priv->is_remote = utils_is_remote_path(locale_filename);
2038 		monitor_file_setup(doc);
2039 	}
2040 	return NULL;
2041 }
2042 
2043 
save_file_handle_infobars(GeanyDocument * doc,gboolean force)2044 static gboolean save_file_handle_infobars(GeanyDocument *doc, gboolean force)
2045 {
2046 	GtkWidget *bar = NULL;
2047 
2048 	document_show_tab(doc);
2049 
2050 	if (doc->priv->info_bars[MSG_TYPE_RELOAD])
2051 	{
2052 		if (!dialogs_show_question_full(NULL, _("_Overwrite"), GTK_STOCK_CANCEL,
2053 			_("Overwrite?"),
2054 			_("The file '%s' on the disk is more recent than the current buffer."),
2055 			doc->file_name))
2056 			return FALSE;
2057 		bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
2058 	}
2059 	else if (doc->priv->info_bars[MSG_TYPE_RESAVE])
2060 	{
2061 		if (!dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
2062 			_("Try to resave the file?"),
2063 			_("File \"%s\" was not found on disk!"),
2064 			doc->file_name))
2065 			return FALSE;
2066 		bar = doc->priv->info_bars[MSG_TYPE_RESAVE];
2067 	}
2068 	else
2069 	{
2070 		g_assert_not_reached();
2071 		return FALSE;
2072 	}
2073 	gtk_info_bar_response(GTK_INFO_BAR(bar), RESPONSE_DOCUMENT_SAVE);
2074 	return TRUE;
2075 }
2076 
2077 
2078 /**
2079  *  Saves the document.
2080  *  Also shows the Save As dialog if necessary.
2081  *  If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
2082  *
2083  *  Saving may include replacing tabs with spaces,
2084  *  stripping trailing spaces and adding a final new line at the end of the file, depending
2085  *  on user preferences. Then the @c "document-before-save" signal is emitted,
2086  *  allowing plugins to modify the document before it is saved, and data is
2087  *  actually written to disk.
2088  *
2089  *  On successful saving:
2090  *  - GeanyDocument::real_path is set.
2091  *  - The filetype is set again or auto-detected if it wasn't set yet.
2092  *  - The @c "document-save" signal is emitted for plugins.
2093  *
2094  *  @warning You should ensure @c doc->file_name has an absolute path unless you want the
2095  *  Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
2096  *  added in Geany 1.22.
2097  *
2098  *  @param doc The document to save.
2099  *  @param force Whether to save the file even if it is not modified.
2100  *
2101  *  @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
2102  **/
2103 GEANY_API_SYMBOL
document_save_file(GeanyDocument * doc,gboolean force)2104 gboolean document_save_file(GeanyDocument *doc, gboolean force)
2105 {
2106 	gchar *errmsg;
2107 	gchar *data;
2108 	gsize len;
2109 	gchar *locale_filename;
2110 	const GeanyFilePrefs *fp;
2111 
2112 	g_return_val_if_fail(doc != NULL, FALSE);
2113 
2114 	if (document_need_save_as(doc))
2115 	{
2116 		/* ensure doc is the current tab before showing the dialog */
2117 		document_show_tab(doc);
2118 		return dialogs_show_save_as();
2119 	}
2120 
2121 	if (!force && !doc->changed)
2122 		return FALSE;
2123 	if (doc->readonly)
2124 	{
2125 		ui_set_statusbar(TRUE,
2126 			_("Cannot save read-only document '%s'!"), DOC_FILENAME(doc));
2127 		return FALSE;
2128 	}
2129 	document_check_disk_status(doc, TRUE);
2130 	if (doc->priv->protected)
2131 		return save_file_handle_infobars(doc, force);
2132 
2133 	fp = project_get_file_prefs();
2134 	/* replaces tabs with spaces but only if the current file is not a Makefile */
2135 	if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
2136 		editor_replace_tabs(doc->editor, TRUE);
2137 	/* strip trailing spaces */
2138 	if (fp->strip_trailing_spaces)
2139 		editor_strip_trailing_spaces(doc->editor, TRUE);
2140 	/* ensure the file has a newline at the end */
2141 	if (fp->final_new_line)
2142 		editor_ensure_final_newline(doc->editor);
2143 	/* ensure newlines are consistent */
2144 	if (fp->ensure_convert_new_lines)
2145 		sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
2146 
2147 	/* notify plugins which may wish to modify the document before it's saved */
2148 	g_signal_emit_by_name(geany_object, "document-before-save", doc);
2149 
2150 	len = sci_get_length(doc->editor->sci) + 1;
2151 	if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
2152 	{	/* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
2153 		 * encoding, it will be converted to doc->encoding below and this conversion
2154 		 * also changes the BOM */
2155 		data = (gchar*) g_malloc(len + 3);	/* 3 chars for BOM */
2156 		data[0] = (gchar) 0xef;
2157 		data[1] = (gchar) 0xbb;
2158 		data[2] = (gchar) 0xbf;
2159 		sci_get_text(doc->editor->sci, len, data + 3);
2160 		len += 3;
2161 	}
2162 	else
2163 	{
2164 		data = (gchar*) g_malloc(len);
2165 		sci_get_text(doc->editor->sci, len, data);
2166 	}
2167 
2168 	/* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
2169 	if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
2170 		! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
2171 	{
2172 		if (! save_convert_to_encoding(doc, &data, &len))
2173 		{
2174 			g_free(data);
2175 			return FALSE;
2176 		}
2177 	}
2178 	else
2179 	{
2180 		len = strlen(data);
2181 	}
2182 
2183 	locale_filename = utils_get_locale_from_utf8(doc->file_name);
2184 
2185 	/* ignore file changed notification when the file is written */
2186 	doc->priv->file_disk_status = FILE_IGNORE;
2187 
2188 	/* actually write the content of data to the file on disk */
2189 	errmsg = save_doc(doc, locale_filename, data, len);
2190 	g_free(data);
2191 
2192 	if (errmsg != NULL)
2193 	{
2194 		ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
2195 
2196 		if (!file_prefs.use_safe_file_saving)
2197 		{
2198 			SETPTR(errmsg,
2199 				g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
2200 		}
2201 		dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
2202 		doc->priv->file_disk_status = FILE_OK;
2203 		utils_beep();
2204 		g_free(locale_filename);
2205 		g_free(errmsg);
2206 		return FALSE;
2207 	}
2208 
2209 	/* store the opened encoding for undo/redo */
2210 	store_saved_encoding(doc);
2211 
2212 	/* ignore the following things if we are quitting */
2213 	if (! main_status.quitting)
2214 	{
2215 		sci_set_savepoint(doc->editor->sci);
2216 
2217 		if (file_prefs.disk_check_timeout > 0)
2218 			document_update_timestamp(doc, locale_filename);
2219 
2220 		/* update filetype-related things */
2221 		document_set_filetype(doc, doc->file_type);
2222 
2223 		document_update_tab_label(doc);
2224 
2225 		msgwin_status_add(_("File %s saved."), doc->file_name);
2226 		ui_update_statusbar(doc, -1);
2227 #ifdef HAVE_VTE
2228 		vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
2229 #endif
2230 	}
2231 	g_free(locale_filename);
2232 
2233 	g_signal_emit_by_name(geany_object, "document-save", doc);
2234 
2235 	return TRUE;
2236 }
2237 
2238 
2239 /* special search function, used from the find entry in the toolbar
2240  * return TRUE if text was found otherwise FALSE
2241  * return also TRUE if text is empty  */
document_search_bar_find(GeanyDocument * doc,const gchar * text,gboolean inc,gboolean backwards)2242 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gboolean inc,
2243 		gboolean backwards)
2244 {
2245 	gint start_pos, search_pos;
2246 	struct Sci_TextToFind ttf;
2247 
2248 	g_return_val_if_fail(text != NULL, FALSE);
2249 	g_return_val_if_fail(doc != NULL, FALSE);
2250 	if (! *text)
2251 		return TRUE;
2252 
2253 	start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
2254 		sci_get_selection_end(doc->editor->sci);	/* equal if no selection */
2255 
2256 	/* search cursor to end or start */
2257 	ttf.chrg.cpMin = start_pos;
2258 	ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
2259 	ttf.lpstrText = (gchar *)text;
2260 	search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2261 
2262 	/* if no match, search start (or end) to cursor */
2263 	if (search_pos == -1)
2264 	{
2265 		if (backwards)
2266 		{
2267 			ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
2268 			ttf.chrg.cpMax = start_pos;
2269 		}
2270 		else
2271 		{
2272 			ttf.chrg.cpMin = 0;
2273 			ttf.chrg.cpMax = start_pos + strlen(text);
2274 		}
2275 		search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2276 	}
2277 
2278 	if (search_pos != -1)
2279 	{
2280 		gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
2281 
2282 		/* unfold maybe folded results */
2283 		sci_ensure_line_is_visible(doc->editor->sci, line);
2284 
2285 		sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2286 		sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2287 
2288 		if (! editor_line_in_view(doc->editor, line))
2289 		{	/* we need to force scrolling in case the cursor is outside of the current visible area
2290 			 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2291 			 * while searching */
2292 			editor_scroll_to_line(doc->editor, -1, 0.3F);
2293 		}
2294 		else
2295 			sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2296 		return TRUE;
2297 	}
2298 	else
2299 	{
2300 		if (! inc)
2301 		{
2302 			ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2303 		}
2304 		utils_beep();
2305 		sci_goto_pos(doc->editor->sci, start_pos, FALSE);	/* clear selection */
2306 		return FALSE;
2307 	}
2308 }
2309 
2310 
2311 /* General search function, used from the find dialog.
2312  * Returns -1 on failure or the start position of the matching text.
2313  * Will skip past any selection, ignoring it.
2314  *
2315  * @param text Text to find.
2316  * @param original_text Text as it was entered by user, or @c NULL to use @c text
2317  */
document_find_text(GeanyDocument * doc,const gchar * text,const gchar * original_text,GeanyFindFlags flags,gboolean search_backwards,GeanyMatchInfo ** match_,gboolean scroll,GtkWidget * parent)2318 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2319 		GeanyFindFlags flags, gboolean search_backwards, GeanyMatchInfo **match_,
2320 		gboolean scroll, GtkWidget *parent)
2321 {
2322 	gint selection_end, selection_start, search_pos;
2323 
2324 	g_return_val_if_fail(doc != NULL && text != NULL, -1);
2325 	if (! *text)
2326 		return -1;
2327 
2328 	/* Sci doesn't support searching backwards with a regex */
2329 	if (flags & GEANY_FIND_REGEXP)
2330 		search_backwards = FALSE;
2331 
2332 	if (!original_text)
2333 		original_text = text;
2334 
2335 	selection_start = sci_get_selection_start(doc->editor->sci);
2336 	selection_end = sci_get_selection_end(doc->editor->sci);
2337 	if ((selection_end - selection_start) > 0)
2338 	{ /* there's a selection so go to the end */
2339 		if (search_backwards)
2340 			sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2341 		else
2342 			sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2343 	}
2344 
2345 	sci_set_search_anchor(doc->editor->sci);
2346 	if (search_backwards)
2347 		search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2348 	else
2349 		search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2350 
2351 	if (search_pos != -1)
2352 	{
2353 		/* unfold maybe folded results */
2354 		sci_ensure_line_is_visible(doc->editor->sci,
2355 			sci_get_line_from_position(doc->editor->sci, search_pos));
2356 		if (scroll)
2357 			doc->editor->scroll_percent = 0.3F;
2358 	}
2359 	else
2360 	{
2361 		gint sci_len = sci_get_length(doc->editor->sci);
2362 
2363 		/* if we just searched the whole text, give up searching. */
2364 		if ((selection_end == 0 && ! search_backwards) ||
2365 			(selection_end == sci_len && search_backwards))
2366 		{
2367 			ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2368 			utils_beep();
2369 			return -1;
2370 		}
2371 
2372 		/* we searched only part of the document, so ask whether to wraparound. */
2373 		if (search_prefs.always_wrap ||
2374 			dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2375 				_("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2376 		{
2377 			gint ret;
2378 
2379 			sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2380 			ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2381 			if (ret == -1)
2382 			{	/* return to original cursor position if not found */
2383 				sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2384 			}
2385 			return ret;
2386 		}
2387 	}
2388 	return search_pos;
2389 }
2390 
2391 
2392 /* Replaces the selection if it matches, otherwise just finds the next match.
2393  * Returns: start of replaced text, or -1 if no replacement was made
2394  *
2395  * @param find_text Text to find.
2396  * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2397  */
document_replace_text(GeanyDocument * doc,const gchar * find_text,const gchar * original_find_text,const gchar * replace_text,GeanyFindFlags flags,gboolean search_backwards)2398 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2399 		const gchar *replace_text, GeanyFindFlags flags, gboolean search_backwards)
2400 {
2401 	gint selection_end, selection_start, search_pos;
2402 	GeanyMatchInfo *match = NULL;
2403 
2404 	g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2405 
2406 	if (! *find_text)
2407 		return -1;
2408 
2409 	/* Sci doesn't support searching backwards with a regex */
2410 	if (flags & GEANY_FIND_REGEXP)
2411 		search_backwards = FALSE;
2412 
2413 	if (!original_find_text)
2414 		original_find_text = find_text;
2415 
2416 	selection_start = sci_get_selection_start(doc->editor->sci);
2417 	selection_end = sci_get_selection_end(doc->editor->sci);
2418 	if (selection_end == selection_start)
2419 	{
2420 		/* no selection so just find the next match */
2421 		document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2422 		return -1;
2423 	}
2424 	/* there's a selection so go to the start before finding to search through it
2425 	 * this ensures there is a match */
2426 	if (search_backwards)
2427 		sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2428 	else
2429 		sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2430 
2431 	search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2432 	/* return if the original selected text did not match (at the start of the selection) */
2433 	if (search_pos != selection_start)
2434 	{
2435 		if (search_pos != -1)
2436 			geany_match_info_free(match);
2437 		return -1;
2438 	}
2439 
2440 	if (search_pos != -1)
2441 	{
2442 		gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2443 		/* select the replacement - find text will skip past the selected text */
2444 		sci_set_selection_start(doc->editor->sci, search_pos);
2445 		sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2446 		geany_match_info_free(match);
2447 	}
2448 	else
2449 	{
2450 		/* no match in the selection */
2451 		utils_beep();
2452 	}
2453 	return search_pos;
2454 }
2455 
2456 
show_replace_summary(GeanyDocument * doc,gint count,const gchar * original_find_text,const gchar * original_replace_text)2457 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2458 	const gchar *original_replace_text)
2459 {
2460 	gchar *filename;
2461 
2462 	if (count == 0)
2463 	{
2464 		ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2465 		return;
2466 	}
2467 
2468 	filename = g_path_get_basename(DOC_FILENAME(doc));
2469 	ui_set_statusbar(TRUE, ngettext(
2470 		"%s: replaced %d occurrence of \"%s\" with \"%s\".",
2471 		"%s: replaced %d occurrences of \"%s\" with \"%s\".",
2472 		count), filename, count, original_find_text, original_replace_text);
2473 	g_free(filename);
2474 }
2475 
2476 
2477 /* Replace all text matches in a certain range within document.
2478  * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2479  * or -1 if no text was found.
2480  * scroll_to_match is whether to scroll the last replacement in view (which also
2481  * clears the selection).
2482  * Returns: the number of replacements made. */
2483 static guint
document_replace_range(GeanyDocument * doc,const gchar * find_text,const gchar * replace_text,GeanyFindFlags flags,gint start,gint end,gboolean scroll_to_match,gint * new_range_end)2484 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2485 	GeanyFindFlags flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2486 {
2487 	gint count = 0;
2488 	struct Sci_TextToFind ttf;
2489 	ScintillaObject *sci;
2490 
2491 	if (new_range_end != NULL)
2492 		*new_range_end = -1;
2493 
2494 	g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2495 
2496 	if (! *find_text || doc->readonly)
2497 		return 0;
2498 
2499 	sci = doc->editor->sci;
2500 
2501 	ttf.chrg.cpMin = start;
2502 	ttf.chrg.cpMax = end;
2503 	ttf.lpstrText = (gchar*)find_text;
2504 
2505 	sci_start_undo_action(sci);
2506 	count = search_replace_range(sci, &ttf, flags, replace_text);
2507 	sci_end_undo_action(sci);
2508 
2509 	if (count > 0)
2510 	{	/* scroll last match in view, will destroy the existing selection */
2511 		if (scroll_to_match)
2512 			sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2513 
2514 		if (new_range_end != NULL)
2515 			*new_range_end = ttf.chrg.cpMax;
2516 	}
2517 	return count;
2518 }
2519 
2520 
document_replace_sel(GeanyDocument * doc,const gchar * find_text,const gchar * replace_text,const gchar * original_find_text,const gchar * original_replace_text,GeanyFindFlags flags)2521 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2522 						  const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2523 {
2524 	gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2525 	gint max_column = 0, count = 0;
2526 	gboolean replaced = FALSE;
2527 
2528 	g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2529 
2530 	if (! *find_text)
2531 		return;
2532 
2533 	selection_start = sci_get_selection_start(doc->editor->sci);
2534 	selection_end = sci_get_selection_end(doc->editor->sci);
2535 	/* do we have a selection? */
2536 	if ((selection_end - selection_start) == 0)
2537 	{
2538 		utils_beep();
2539 		return;
2540 	}
2541 
2542 	selection_mode = sci_get_selection_mode(doc->editor->sci);
2543 	selected_lines = sci_get_lines_selected(doc->editor->sci);
2544 	/* handle rectangle, multi line selections (it doesn't matter on a single line) */
2545 	if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2546 	{
2547 		gint first_line, line;
2548 
2549 		sci_start_undo_action(doc->editor->sci);
2550 
2551 		first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2552 		/* Find the last line with chars selected (not EOL char) */
2553 		last_line = sci_get_line_from_position(doc->editor->sci,
2554 			selection_end - editor_get_eol_char_len(doc->editor));
2555 		last_line = MAX(first_line, last_line);
2556 		for (line = first_line; line < (first_line + selected_lines); line++)
2557 		{
2558 			gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2559 			gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2560 
2561 			/* skip line if there is no selection */
2562 			if (line_start != INVALID_POSITION)
2563 			{
2564 				/* don't let document_replace_range() scroll to match to keep our selection */
2565 				gint new_sel_end;
2566 
2567 				count += document_replace_range(doc, find_text, replace_text, flags,
2568 								line_start, line_end, FALSE, &new_sel_end);
2569 				if (new_sel_end != -1)
2570 				{
2571 					replaced = TRUE;
2572 					/* this gets the greatest column within the selection after replacing */
2573 					max_column = MAX(max_column,
2574 						new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2575 				}
2576 			}
2577 		}
2578 		sci_end_undo_action(doc->editor->sci);
2579 	}
2580 	else	/* handle normal line selection */
2581 	{
2582 		count += document_replace_range(doc, find_text, replace_text, flags,
2583 						selection_start, selection_end, TRUE, &selection_end);
2584 		if (selection_end != -1)
2585 			replaced = TRUE;
2586 	}
2587 
2588 	if (replaced)
2589 	{	/* update the selection for the new endpoint */
2590 
2591 		if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2592 		{
2593 			/* now we can scroll to the selection and destroy it because we rebuild it later */
2594 			/*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2595 
2596 			/* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2597 			 * the highest column on the last line. The wrapped selection is completely different
2598 			 * from the original one, so skip the selection at all */
2599 			/* TODO is there a better way to handle the wrapped selection? */
2600 			if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2601 			{	/* for keeping and adjusting the selection in multi line rectangle selection we
2602 				 * need the last line of the original selection and the greatest column number after
2603 				 * replacing and set the selection end to the last line at the greatest column */
2604 				sci_set_selection_start(doc->editor->sci, selection_start);
2605 				sci_set_selection_end(doc->editor->sci,
2606 					sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2607 				sci_set_selection_mode(doc->editor->sci, selection_mode);
2608 			}
2609 		}
2610 		else
2611 		{
2612 			sci_set_selection_start(doc->editor->sci, selection_start);
2613 			sci_set_selection_end(doc->editor->sci, selection_end);
2614 		}
2615 	}
2616 	else /* no replacements */
2617 		utils_beep();
2618 
2619 	show_replace_summary(doc, count, original_find_text, original_replace_text);
2620 }
2621 
2622 
2623 /* returns number of replacements made. */
document_replace_all(GeanyDocument * doc,const gchar * find_text,const gchar * replace_text,const gchar * original_find_text,const gchar * original_replace_text,GeanyFindFlags flags)2624 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2625 		const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2626 {
2627 	gint len, count;
2628 	g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2629 
2630 	if (! *find_text)
2631 		return FALSE;
2632 
2633 	len = sci_get_length(doc->editor->sci);
2634 	count = document_replace_range(
2635 			doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2636 
2637 	show_replace_summary(doc, count, original_find_text, original_replace_text);
2638 	return count;
2639 }
2640 
2641 
2642 /*
2643  * Parses or re-parses the document's buffer and updates the type
2644  * keywords and symbol list.
2645  *
2646  * @param doc The document.
2647  */
document_update_tags(GeanyDocument * doc)2648 void document_update_tags(GeanyDocument *doc)
2649 {
2650 	guchar *buffer_ptr;
2651 	gsize len;
2652 
2653 	g_return_if_fail(DOC_VALID(doc));
2654 	g_return_if_fail(app->tm_workspace != NULL);
2655 
2656 	/* early out if it's a new file or doesn't support tags */
2657 	if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2658 	{
2659 		/* We must call sidebar_update_tag_list() before returning,
2660 		 * to ensure that the symbol list is always updated properly (e.g.
2661 		 * when creating a new document with a partial filename set. */
2662 		sidebar_update_tag_list(doc, FALSE);
2663 		return;
2664 	}
2665 
2666 	/* create a new TM file if there isn't one yet */
2667 	if (! doc->tm_file)
2668 	{
2669 		gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2670 		const gchar *name;
2671 
2672 		/* lookup the name rather than using filetype name to support custom filetypes */
2673 		name = tm_source_file_get_lang_name(doc->file_type->lang);
2674 		doc->tm_file = tm_source_file_new(locale_filename, name);
2675 		g_free(locale_filename);
2676 
2677 		if (doc->tm_file)
2678 			tm_workspace_add_source_file_noupdate(doc->tm_file);
2679 	}
2680 
2681 	/* early out if there's no tm source file and we couldn't create one */
2682 	if (doc->tm_file == NULL)
2683 	{
2684 		/* We must call sidebar_update_tag_list() before returning,
2685 		 * to ensure that the symbol list is always updated properly (e.g.
2686 		 * when creating a new document with a partial filename set. */
2687 		sidebar_update_tag_list(doc, FALSE);
2688 		return;
2689 	}
2690 
2691 	/* Parse Scintilla's buffer directly using TagManager
2692 	 * Note: this buffer *MUST NOT* be modified */
2693 	len = sci_get_length(doc->editor->sci);
2694 	buffer_ptr = (guchar *) SSM(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2695 	tm_workspace_update_source_file_buffer(doc->tm_file, buffer_ptr, len);
2696 
2697 	sidebar_update_tag_list(doc, TRUE);
2698 	document_highlight_tags(doc);
2699 }
2700 
2701 
2702 /* Re-highlights type keywords without re-parsing the whole document. */
document_highlight_tags(GeanyDocument * doc)2703 void document_highlight_tags(GeanyDocument *doc)
2704 {
2705 	GString *keywords_str;
2706 	gint keyword_idx;
2707 
2708 	/* some filetypes support type keywords (such as struct names), but not
2709 	 * necessarily all filetypes for a particular scintilla lexer.  this
2710 	 * tells us whether the filetype supports keywords, and if so
2711 	 * which index to use for the scintilla keywords set. */
2712 	switch (doc->file_type->id)
2713 	{
2714 		case GEANY_FILETYPES_C:
2715 		case GEANY_FILETYPES_CPP:
2716 		case GEANY_FILETYPES_CS:
2717 		case GEANY_FILETYPES_D:
2718 		case GEANY_FILETYPES_JAVA:
2719 		case GEANY_FILETYPES_OBJECTIVEC:
2720 		case GEANY_FILETYPES_VALA:
2721 		case GEANY_FILETYPES_RUST:
2722 		case GEANY_FILETYPES_GO:
2723 		{
2724 
2725 			/* index of the keyword set in the Scintilla lexer, for
2726 			 * example in LexCPP.cxx, see "cppWordLists" global array.
2727 			 * TODO: this magic number should be a member of the filetype */
2728 			keyword_idx = 3;
2729 			break;
2730 		}
2731 		default:
2732 			return; /* early out if type keywords are not supported */
2733 	}
2734 	if (!app->tm_workspace->tags_array)
2735 		return;
2736 
2737 	/* get any type keywords and tell scintilla about them
2738 	 * this will cause the type keywords to be colourized in scintilla */
2739 	keywords_str = symbols_find_typenames_as_string(doc->file_type->lang, FALSE);
2740 	if (keywords_str)
2741 	{
2742 		gchar *keywords = g_string_free(keywords_str, FALSE);
2743 		guint hash = g_str_hash(keywords);
2744 
2745 		if (hash != doc->priv->keyword_hash)
2746 		{
2747 			sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2748 			queue_colourise(doc); /* force re-highlighting the entire document */
2749 			doc->priv->keyword_hash = hash;
2750 		}
2751 		g_free(keywords);
2752 	}
2753 }
2754 
2755 
on_document_update_tag_list_idle(gpointer data)2756 static gboolean on_document_update_tag_list_idle(gpointer data)
2757 {
2758 	GeanyDocument *doc = data;
2759 
2760 	if (! DOC_VALID(doc))
2761 		return FALSE;
2762 
2763 	if (! main_status.quitting)
2764 		document_update_tags(doc);
2765 
2766 	doc->priv->tag_list_update_source = 0;
2767 
2768 	/* don't update the tags until another modification of the buffer */
2769 	return FALSE;
2770 }
2771 
2772 
document_update_tag_list_in_idle(GeanyDocument * doc)2773 void document_update_tag_list_in_idle(GeanyDocument *doc)
2774 {
2775 	if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2776 		return;
2777 
2778 	/* prevent "stacking up" callback handlers, we only need one to run soon */
2779 	if (doc->priv->tag_list_update_source != 0)
2780 		g_source_remove(doc->priv->tag_list_update_source);
2781 
2782 	doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2783 		editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2784 }
2785 
2786 
document_load_config(GeanyDocument * doc,GeanyFiletype * type,gboolean filetype_changed)2787 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2788 		gboolean filetype_changed)
2789 {
2790 	g_return_if_fail(doc);
2791 	if (type == NULL)
2792 		type = filetypes[GEANY_FILETYPES_NONE];
2793 
2794 	if (filetype_changed)
2795 	{
2796 		doc->file_type = type;
2797 
2798 		/* delete tm file object to force creation of a new one */
2799 		if (doc->tm_file != NULL)
2800 		{
2801 			tm_workspace_remove_source_file(doc->tm_file);
2802 			tm_source_file_free(doc->tm_file);
2803 			doc->tm_file = NULL;
2804 		}
2805 		/* load tags files before highlighting (some lexers highlight global typenames) */
2806 		if (type->id != GEANY_FILETYPES_NONE)
2807 			symbols_global_tags_loaded(type->id);
2808 
2809 		highlighting_set_styles(doc->editor->sci, type);
2810 		editor_set_indentation_guides(doc->editor);
2811 		build_menu_update(doc);
2812 		queue_colourise(doc);
2813 		if (type->priv->symbol_list_sort_mode == SYMBOLS_SORT_USE_PREVIOUS)
2814 			doc->priv->symbol_list_sort_mode = interface_prefs.symbols_sort_mode;
2815 		else
2816 			doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2817 	}
2818 
2819 	document_update_tags(doc);
2820 }
2821 
2822 
2823 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2824  * @param doc The document to use.
2825  * @param type The filetype. */
2826 GEANY_API_SYMBOL
document_set_filetype(GeanyDocument * doc,GeanyFiletype * type)2827 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2828 {
2829 	gboolean ft_changed;
2830 	GeanyFiletype *old_ft;
2831 
2832 	g_return_if_fail(doc);
2833 	if (type == NULL)
2834 		type = filetypes[GEANY_FILETYPES_NONE];
2835 
2836 	old_ft = doc->file_type;
2837 	geany_debug("%s : %s (%s)",
2838 		(doc->file_name != NULL) ? doc->file_name : "unknown",
2839 		type->name,
2840 		(doc->encoding != NULL) ? doc->encoding : "unknown");
2841 
2842 	ft_changed = (doc->file_type != type); /* filetype has changed */
2843 	document_load_config(doc, type, ft_changed);
2844 
2845 	if (ft_changed)
2846 	{
2847 		const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2848 
2849 		/* assume that if previous filetype was none and the settings are the default ones, this
2850 		 * is the first time the filetype is carefully set, so we should apply indent settings */
2851 		if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2852 			doc->editor->indent_type == iprefs->type &&
2853 			doc->editor->indent_width == iprefs->width)
2854 		{
2855 			document_apply_indent_settings(doc);
2856 			ui_document_show_hide(doc);
2857 		}
2858 
2859 		sidebar_openfiles_update(doc); /* to update the icon */
2860 		g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2861 	}
2862 }
2863 
2864 
document_reload_config(GeanyDocument * doc)2865 void document_reload_config(GeanyDocument *doc)
2866 {
2867 	document_load_config(doc, doc->file_type, TRUE);
2868 }
2869 
2870 
2871 /**
2872  *  Sets the encoding of a document.
2873  *  This function only set the encoding of the %document, it does not any conversions. The new
2874  *  encoding is used when e.g. saving the file.
2875  *
2876  *  @param doc The document to use.
2877  *  @param new_encoding The encoding to be set for the document.
2878  **/
2879 GEANY_API_SYMBOL
document_set_encoding(GeanyDocument * doc,const gchar * new_encoding)2880 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2881 {
2882 	if (doc == NULL || new_encoding == NULL ||
2883 		utils_str_equal(new_encoding, doc->encoding))
2884 		return;
2885 
2886 	g_free(doc->encoding);
2887 	doc->encoding = g_strdup(new_encoding);
2888 
2889 	ui_update_statusbar(doc, -1);
2890 	gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2891 			encodings_is_unicode_charset(doc->encoding));
2892 }
2893 
2894 
2895 /* own Undo / Redo implementation to be able to undo / redo changes
2896  * to the encoding or the Unicode BOM (which are Scintilla independet).
2897  * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2898 
2899 /* Clears an Undo or Redo buffer. */
document_undo_clear_stack(GTrashStack ** stack)2900 void document_undo_clear_stack(GTrashStack **stack)
2901 {
2902 	while (g_trash_stack_height(stack) > 0)
2903 	{
2904 		undo_action *a = g_trash_stack_pop(stack);
2905 
2906 		if (G_LIKELY(a != NULL))
2907 		{
2908 			switch (a->type)
2909 			{
2910 				case UNDO_ENCODING:
2911 				case UNDO_RELOAD:
2912 					g_free(a->data); break;
2913 				default: break;
2914 			}
2915 			g_free(a);
2916 		}
2917 	}
2918 	*stack = NULL;
2919 }
2920 
2921 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
document_undo_clear(GeanyDocument * doc)2922 void document_undo_clear(GeanyDocument *doc)
2923 {
2924 	document_undo_clear_stack(&doc->priv->undo_actions);
2925 	document_undo_clear_stack(&doc->priv->redo_actions);
2926 
2927 	if (! main_status.quitting && doc->editor != NULL)
2928 		document_set_text_changed(doc, FALSE);
2929 }
2930 
2931 
2932 /* Adds an undo action without clearing the redo stack. This function should
2933  * not be called directly, generally (use document_undo_add() instead), but is
2934  * used by document_redo() in order not to erase the redo stack while moving
2935  * an action from the redo stack to the undo stack. */
document_undo_add_internal(GeanyDocument * doc,guint type,gpointer data)2936 void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data)
2937 {
2938 	undo_action *action;
2939 
2940 	g_return_if_fail(doc != NULL);
2941 
2942 	action = g_new0(undo_action, 1);
2943 	action->type = type;
2944 	action->data = data;
2945 
2946 	g_trash_stack_push(&doc->priv->undo_actions, action);
2947 
2948 	/* avoid unnecessary redraws */
2949 	if (type != UNDO_SCINTILLA || !doc->changed)
2950 		document_set_text_changed(doc, TRUE);
2951 
2952 	ui_update_popup_reundo_items(doc);
2953 }
2954 
2955 /* note: this is called on SCN_MODIFIED notifications */
document_undo_add(GeanyDocument * doc,guint type,gpointer data)2956 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2957 {
2958 	/* Clear the redo actions stack before adding the undo action. */
2959 	document_undo_clear_stack(&doc->priv->redo_actions);
2960 
2961 	document_undo_add_internal(doc, type, data);
2962 }
2963 
2964 
document_can_undo(GeanyDocument * doc)2965 gboolean document_can_undo(GeanyDocument *doc)
2966 {
2967 	g_return_val_if_fail(doc != NULL, FALSE);
2968 
2969 	if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2970 		return TRUE;
2971 	else
2972 		return FALSE;
2973 }
2974 
2975 
update_changed_state(GeanyDocument * doc)2976 static void update_changed_state(GeanyDocument *doc)
2977 {
2978 	doc->changed =
2979 		(sci_is_modified(doc->editor->sci) ||
2980 		doc->has_bom != doc->priv->saved_encoding.has_bom ||
2981 		! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2982 	document_set_text_changed(doc, doc->changed);
2983 }
2984 
2985 
document_undo(GeanyDocument * doc)2986 void document_undo(GeanyDocument *doc)
2987 {
2988 	undo_action *action;
2989 
2990 	g_return_if_fail(doc != NULL);
2991 
2992 	action = g_trash_stack_pop(&doc->priv->undo_actions);
2993 
2994 	if (G_UNLIKELY(action == NULL))
2995 	{
2996 		/* fallback, should not be necessary */
2997 		geany_debug("%s: fallback used", G_STRFUNC);
2998 		sci_undo(doc->editor->sci);
2999 	}
3000 	else
3001 	{
3002 		switch (action->type)
3003 		{
3004 			case UNDO_SCINTILLA:
3005 			{
3006 				document_redo_add(doc, UNDO_SCINTILLA, NULL);
3007 
3008 				sci_undo(doc->editor->sci);
3009 				break;
3010 			}
3011 			case UNDO_BOM:
3012 			{
3013 				document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3014 
3015 				doc->has_bom = GPOINTER_TO_INT(action->data);
3016 				ui_update_statusbar(doc, -1);
3017 				ui_document_show_hide(doc);
3018 				break;
3019 			}
3020 			case UNDO_ENCODING:
3021 			{
3022 				/* use the "old" encoding */
3023 				document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3024 
3025 				document_set_encoding(doc, (const gchar*)action->data);
3026 				g_free(action->data);
3027 
3028 				ui_update_statusbar(doc, -1);
3029 				ui_document_show_hide(doc);
3030 				break;
3031 			}
3032 			case UNDO_EOL:
3033 			{
3034 				undo_action *next_action;
3035 
3036 				document_redo_add(doc, UNDO_EOL, GINT_TO_POINTER(sci_get_eol_mode(doc->editor->sci)));
3037 
3038 				sci_set_eol_mode(doc->editor->sci, GPOINTER_TO_INT(action->data));
3039 
3040 				ui_update_statusbar(doc, -1);
3041 				ui_document_show_hide(doc);
3042 
3043 				/* When undoing, UNDO_EOL is always followed by UNDO_SCINTILLA
3044 				 * which undos the line endings in the editor and should be
3045 				 * performed together with UNDO_EOL. */
3046 				next_action = g_trash_stack_peek(&doc->priv->undo_actions);
3047 				if (next_action && next_action->type == UNDO_SCINTILLA)
3048 					document_undo(doc);
3049 				break;
3050 			}
3051 			case UNDO_RELOAD:
3052 			{
3053 				UndoReloadData *data = (UndoReloadData*)action->data;
3054 				gint eol_mode = data->eol_mode;
3055 				guint i;
3056 
3057 				/* We reuse 'data' for the redo action, so read the current EOL mode
3058 				 * into it before proceeding. */
3059 				data->eol_mode = editor_get_eol_char_mode(doc->editor);
3060 
3061 				/* Undo the rest of the actions which are part of the reloading process. */
3062 				for (i = 0; i < data->actions_count; i++)
3063 					document_undo(doc);
3064 
3065 				/* Restore the previous EOL mode. */
3066 				sci_set_eol_mode(doc->editor->sci, eol_mode);
3067 				/* This might affect the status bar and document menu, so update them. */
3068 				ui_update_statusbar(doc, -1);
3069 				ui_document_show_hide(doc);
3070 
3071 				document_redo_add(doc, UNDO_RELOAD, data);
3072 				break;
3073 			}
3074 			default: break;
3075 		}
3076 	}
3077 	g_free(action); /* free the action which was taken from the stack */
3078 
3079 	update_changed_state(doc);
3080 	ui_update_popup_reundo_items(doc);
3081 }
3082 
3083 
document_can_redo(GeanyDocument * doc)3084 gboolean document_can_redo(GeanyDocument *doc)
3085 {
3086 	g_return_val_if_fail(doc != NULL, FALSE);
3087 
3088 	if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
3089 		return TRUE;
3090 	else
3091 		return FALSE;
3092 }
3093 
3094 
document_redo(GeanyDocument * doc)3095 void document_redo(GeanyDocument *doc)
3096 {
3097 	undo_action *action;
3098 
3099 	g_return_if_fail(doc != NULL);
3100 
3101 	action = g_trash_stack_pop(&doc->priv->redo_actions);
3102 
3103 	if (G_UNLIKELY(action == NULL))
3104 	{
3105 		/* fallback, should not be necessary */
3106 		geany_debug("%s: fallback used", G_STRFUNC);
3107 		sci_redo(doc->editor->sci);
3108 	}
3109 	else
3110 	{
3111 		switch (action->type)
3112 		{
3113 			case UNDO_SCINTILLA:
3114 			{
3115 				undo_action *next_action;
3116 
3117 				document_undo_add_internal(doc, UNDO_SCINTILLA, NULL);
3118 
3119 				sci_redo(doc->editor->sci);
3120 
3121 				/* When redoing an EOL change, the UNDO_SCINTILLA which changes
3122 				 * the line ends in the editor is followed by UNDO_EOL
3123 				 * which should be performed together with UNDO_SCINTILLA. */
3124 				next_action = g_trash_stack_peek(&doc->priv->redo_actions);
3125 				if (next_action != NULL && next_action->type == UNDO_EOL)
3126 					document_redo(doc);
3127 				break;
3128 			}
3129 			case UNDO_BOM:
3130 			{
3131 				document_undo_add_internal(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3132 
3133 				doc->has_bom = GPOINTER_TO_INT(action->data);
3134 				ui_update_statusbar(doc, -1);
3135 				ui_document_show_hide(doc);
3136 				break;
3137 			}
3138 			case UNDO_ENCODING:
3139 			{
3140 				document_undo_add_internal(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3141 
3142 				document_set_encoding(doc, (const gchar*)action->data);
3143 				g_free(action->data);
3144 
3145 				ui_update_statusbar(doc, -1);
3146 				ui_document_show_hide(doc);
3147 				break;
3148 			}
3149 			case UNDO_EOL:
3150 			{
3151 				document_undo_add_internal(doc, UNDO_EOL, GINT_TO_POINTER(sci_get_eol_mode(doc->editor->sci)));
3152 
3153 				sci_set_eol_mode(doc->editor->sci, GPOINTER_TO_INT(action->data));
3154 
3155 				ui_update_statusbar(doc, -1);
3156 				ui_document_show_hide(doc);
3157 				break;
3158 			}
3159 			case UNDO_RELOAD:
3160 			{
3161 				UndoReloadData *data = (UndoReloadData*)action->data;
3162 				gint eol_mode = data->eol_mode;
3163 				guint i;
3164 
3165 				/* We reuse 'data' for the undo action, so read the current EOL mode
3166 				 * into it before proceeding. */
3167 				data->eol_mode = editor_get_eol_char_mode(doc->editor);
3168 
3169 				/* Redo the rest of the actions which are part of the reloading process. */
3170 				for (i = 0; i < data->actions_count; i++)
3171 					document_redo(doc);
3172 
3173 				/* Restore the previous EOL mode. */
3174 				sci_set_eol_mode(doc->editor->sci, eol_mode);
3175 				/* This might affect the status bar and document menu, so update them. */
3176 				ui_update_statusbar(doc, -1);
3177 				ui_document_show_hide(doc);
3178 
3179 				document_undo_add_internal(doc, UNDO_RELOAD, data);
3180 				break;
3181 			}
3182 			default: break;
3183 		}
3184 	}
3185 	g_free(action); /* free the action which was taken from the stack */
3186 
3187 	update_changed_state(doc);
3188 	ui_update_popup_reundo_items(doc);
3189 }
3190 
3191 
document_redo_add(GeanyDocument * doc,guint type,gpointer data)3192 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
3193 {
3194 	undo_action *action;
3195 
3196 	g_return_if_fail(doc != NULL);
3197 
3198 	action = g_new0(undo_action, 1);
3199 	action->type = type;
3200 	action->data = data;
3201 
3202 	g_trash_stack_push(&doc->priv->redo_actions, action);
3203 
3204 	if (type != UNDO_SCINTILLA || !doc->changed)
3205 		document_set_text_changed(doc, TRUE);
3206 
3207 	ui_update_popup_reundo_items(doc);
3208 }
3209 
3210 
3211 enum
3212 {
3213 	STATUS_CHANGED,
3214 	STATUS_DISK_CHANGED,
3215 	STATUS_READONLY
3216 };
3217 
3218 static struct
3219 {
3220 	const gchar *name;
3221 	GdkColor color;
3222 	gboolean loaded;
3223 } document_status_styles[] = {
3224 	{ "geany-document-status-changed",      {0}, FALSE },
3225 	{ "geany-document-status-disk-changed", {0}, FALSE },
3226 	{ "geany-document-status-readonly",     {0}, FALSE }
3227 };
3228 
3229 
document_get_status_id(GeanyDocument * doc)3230 static gint document_get_status_id(GeanyDocument *doc)
3231 {
3232 	if (doc->changed)
3233 		return STATUS_CHANGED;
3234 #ifdef USE_GIO_FILEMON
3235 	else if (doc->priv->file_disk_status == FILE_CHANGED)
3236 #else
3237 	else if (doc->priv->protected)
3238 #endif
3239 		return STATUS_DISK_CHANGED;
3240 	else if (doc->readonly)
3241 		return STATUS_READONLY;
3242 
3243 	return -1;
3244 }
3245 
3246 
3247 /* returns an identifier that is to be set as a widget name or class to get it styled
3248  * depending on the document status (changed, readonly, etc.)
3249  * a NULL return value means default (unchanged) style */
document_get_status_widget_class(GeanyDocument * doc)3250 const gchar *document_get_status_widget_class(GeanyDocument *doc)
3251 {
3252 	gint status;
3253 
3254 	g_return_val_if_fail(doc != NULL, NULL);
3255 
3256 	status = document_get_status_id(doc);
3257 	if (status < 0)
3258 		return NULL;
3259 	else
3260 		return document_status_styles[status].name;
3261 }
3262 
3263 
3264 /**
3265  *  Gets the status color of the document, or @c NULL if default widget coloring should be used.
3266  *  Returned colors are red if the document has changes, green if the document is read-only
3267  *  or simply @c NULL if the document is unmodified but writable.
3268  *
3269  *  @param doc The document to use.
3270  *
3271  *  @return @nullable The color for the document or @c NULL if the default color should be used.
3272  *          The color object is owned by Geany and should not be modified or freed.
3273  *
3274  *  @since 0.16
3275  */
3276 GEANY_API_SYMBOL
document_get_status_color(GeanyDocument * doc)3277 const GdkColor *document_get_status_color(GeanyDocument *doc)
3278 {
3279 	gint status;
3280 
3281 	g_return_val_if_fail(doc != NULL, NULL);
3282 
3283 	status = document_get_status_id(doc);
3284 	if (status < 0)
3285 		return NULL;
3286 	if (! document_status_styles[status].loaded)
3287 	{
3288 #if GTK_CHECK_VERSION(3, 0, 0)
3289 		GdkRGBA color;
3290 		GtkWidgetPath *path = gtk_widget_path_new();
3291 		GtkStyleContext *ctx = gtk_style_context_new();
3292 		gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
3293 		gtk_widget_path_append_type(path, GTK_TYPE_BOX);
3294 		gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
3295 		gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
3296 		gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
3297 		gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
3298 		gtk_style_context_set_path(ctx, path);
3299 		gtk_style_context_get_color(ctx, gtk_style_context_get_state(ctx), &color);
3300 		document_status_styles[status].color.red   = 0xffff * color.red;
3301 		document_status_styles[status].color.green = 0xffff * color.green;
3302 		document_status_styles[status].color.blue  = 0xffff * color.blue;
3303 		document_status_styles[status].loaded = TRUE;
3304 		gtk_widget_path_unref(path);
3305 		g_object_unref(ctx);
3306 #else
3307 		GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
3308 		gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
3309 				document_status_styles[status].name, NULL);
3310 		GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
3311 
3312 		document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
3313 		document_status_styles[status].loaded = TRUE;
3314 		g_free(path);
3315 #endif
3316 	}
3317 	return &document_status_styles[status].color;
3318 }
3319 
3320 
3321 /** Accessor function for @ref GeanyData::documents_array items.
3322  * @warning Always check the returned document is valid (@c doc->is_valid).
3323  * @param idx @c GeanyData::documents_array index.
3324  * @return @transfer{none} @nullable The document, or @c NULL if @a idx is out of range.
3325  *
3326  *  @since 0.16
3327  */
3328 GEANY_API_SYMBOL
document_index(gint idx)3329 GeanyDocument *document_index(gint idx)
3330 {
3331 	return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
3332 }
3333 
3334 
document_clone(GeanyDocument * old_doc)3335 GeanyDocument *document_clone(GeanyDocument *old_doc)
3336 {
3337 	gchar *text;
3338 	GeanyDocument *doc;
3339 	ScintillaObject *old_sci;
3340 
3341 	g_return_val_if_fail(old_doc, NULL);
3342 	old_sci = old_doc->editor->sci;
3343 	if (sci_has_selection(old_sci))
3344 		text = sci_get_selection_contents(old_sci);
3345 	else
3346 		text = sci_get_contents(old_sci, -1);
3347 
3348 	doc = document_new_file(NULL, old_doc->file_type, text);
3349 	g_free(text);
3350 	document_set_text_changed(doc, TRUE);
3351 
3352 	/* copy file properties */
3353 	doc->editor->line_wrapping = old_doc->editor->line_wrapping;
3354 	doc->editor->line_breaking = old_doc->editor->line_breaking;
3355 	doc->editor->auto_indent = old_doc->editor->auto_indent;
3356 	editor_set_indent(doc->editor, old_doc->editor->indent_type,
3357 		old_doc->editor->indent_width);
3358 	doc->readonly = old_doc->readonly;
3359 	doc->has_bom = old_doc->has_bom;
3360 	doc->priv->protected = 0;
3361 	document_set_encoding(doc, old_doc->encoding);
3362 	sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
3363 	sci_set_readonly(doc->editor->sci, doc->readonly);
3364 
3365 	/* update ui */
3366 	ui_document_show_hide(doc);
3367 	return doc;
3368 }
3369 
3370 
3371 /* @return TRUE if all files were saved or had their changes discarded. */
document_account_for_unsaved(void)3372 gboolean document_account_for_unsaved(void)
3373 {
3374 	guint p, page_count;
3375 
3376 	page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3377 	/* iterate over documents in tabs order */
3378 	for (p = 0; p < page_count; p++)
3379 	{
3380 		GeanyDocument *doc = document_get_from_page(p);
3381 
3382 		if (DOC_VALID(doc) && doc->changed)
3383 		{
3384 			if (! dialogs_show_unsaved_file(doc))
3385 				return FALSE;
3386 		}
3387 	}
3388 
3389 	return TRUE;
3390 }
3391 
3392 
force_close_all(void)3393 static void force_close_all(void)
3394 {
3395 	guint i;
3396 
3397 	main_status.closing_all = TRUE;
3398 
3399 	foreach_document(i)
3400 	{
3401 		document_close(documents[i]);
3402 	}
3403 
3404 	main_status.closing_all = FALSE;
3405 }
3406 
3407 
document_close_all(void)3408 gboolean document_close_all(void)
3409 {
3410 	if (! document_account_for_unsaved())
3411 		return FALSE;
3412 
3413 	force_close_all();
3414 
3415 	return TRUE;
3416 }
3417 
3418 
3419 /* *
3420  * Shows a message related to a document.
3421  *
3422  * Use this whenever the user needs to see a document-related message,
3423  * for example when the file was externally modified or deleted.
3424  *
3425  * Any of the buttons can be @c NULL.  If not @c NULL, @a btn_1's
3426  * @a response_1 response will be the default for the @c GtkInfoBar or
3427  * @c GtkDialog.
3428  *
3429  * @param doc @c GeanyDocument.
3430  * @param msgtype The type of message.
3431  * @param response_cb A callback function called when there's a response.
3432  * @param btn_1 The first action area button.
3433  * @param response_1 The response for @a btn_1.
3434  * @param btn_2 The second action area button.
3435  * @param response_2 The response for @a btn_2.
3436  * @param btn_3 The third action area button.
3437  * @param response_3 The response for @a btn_3.
3438  * @param extra_text Text to show below the main message.
3439  * @param format The text format for the main message.
3440  * @param ... Used with @a format as in @c printf.
3441  *
3442  * @since 1.25
3443  * */
document_show_message(GeanyDocument * doc,GtkMessageType msgtype,void (* response_cb)(GtkWidget * info_bar,gint response_id,GeanyDocument * doc),const gchar * btn_1,GtkResponseType response_1,const gchar * btn_2,GtkResponseType response_2,const gchar * btn_3,GtkResponseType response_3,const gchar * extra_text,const gchar * format,...)3444 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3445 	void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3446 	const gchar *btn_1, GtkResponseType response_1,
3447 	const gchar *btn_2, GtkResponseType response_2,
3448 	const gchar *btn_3, GtkResponseType response_3,
3449 	const gchar *extra_text, const gchar *format, ...)
3450 {
3451 	va_list args;
3452 	gchar *text, *markup;
3453 	GtkWidget *hbox, *icon, *label, *content_area;
3454 	GtkWidget *info_widget, *parent;
3455 	parent = document_get_notebook_child(doc);
3456 
3457 	va_start(args, format);
3458 	text = g_strdup_vprintf(format, args);
3459 	va_end(args);
3460 
3461 	markup = g_markup_printf_escaped("<span size=\"larger\">%s</span>", text);
3462 	g_free(text);
3463 
3464 	info_widget = gtk_info_bar_new();
3465 	/* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3466 	gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3467 
3468 	gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3469 
3470 	if (btn_1)
3471 		gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3472 	if (btn_2)
3473 		gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3474 	if (btn_3)
3475 		gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3476 
3477 	content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3478 
3479 	label = geany_wrap_label_new(NULL);
3480 	gtk_label_set_markup(GTK_LABEL(label), markup);
3481 	g_free(markup);
3482 
3483 	g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3484 
3485 	hbox = gtk_hbox_new(FALSE, 12);
3486 	gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3487 
3488 	switch (msgtype)
3489 	{
3490 		case GTK_MESSAGE_INFO:
3491 			icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3492 			break;
3493 		case GTK_MESSAGE_WARNING:
3494 			icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3495 			break;
3496 		case GTK_MESSAGE_QUESTION:
3497 			icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3498 			break;
3499 		case GTK_MESSAGE_ERROR:
3500 			icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3501 			break;
3502 		default:
3503 			icon = NULL;
3504 			break;
3505 	}
3506 
3507 	if (icon)
3508 		gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3509 
3510 	if (extra_text)
3511 	{
3512 		GtkWidget *vbox = gtk_vbox_new(FALSE, 6);
3513 		GtkWidget *extra_label = geany_wrap_label_new(extra_text);
3514 
3515 		gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3516 		gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3517 		gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3518 	}
3519 	else
3520 		gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3521 
3522 	gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3523 
3524 	gtk_widget_show_all(info_widget);
3525 
3526 	return info_widget;
3527 }
3528 
3529 
on_monitor_reload_file_response(GtkWidget * bar,gint response_id,GeanyDocument * doc)3530 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3531 {
3532 	gboolean close = FALSE;
3533 
3534 	// disable info bar so actions complete normally
3535 	unprotect_document(doc);
3536 	doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3537 
3538 	if (response_id == RESPONSE_DOCUMENT_RELOAD)
3539 	{
3540 		close = doc->changed ?
3541 			document_reload_prompt(doc, doc->encoding) :
3542 			document_reload_force(doc, doc->encoding);
3543 	}
3544 	else if (response_id == RESPONSE_DOCUMENT_SAVE)
3545 	{
3546 		close = document_save_file(doc, TRUE);	// force overwrite
3547 	}
3548 	else if (response_id == GTK_RESPONSE_CANCEL)
3549 	{
3550 		document_set_text_changed(doc, TRUE);
3551 		close = TRUE;
3552 	}
3553 	if (!close)
3554 	{
3555 		doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3556 		protect_document(doc);
3557 		return;
3558 	}
3559 	gtk_widget_destroy(bar);
3560 }
3561 
3562 
on_sci_key(GtkWidget * widget,GdkEventKey * event,gpointer data)3563 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3564 {
3565 	GtkInfoBar *bar = GTK_INFO_BAR(data);
3566 
3567 	g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3568 
3569 	switch (event->keyval)
3570 	{
3571 		case GDK_Tab:
3572 		case GDK_ISO_Left_Tab:
3573 		{
3574 			GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3575 			GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3576 			gtk_widget_child_focus(action_area, dir);
3577 			return TRUE;
3578 		}
3579 		case GDK_Escape:
3580 		{
3581 			gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3582 			return TRUE;
3583 		}
3584 		default:
3585 			return FALSE;
3586 	}
3587 }
3588 
3589 
3590 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
enable_key_intercept(GeanyDocument * doc,GtkWidget * bar)3591 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3592 {
3593 	/* automatically focus editor again on bar close */
3594 	g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3595 			G_CONNECT_SWAPPED);
3596 	g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3597 }
3598 
3599 
monitor_reload_file(GeanyDocument * doc)3600 static void monitor_reload_file(GeanyDocument *doc)
3601 {
3602 	if (! doc->changed && file_prefs.reload_clean_doc_on_file_change)
3603 	{
3604 		document_reload_force(doc, doc->encoding);
3605 		return;
3606 	}
3607 
3608 	gchar *base_name = g_path_get_basename(doc->file_name);
3609 
3610 	/* show this message only once */
3611 	if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3612 	{
3613 		GtkWidget *bar;
3614 
3615 		bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3616 				_("_Reload"), RESPONSE_DOCUMENT_RELOAD,
3617 				_("_Overwrite"), RESPONSE_DOCUMENT_SAVE,
3618 				GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3619 				_("Do you want to reload it?"),
3620 				_("The file '%s' on the disk is more recent than the current buffer."),
3621 				base_name);
3622 
3623 		protect_document(doc);
3624 		doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3625 		enable_key_intercept(doc, bar);
3626 	}
3627 	g_free(base_name);
3628 }
3629 
3630 
on_monitor_resave_missing_file_response(GtkWidget * bar,gint response_id,GeanyDocument * doc)3631 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3632                                                     gint response_id,
3633                                                     GeanyDocument *doc)
3634 {
3635 	gboolean close = TRUE;
3636 
3637 	unprotect_document(doc);
3638 
3639 	if (response_id == RESPONSE_DOCUMENT_SAVE)
3640 		close = dialogs_show_save_as();
3641 
3642 	if (close)
3643 	{
3644 		doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3645 		gtk_widget_destroy(bar);
3646 	}
3647 	else
3648 	{
3649 		/* protect back the document if save didn't occur */
3650 		protect_document(doc);
3651 	}
3652 }
3653 
3654 
monitor_resave_missing_file(GeanyDocument * doc)3655 static void monitor_resave_missing_file(GeanyDocument *doc)
3656 {
3657 	if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3658 	{
3659 		GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3660 
3661 		if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3662 			gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3663 
3664 		bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3665 				on_monitor_resave_missing_file_response,
3666 				GTK_STOCK_SAVE, RESPONSE_DOCUMENT_SAVE,
3667 				GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3668 				NULL, GTK_RESPONSE_NONE,
3669 				_("Try to resave the file?"),
3670 				_("File \"%s\" was not found on disk!"),
3671 				doc->file_name);
3672 
3673 		protect_document(doc);
3674 		document_set_text_changed(doc, TRUE);
3675 		/* don't prompt more than once */
3676 		SETPTR(doc->real_path, NULL);
3677 		doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3678 		enable_key_intercept(doc, bar);
3679 	}
3680 }
3681 
3682 
3683 /* Set force to force a disk check, otherwise it is ignored if there was a check
3684  * in the last file_prefs.disk_check_timeout seconds.
3685  * @return @c TRUE if the file has changed. */
document_check_disk_status(GeanyDocument * doc,gboolean force)3686 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3687 {
3688 	gboolean ret = FALSE;
3689 	gboolean use_gio_filemon;
3690 	time_t mtime = 0;
3691 	gchar *locale_filename;
3692 	FileDiskStatus old_status;
3693 
3694 	g_return_val_if_fail(doc != NULL, FALSE);
3695 
3696 	/* ignore remote files and documents that have never been saved to disk */
3697 	if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3698 			|| doc->real_path == NULL || doc->priv->is_remote)
3699 		return FALSE;
3700 
3701 	use_gio_filemon = (doc->priv->monitor != NULL);
3702 
3703 	if (use_gio_filemon)
3704 	{
3705 		if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3706 			return FALSE;
3707 	}
3708 	else
3709 	{
3710 		time_t cur_time = time(NULL);
3711 
3712 		if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3713 			return FALSE;
3714 
3715 		doc->priv->last_check = cur_time;
3716 	}
3717 
3718 	locale_filename = utils_get_locale_from_utf8(doc->file_name);
3719 	if (!get_mtime(locale_filename, &mtime))
3720 	{
3721 		monitor_resave_missing_file(doc);
3722 		/* doc may be closed now */
3723 		ret = TRUE;
3724 	}
3725 	else if (doc->priv->mtime < mtime)
3726 	{
3727 		/* make sure the user is not prompted again after he cancelled the "reload file?" message */
3728 		doc->priv->mtime = mtime;
3729 		monitor_reload_file(doc);
3730 		/* doc may be closed now */
3731 		ret = TRUE;
3732 	}
3733 	g_free(locale_filename);
3734 
3735 	if (DOC_VALID(doc))
3736 	{	/* doc can get invalid when a document was closed */
3737 		old_status = doc->priv->file_disk_status;
3738 		doc->priv->file_disk_status = FILE_OK;
3739 		if (old_status != doc->priv->file_disk_status)
3740 			ui_update_tab_status(doc);
3741 	}
3742 	return ret;
3743 }
3744 
3745 
3746 /** Compares documents by their display names.
3747  * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3748  * @note 'Display name' means the base name of the document's filename.
3749  *
3750  * @param a @c GeanyDocument**.
3751  * @param b @c GeanyDocument**.
3752  * @warning The arguments take the address of each document pointer.
3753  * @return Negative value if a < b; zero if a = b; positive value if a > b.
3754  *
3755  * @since 0.21
3756  */
3757 GEANY_API_SYMBOL
document_compare_by_display_name(gconstpointer a,gconstpointer b)3758 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3759 {
3760 	GeanyDocument *doc_a = *((GeanyDocument**) a);
3761 	GeanyDocument *doc_b = *((GeanyDocument**) b);
3762 	gchar *base_name_a, *base_name_b;
3763 	gint result;
3764 
3765 	base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3766 	base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3767 
3768 	result = strcmp(base_name_a, base_name_b);
3769 
3770 	g_free(base_name_a);
3771 	g_free(base_name_b);
3772 
3773 	return result;
3774 }
3775 
3776 
3777 /** Compares documents by their tab order.
3778  * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3779  *
3780  * @param a @c GeanyDocument**.
3781  * @param b @c GeanyDocument**.
3782  * @warning The arguments take the address of each document pointer.
3783  * @return Negative value if a < b; zero if a = b; positive value if a > b.
3784  *
3785  * @since 0.21 (GEANY_API_VERSION 209)
3786  */
3787 GEANY_API_SYMBOL
document_compare_by_tab_order(gconstpointer a,gconstpointer b)3788 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3789 {
3790 	GeanyDocument *doc_a = *((GeanyDocument**) a);
3791 	GeanyDocument *doc_b = *((GeanyDocument**) b);
3792 	gint notebook_position_doc_a;
3793 	gint notebook_position_doc_b;
3794 
3795 	notebook_position_doc_a = document_get_notebook_page(doc_a);
3796 	notebook_position_doc_b = document_get_notebook_page(doc_b);
3797 
3798 	if (notebook_position_doc_a < notebook_position_doc_b)
3799 		return -1;
3800 	if (notebook_position_doc_a > notebook_position_doc_b)
3801 		return 1;
3802 	/* equality */
3803 	return 0;
3804 }
3805 
3806 
3807 /** Compares documents by their tab order, in reverse order.
3808  * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3809  *
3810  * @param a @c GeanyDocument**.
3811  * @param b @c GeanyDocument**.
3812  * @warning The arguments take the address of each document pointer.
3813  * @return Negative value if a < b; zero if a = b; positive value if a > b.
3814  *
3815  * @since 0.21 (GEANY_API_VERSION 209)
3816  */
3817 GEANY_API_SYMBOL
document_compare_by_tab_order_reverse(gconstpointer a,gconstpointer b)3818 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3819 {
3820 	return -1 * document_compare_by_tab_order(a, b);
3821 }
3822 
3823 
document_grab_focus(GeanyDocument * doc)3824 void document_grab_focus(GeanyDocument *doc)
3825 {
3826 	g_return_if_fail(doc != NULL);
3827 
3828 	gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));
3829 }
3830 
copy_(void * src)3831 static void        *copy_(void *src) { return src; }
free_(void * doc)3832 static void         free_(void *doc) { }
3833 
3834 /** @gironly
3835  * Gets the GType of GeanyDocument
3836  *
3837  * @return the GeanyDocument type */
3838 GEANY_API_SYMBOL
3839 GType document_get_type (void);
3840 
3841 G_DEFINE_BOXED_TYPE(GeanyDocument, document, copy_, free_);
3842 
3843 
document_get_data(const GeanyDocument * doc,const gchar * key)3844 gpointer document_get_data(const GeanyDocument *doc, const gchar *key)
3845 {
3846 	return g_datalist_get_data(&doc->priv->data, key);
3847 }
3848 
3849 
document_set_data(GeanyDocument * doc,const gchar * key,gpointer data)3850 void document_set_data(GeanyDocument *doc, const gchar *key, gpointer data)
3851 {
3852 	g_datalist_set_data(&doc->priv->data, key, data);
3853 }
3854 
3855 
document_set_data_full(GeanyDocument * doc,const gchar * key,gpointer data,GDestroyNotify free_func)3856 void document_set_data_full(GeanyDocument *doc, const gchar *key,
3857 	gpointer data, GDestroyNotify free_func)
3858 {
3859 	g_datalist_set_data_full(&doc->priv->data, key, data, free_func);
3860 }
3861