Fix build with GLib < 2.32
[geany-mirror.git] / src / document.c
blob2a937bd985804a63b6ffc776ae7e14de8a9de2f7
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 * Document related actions: new, save, open, etc.
24 * Also Scintilla search actions.
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #include "document.h"
33 #include "app.h"
34 #include "callbacks.h" /* for ignore_callback */
35 #include "dialogs.h"
36 #include "documentprivate.h"
37 #include "encodings.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"
56 #include "gtkcompat.h"
58 #ifdef HAVE_SYS_TIME_H
59 # include <sys/time.h>
60 #endif
61 #include <time.h>
63 #include <unistd.h>
64 #include <string.h>
65 #include <errno.h>
67 #ifdef HAVE_SYS_TYPES_H
68 # include <sys/types.h>
69 #endif
71 #include <stdlib.h>
73 /* gstdio.h also includes sys/stat.h */
74 #include <glib/gstdio.h>
76 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
77 /*#define USE_GIO_FILEMON 1*/
78 #include <gio/gio.h>
80 #include <gdk/gdkkeysyms.h>
82 GeanyFilePrefs file_prefs;
85 /** Dynamic array of GeanyDocument pointers.
86 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
87 * to a document over time, but it may represent a different
88 * document later on, or may have been closed and become invalid.
90 * @warning You must check @c GeanyDocument::is_valid when iterating over this array.
91 * This is done automatically if you use the foreach_document() macro.
93 * @note
94 * Never assume that the order of document pointers is the same as the order of notebook tabs.
95 * One reason is that notebook tabs can be reordered.
96 * Use @c document_get_from_page() to lookup a document from a notebook tab number.
98 * @see documents. */
99 GPtrArray *documents_array = NULL;
102 /* an undo action, also used for redo actions */
103 typedef struct
105 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
106 guint type; /* to identify the action */
107 gpointer *data; /* the old value (before the change), in case of a redo action
108 * it contains the new value */
109 } undo_action;
112 static void document_undo_clear(GeanyDocument *doc);
113 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
114 static gboolean remove_page(guint page_num);
118 * Finds a document whose @c real_path field matches the given filename.
120 * @param realname The filename to search, which should be identical to the
121 * string returned by @c tm_get_real_path().
123 * @return The matching document, or @c NULL.
124 * @note This is only really useful when passing a @c TMWorkObject::file_name.
125 * @see GeanyDocument::real_path.
126 * @see document_find_by_filename().
128 * @since 0.15
130 GeanyDocument* document_find_by_real_path(const gchar *realname)
132 guint i;
134 if (! realname)
135 return NULL; /* file doesn't exist on disk */
137 for (i = 0; i < documents_array->len; i++)
139 GeanyDocument *doc = documents[i];
141 if (! doc->is_valid || ! doc->real_path)
142 continue;
144 if (utils_filenamecmp(realname, doc->real_path) == 0)
146 return doc;
149 return NULL;
153 /* dereference symlinks, /../ junk in path and return locale encoding */
154 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
156 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
157 gchar *realname = tm_get_real_path(locale_name);
159 g_free(locale_name);
160 return realname;
165 * Finds a document with the given filename.
166 * This matches either an exact GeanyDocument::file_name string, or variant
167 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
168 * match @c "/name").
170 * @param utf8_filename The filename to search (in UTF-8 encoding).
172 * @return The matching document, or @c NULL.
173 * @see document_find_by_real_path().
175 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
177 guint i;
178 GeanyDocument *doc;
179 gchar *realname;
181 g_return_val_if_fail(utf8_filename != NULL, NULL);
183 /* First search GeanyDocument::file_name, so we can find documents with a
184 * filename set but not saved on disk, like vcdiff produces */
185 for (i = 0; i < documents_array->len; i++)
187 doc = documents[i];
189 if (! doc->is_valid || doc->file_name == NULL)
190 continue;
192 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
194 return doc;
197 /* Now try matching based on the realpath(), which is unique per file on disk */
198 realname = get_real_path_from_utf8(utf8_filename);
199 doc = document_find_by_real_path(realname);
200 g_free(realname);
201 return doc;
205 /* returns the document which has sci, or NULL. */
206 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
208 guint i;
210 g_return_val_if_fail(sci != NULL, NULL);
212 for (i = 0; i < documents_array->len; i++)
214 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
215 return documents[i];
217 return NULL;
221 /** Gets the notebook page index for a document.
222 * @param doc The document.
223 * @return The index.
224 * @since 0.19 */
225 gint document_get_notebook_page(GeanyDocument *doc)
227 GtkWidget *parent;
228 GtkWidget *child;
230 g_return_val_if_fail(doc != NULL, -1);
232 child = GTK_WIDGET(doc->editor->sci);
233 parent = gtk_widget_get_parent(child);
234 /* search for the direct notebook child, mirroring document_get_from_page() */
235 while (parent && ! GTK_IS_NOTEBOOK(parent))
237 child = parent;
238 parent = gtk_widget_get_parent(child);
241 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
246 * Recursively searches a containers children until it finds a
247 * Scintilla widget, or NULL if one was not found.
249 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
251 ScintillaObject *sci = NULL;
252 GList *children, *iter;
254 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
256 children = gtk_container_get_children(GTK_CONTAINER(container));
257 for (iter = children; iter != NULL; iter = g_list_next(iter))
259 if (IS_SCINTILLA(iter->data))
261 sci = SCINTILLA(iter->data);
262 break;
264 else if (GTK_IS_CONTAINER(iter->data))
266 sci = locate_sci_in_container(iter->data);
267 if (IS_SCINTILLA(sci))
268 break;
269 sci = NULL;
272 g_list_free(children);
274 return sci;
279 * Finds the document for the given notebook page @a page_num.
281 * @param page_num The notebook page number to search.
283 * @return The corresponding document for the given notebook page, or @c NULL.
285 GeanyDocument *document_get_from_page(guint page_num)
287 GtkWidget *parent;
288 ScintillaObject *sci;
290 if (page_num >= documents_array->len)
291 return NULL;
293 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
294 g_return_val_if_fail(GTK_IS_BOX(parent), NULL);
296 sci = locate_sci_in_container(parent);
297 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
299 return document_find_by_sci(sci);
304 * Finds the current document.
306 * @return A pointer to the current document or @c NULL if there are no opened documents.
308 GeanyDocument *document_get_current(void)
310 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
312 if (cur_page == -1)
313 return NULL;
314 else
315 return document_get_from_page((guint) cur_page);
319 void document_init_doclist(void)
321 documents_array = g_ptr_array_new();
325 void document_finalize(void)
327 guint i;
329 for (i = 0; i < documents_array->len; i++)
330 g_free(documents[i]);
331 g_ptr_array_free(documents_array, TRUE);
336 * Returns the last part of the filename of the given GeanyDocument. The result is also
337 * truncated to a maximum of @a length characters in case the filename is very long.
339 * @param doc The document to use.
340 * @param length The length of the resulting string or -1 to use a default value.
342 * @return The ellipsized last part of the filename of @a doc, should be freed when no
343 * longer needed.
345 * @since 0.17
347 /* TODO make more use of this */
348 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
350 gchar *base_name, *short_name;
352 g_return_val_if_fail(doc != NULL, NULL);
354 if (length < 0)
355 length = 30;
357 base_name = g_path_get_basename(DOC_FILENAME(doc));
358 short_name = utils_str_middle_truncate(base_name, (guint)length);
360 g_free(base_name);
362 return short_name;
366 void document_update_tab_label(GeanyDocument *doc)
368 gchar *short_name;
369 GtkWidget *parent;
371 g_return_if_fail(doc != NULL);
373 short_name = document_get_basename_for_display(doc, -1);
375 /* we need to use the event box for the tooltip, labels don't get the necessary events */
376 parent = gtk_widget_get_parent(doc->priv->tab_label);
377 parent = gtk_widget_get_parent(parent);
379 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
381 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
383 g_free(short_name);
388 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
389 * according to the document's save state.
390 * This is called by Geany mostly when opening or saving files.
392 * @param doc The document to use.
393 * @param changed Whether the document state should indicate changes have been made.
395 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
397 g_return_if_fail(doc != NULL);
399 doc->changed = changed;
401 if (! main_status.quitting)
403 ui_update_tab_status(doc);
404 ui_save_buttons_toggle(changed);
405 ui_set_window_title(doc);
406 ui_update_statusbar(doc, -1);
411 /* returns the next free place in the document list,
412 * or -1 if the documents_array is full */
413 static gint document_get_new_idx(void)
415 guint i;
417 for (i = 0; i < documents_array->len; i++)
419 if (documents[i]->editor == NULL)
421 return (gint) i;
424 return -1;
428 static void queue_colourise(GeanyDocument *doc)
430 /* Colourise the editor before it is next drawn */
431 doc->priv->colourise_needed = TRUE;
433 /* If the editor doesn't need drawing (e.g. after saving the current
434 * document), we need to force a redraw, so the expose event is triggered.
435 * This ensures we don't start colourising before all documents are opened/saved,
436 * only once the editor is drawn. */
437 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
441 #ifdef USE_GIO_FILEMON
442 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
443 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
444 GeanyDocument *doc)
446 g_return_if_fail(doc != NULL);
448 if (file_prefs.disk_check_timeout == 0)
449 return;
451 geany_debug("%s: event: %d previous file status: %d",
452 G_STRFUNC, event, doc->priv->file_disk_status);
453 switch (event)
455 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
457 if (doc->priv->file_disk_status == FILE_IGNORE)
458 doc->priv->file_disk_status = FILE_OK;
459 else
460 doc->priv->file_disk_status = FILE_CHANGED;
461 g_message("%s: FILE_CHANGED", G_STRFUNC);
462 break;
464 case G_FILE_MONITOR_EVENT_DELETED:
466 doc->priv->file_disk_status = FILE_CHANGED;
467 g_message("%s: FILE_MISSING", G_STRFUNC);
468 break;
470 default:
471 break;
473 if (doc->priv->file_disk_status != FILE_OK)
475 ui_update_tab_status(doc);
478 #endif
481 static void document_stop_file_monitoring(GeanyDocument *doc)
483 g_return_if_fail(doc != NULL);
485 if (doc->priv->monitor != NULL)
487 g_object_unref(doc->priv->monitor);
488 doc->priv->monitor = NULL;
493 static void monitor_file_setup(GeanyDocument *doc)
495 g_return_if_fail(doc != NULL);
496 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
497 * doesn't work at all for remote files and legacy polling is too slow. */
498 if (! doc->priv->is_remote)
500 #ifdef USE_GIO_FILEMON
501 gchar *locale_filename;
503 /* stop any previous monitoring */
504 document_stop_file_monitoring(doc);
506 locale_filename = utils_get_locale_from_utf8(doc->file_name);
507 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
509 /* get a file monitor and connect to the 'changed' signal */
510 GFile *file = g_file_new_for_path(locale_filename);
511 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
512 g_signal_connect(doc->priv->monitor, "changed",
513 G_CALLBACK(monitor_file_changed_cb), doc);
515 /* we set the rate limit according to the GUI pref but it's most probably not used */
516 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
518 g_object_unref(file);
520 g_free(locale_filename);
521 #endif
523 doc->priv->file_disk_status = FILE_OK;
527 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
529 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
530 if (DOC_VALID(doc))
532 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
533 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
535 if (source_widget == NULL)
536 source_widget = doc->priv->tag_tree;
538 if (focusw == source_widget)
539 gtk_widget_grab_focus(sci);
544 static gboolean on_idle_focus(gpointer doc)
546 document_try_focus(doc, NULL);
547 return FALSE;
551 /* Creates a new document and editor, adding a tab in the notebook.
552 * @return The created document */
553 static GeanyDocument *document_create(const gchar *utf8_filename)
555 GeanyDocument *doc;
556 gint new_idx;
557 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
559 if (cur_pages == 1)
561 doc = document_get_current();
562 /* remove the empty document first */
563 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
564 /* prevent immediately opening another new doc with
565 * new_document_after_close pref */
566 remove_page(0);
569 new_idx = document_get_new_idx();
570 if (new_idx == -1) /* expand the array, no free places */
572 doc = g_new0(GeanyDocument, 1);
574 new_idx = documents_array->len;
575 g_ptr_array_add(documents_array, doc);
578 doc = documents[new_idx];
580 /* initialize default document settings */
581 doc->priv = g_new0(GeanyDocumentPrivate, 1);
582 doc->index = new_idx;
583 doc->file_name = g_strdup(utf8_filename);
584 doc->editor = editor_create(doc);
585 #ifndef USE_GIO_FILEMON
586 doc->priv->last_check = time(NULL);
587 #endif
589 sidebar_openfiles_add(doc); /* sets doc->iter */
591 notebook_new_tab(doc);
593 /* select document in sidebar */
595 GtkTreeSelection *sel;
597 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
598 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
601 ui_document_buttons_update();
603 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
604 return doc;
609 * Closes the given document.
611 * @param doc The document to remove.
613 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
615 * @since 0.15
617 gboolean document_close(GeanyDocument *doc)
619 g_return_val_if_fail(doc, FALSE);
621 return document_remove_page(document_get_notebook_page(doc));
625 /* Call document_remove_page() instead, this is only needed for document_create()
626 * to prevent re-opening a new document when the last document is closed (if enabled). */
627 static gboolean remove_page(guint page_num)
629 GeanyDocument *doc = document_get_from_page(page_num);
631 g_return_val_if_fail(doc != NULL, FALSE);
633 if (doc->changed && ! dialogs_show_unsaved_file(doc))
634 return FALSE;
636 /* tell any plugins that the document is about to be closed */
637 g_signal_emit_by_name(geany_object, "document-close", doc);
639 /* Checking real_path makes it likely the file exists on disk */
640 if (! main_status.closing_all && doc->real_path != NULL)
641 ui_add_recent_document(doc);
643 doc->is_valid = FALSE;
645 if (main_status.quitting)
647 /* we need to destroy the ScintillaWidget so our handlers on it are
648 * disconnected before we free any data they may use (like the editor).
649 * when not quitting, this is handled by removing the notebook page. */
650 gtk_widget_destroy(GTK_WIDGET(doc->editor->sci));
652 else
654 notebook_remove_page(page_num);
655 sidebar_remove_document(doc);
656 navqueue_remove_file(doc->file_name);
657 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
659 g_free(doc->encoding);
660 g_free(doc->priv->saved_encoding.encoding);
661 g_free(doc->file_name);
662 g_free(doc->real_path);
663 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
665 if (doc->priv->tag_tree)
666 gtk_widget_destroy(doc->priv->tag_tree);
668 editor_destroy(doc->editor);
669 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
671 document_stop_file_monitoring(doc);
673 document_undo_clear(doc);
675 g_free(doc->priv);
677 /* reset document settings to defaults for re-use */
678 memset(doc, 0, sizeof(GeanyDocument));
680 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
682 sidebar_update_tag_list(NULL, FALSE);
683 ui_set_window_title(NULL);
684 ui_save_buttons_toggle(FALSE);
685 ui_update_popup_reundo_items(NULL);
686 ui_document_buttons_update();
687 build_menu_update(NULL);
689 return TRUE;
694 * Removes the given notebook tab at @a page_num and clears all related information
695 * in the document list.
697 * @param page_num The notebook page number to remove.
699 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
701 gboolean document_remove_page(guint page_num)
703 gboolean done = remove_page(page_num);
705 if (done && ui_prefs.new_document_after_close)
706 document_new_file_if_non_open();
708 return done;
712 /* used to keep a record of the unchanged document state encoding */
713 static void store_saved_encoding(GeanyDocument *doc)
715 g_free(doc->priv->saved_encoding.encoding);
716 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
717 doc->priv->saved_encoding.has_bom = doc->has_bom;
721 /* Opens a new empty document only if there are no other documents open */
722 GeanyDocument *document_new_file_if_non_open(void)
724 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
725 return document_new_file(NULL, NULL, NULL);
727 return NULL;
732 * Creates a new document.
733 * Line endings in @a text will be converted to the default setting.
734 * Afterwards, the @c "document-new" signal is emitted for plugins.
736 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
737 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
738 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
740 * @return The new document.
742 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
744 GeanyDocument *doc;
746 if (utf8_filename && g_path_is_absolute(utf8_filename))
748 gchar *tmp;
749 tmp = utils_strdupa(utf8_filename); /* work around const */
750 utils_tidy_path(tmp);
751 utf8_filename = tmp;
753 doc = document_create(utf8_filename);
755 g_assert(doc != NULL);
757 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
758 if (text)
760 GString *template = g_string_new(text);
761 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
763 sci_set_text(doc->editor->sci, template->str);
764 g_string_free(template, TRUE);
766 else
767 sci_clear_all(doc->editor->sci);
769 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
771 sci_set_undo_collection(doc->editor->sci, TRUE);
772 sci_empty_undo_buffer(doc->editor->sci);
774 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
775 /* store the opened encoding for undo/redo */
776 store_saved_encoding(doc);
778 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
779 ft = filetypes_detect_from_document(doc);
781 document_set_filetype(doc, ft); /* also re-parses tags */
783 ui_set_window_title(doc);
784 build_menu_update(doc);
785 document_set_text_changed(doc, FALSE);
786 ui_document_show_hide(doc); /* update the document menu */
788 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
789 /* bring it in front, jump to the start and grab the focus */
790 editor_goto_pos(doc->editor, 0, FALSE);
791 document_try_focus(doc, NULL);
793 #ifdef USE_GIO_FILEMON
794 monitor_file_setup(doc);
795 #else
796 doc->priv->mtime = time(NULL);
797 #endif
799 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
800 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
802 g_signal_emit_by_name(geany_object, "document-new", doc);
804 msgwin_status_add(_("New file \"%s\" opened."),
805 DOC_FILENAME(doc));
807 return doc;
812 * Opens a document specified by @a locale_filename.
813 * Afterwards, the @c "document-open" signal is emitted for plugins.
815 * @param locale_filename The filename of the document to load, in locale encoding.
816 * @param readonly Whether to open the document in read-only mode.
817 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
818 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
820 * @return The document opened or @c NULL.
822 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
823 GeanyFiletype *ft, const gchar *forced_enc)
825 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
829 typedef struct
831 gchar *data; /* null-terminated file data */
832 gsize len; /* string length of data */
833 gchar *enc;
834 gboolean bom;
835 time_t mtime; /* modification time, read by stat::st_mtime */
836 gboolean readonly;
837 } FileData;
840 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
841 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
842 FileData *filedata, const gchar *forced_enc)
844 GError *err = NULL;
845 struct stat st;
847 filedata->data = NULL;
848 filedata->len = 0;
849 filedata->enc = NULL;
850 filedata->bom = FALSE;
851 filedata->readonly = FALSE;
853 if (g_stat(locale_filename, &st) != 0)
855 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
856 display_filename, g_strerror(errno));
857 return FALSE;
860 filedata->mtime = st.st_mtime;
862 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
864 ui_set_statusbar(TRUE, "%s", err->message);
865 g_error_free(err);
866 return FALSE;
869 filedata->len = (gsize) st.st_size;
870 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
871 &filedata->enc, &filedata->bom, &filedata->readonly))
873 if (forced_enc)
875 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
876 display_filename, forced_enc);
878 else
880 ui_set_statusbar(TRUE,
881 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
882 display_filename);
884 g_free(filedata->data);
885 return FALSE;
888 if (filedata->readonly)
890 const gchar *warn_msg = _(
891 "The file \"%s\" could not be opened properly and has been truncated. " \
892 "This can occur if the file contains a NULL byte. " \
893 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
895 if (main_status.main_window_realized)
896 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
898 ui_set_statusbar(TRUE, warn_msg, display_filename);
901 return TRUE;
905 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
906 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
907 * if cl_options.goto_column is set.
909 * returns the new position which may have changed */
910 static gint set_cursor_position(GeanyEditor *editor, gint pos)
912 if (cl_options.goto_line >= 0)
913 { /* goto line which was specified on command line and then undefine the line */
914 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
915 editor->scroll_percent = 0.5F;
916 cl_options.goto_line = -1;
918 else if (pos > 0)
920 sci_set_current_position(editor->sci, pos, FALSE);
921 editor->scroll_percent = 0.5F;
924 if (cl_options.goto_column >= 0)
925 { /* goto column which was specified on command line and then undefine the column */
927 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
928 sci_set_current_position(editor->sci, new_pos, FALSE);
929 editor->scroll_percent = 0.5F;
930 cl_options.goto_column = -1;
931 return new_pos;
933 return sci_get_current_position(editor->sci);
937 /* Count lines that start with some hard tabs then a soft tab. */
938 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
940 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
941 ScintillaObject *sci = editor->sci;
942 gsize count = 0;
943 struct Sci_TextToFind ttf;
944 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
945 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
947 g_free(soft_tab);
949 ttf.chrg.cpMin = 0;
950 ttf.chrg.cpMax = sci_get_length(sci);
951 ttf.lpstrText = regex;
952 while (1)
954 gint pos;
956 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
957 if (pos == -1)
958 break; /* no more matches */
959 count++;
960 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
962 g_free(regex);
963 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
964 return count > sci_get_line_count(sci) * 0.02;
968 /* Detect the indent type based on counting the leading indent characters for each line.
969 * Returns whether detection succeeded, and the detected type in *type_ upon success */
970 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
972 GeanyEditor *editor = doc->editor;
973 ScintillaObject *sci = editor->sci;
974 gint line, line_count;
975 gsize tabs = 0, spaces = 0;
977 if (detect_tabs_and_spaces(editor))
979 *type_ = GEANY_INDENT_TYPE_BOTH;
980 return TRUE;
983 line_count = sci_get_line_count(sci);
984 for (line = 0; line < line_count; line++)
986 gint pos = sci_get_position_from_line(sci, line);
987 gchar c;
989 /* most code will have indent total <= 24, otherwise it's more likely to be
990 * alignment than indentation */
991 if (sci_get_line_indentation(sci, line) > 24)
992 continue;
994 c = sci_get_char_at(sci, pos);
995 if (c == '\t')
996 tabs++;
997 /* check for at least 2 spaces */
998 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
999 spaces++;
1001 if (spaces == 0 && tabs == 0)
1002 return FALSE;
1004 /* the factors may need to be tweaked */
1005 if (spaces > tabs * 4)
1006 *type_ = GEANY_INDENT_TYPE_SPACES;
1007 else if (tabs > spaces * 4)
1008 *type_ = GEANY_INDENT_TYPE_TABS;
1009 else
1010 *type_ = GEANY_INDENT_TYPE_BOTH;
1012 return TRUE;
1016 /* Detect the indent width based on counting the leading indent characters for each line.
1017 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1018 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1020 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1021 ScintillaObject *sci = editor->sci;
1022 gint line, line_count;
1023 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1024 gint count, width, i;
1026 /* can't easily detect the supposed width of a tab, guess the default is OK */
1027 if (type == GEANY_INDENT_TYPE_TABS)
1028 return FALSE;
1030 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1031 sci_set_tab_width(sci, 8);
1033 line_count = sci_get_line_count(sci);
1034 for (line = 0; line < line_count; line++)
1036 gint pos = sci_get_line_indent_position(sci, line);
1038 /* We probably don't have style info yet, because we're generally called just after
1039 * the document got created, so we can't use highlighting_is_code_style().
1040 * That's not good, but the assumption below that concerning lines start with an
1041 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1042 * without removing too much legitimate lines. */
1043 if (sci_get_char_at(sci, pos) == '*')
1044 continue;
1046 width = sci_get_line_indentation(sci, line);
1047 /* most code will have indent total <= 24, otherwise it's more likely to be
1048 * alignment than indentation */
1049 if (width > 24)
1050 continue;
1051 /* < 2 is no indentation */
1052 if (width < 2)
1053 continue;
1055 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1057 if ((width % (i + 2)) == 0)
1058 widths[i]++;
1061 count = 0;
1062 width = iprefs->width;
1063 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1065 /* give large indents higher weight not to be fooled by spurious indents */
1066 if (widths[i] >= count * 1.5)
1068 width = i + 2;
1069 count = widths[i];
1073 if (count == 0)
1074 return FALSE;
1076 *width_ = width;
1077 return TRUE;
1081 /* same as detect_indent_width() but uses editor's indent type */
1082 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1084 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1088 void document_apply_indent_settings(GeanyDocument *doc)
1090 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1091 GeanyIndentType type = iprefs->type;
1092 gint width = iprefs->width;
1094 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1096 if (type != iprefs->type)
1098 const gchar *name = NULL;
1100 switch (type)
1102 case GEANY_INDENT_TYPE_SPACES:
1103 name = _("Spaces");
1104 break;
1105 case GEANY_INDENT_TYPE_TABS:
1106 name = _("Tabs");
1107 break;
1108 case GEANY_INDENT_TYPE_BOTH:
1109 name = _("Tabs and Spaces");
1110 break;
1112 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1113 * and Spaces), the second one is the filename */
1114 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1115 DOC_FILENAME(doc));
1118 else if (doc->file_type->indent_type > -1)
1119 type = doc->file_type->indent_type;
1121 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1123 if (width != iprefs->width)
1125 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1126 DOC_FILENAME(doc));
1129 else if (doc->file_type->indent_width > -1)
1130 width = doc->file_type->indent_width;
1132 editor_set_indent(doc->editor, type, width);
1136 void document_show_tab(GeanyDocument *doc)
1138 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1139 document_get_notebook_page(doc));
1143 /* To open a new file, set doc to NULL; filename should be locale encoded.
1144 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1145 * pos is the cursor position, which can be overridden by --line and --column.
1146 * forced_enc can be NULL to detect the file encoding.
1147 * Returns: doc of the opened file or NULL if an error occurred. */
1148 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1149 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1151 gint editor_mode;
1152 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1153 gchar *utf8_filename = NULL;
1154 gchar *display_filename = NULL;
1155 gchar *locale_filename = NULL;
1156 GeanyFiletype *use_ft;
1157 FileData filedata;
1159 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1161 if (reload)
1163 utf8_filename = g_strdup(doc->file_name);
1164 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1166 else
1168 /* filename must not be NULL when opening a file */
1169 g_return_val_if_fail(filename, NULL);
1171 #ifdef G_OS_WIN32
1172 /* if filename is a shortcut, try to resolve it */
1173 locale_filename = win32_get_shortcut_target(filename);
1174 #else
1175 locale_filename = g_strdup(filename);
1176 #endif
1177 /* remove relative junk */
1178 utils_tidy_path(locale_filename);
1180 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1181 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1183 /* if file is already open, switch to it and go */
1184 doc = document_find_by_filename(utf8_filename);
1185 if (doc != NULL)
1187 ui_add_recent_document(doc); /* either add or reorder recent item */
1188 /* show the doc before reload dialog */
1189 document_show_tab(doc);
1190 document_check_disk_status(doc, TRUE); /* force a file changed check */
1193 if (reload || doc == NULL)
1194 { /* doc possibly changed */
1195 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1197 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1199 g_free(display_filename);
1200 g_free(utf8_filename);
1201 g_free(locale_filename);
1202 return NULL;
1205 if (! reload)
1207 doc = document_create(utf8_filename);
1208 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1210 /* file exists on disk, set real_path */
1211 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1213 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1214 monitor_file_setup(doc);
1217 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1218 sci_empty_undo_buffer(doc->editor->sci);
1220 /* add the text to the ScintillaObject */
1221 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1222 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1223 queue_colourise(doc); /* Ensure the document gets colourised. */
1225 /* detect & set line endings */
1226 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1227 sci_set_eol_mode(doc->editor->sci, editor_mode);
1228 g_free(filedata.data);
1230 sci_set_undo_collection(doc->editor->sci, TRUE);
1232 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1233 g_free(doc->encoding); /* if reloading, free old encoding */
1234 doc->encoding = filedata.enc;
1235 doc->has_bom = filedata.bom;
1236 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1238 doc->readonly = readonly || filedata.readonly;
1239 sci_set_readonly(doc->editor->sci, doc->readonly);
1240 doc->priv->protected = 0;
1242 /* update line number margin width */
1243 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1244 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1246 if (! reload)
1249 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1250 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1251 doc->editor);
1253 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1255 else
1256 { /* reloading */
1257 document_undo_clear(doc);
1259 use_ft = ft;
1261 /* update taglist, typedef keywords and build menu if necessary */
1262 document_set_filetype(doc, use_ft);
1264 /* set indentation settings after setting the filetype */
1265 if (reload)
1266 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1267 else
1268 document_apply_indent_settings(doc);
1270 document_set_text_changed(doc, FALSE); /* also updates tab state */
1271 ui_document_show_hide(doc); /* update the document menu */
1273 /* finally add current file to recent files menu, but not the files from the last session */
1274 if (! main_status.opening_session_files)
1275 ui_add_recent_document(doc);
1277 if (reload)
1279 g_signal_emit_by_name(geany_object, "document-reload", doc);
1280 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1282 else
1284 g_signal_emit_by_name(geany_object, "document-open", doc);
1285 /* For translators: this is the status window message for opening a file. %d is the number
1286 * of the newly opened file, %s indicates whether the file is opened read-only
1287 * (it is replaced with the string ", read-only"). */
1288 msgwin_status_add(_("File %s opened(%d%s)."),
1289 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1290 (readonly) ? _(", read-only") : "");
1294 g_free(display_filename);
1295 g_free(utf8_filename);
1296 g_free(locale_filename);
1298 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1299 pos = set_cursor_position(doc->editor, pos);
1300 /* now bring the file in front */
1301 editor_goto_pos(doc->editor, pos, FALSE);
1303 /* finally, let the editor widget grab the focus so you can start coding
1304 * right away */
1305 g_idle_add(on_idle_focus, doc);
1306 return doc;
1310 /* Takes a new line separated list of filename URIs and opens each file.
1311 * length is the length of the string */
1312 void document_open_file_list(const gchar *data, gsize length)
1314 guint i;
1315 gchar *filename;
1316 gchar **list;
1318 g_return_if_fail(data != NULL);
1320 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1322 /* stop at the end or first empty item, because last item is empty but not null */
1323 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1325 filename = utils_get_path_from_uri(list[i]);
1326 if (filename == NULL)
1327 continue;
1328 document_open_file(filename, FALSE, NULL, NULL);
1329 g_free(filename);
1332 g_strfreev(list);
1337 * Opens each file in the list @a filenames.
1338 * Internally, document_open_file() is called for every list item.
1340 * @param filenames A list of filenames to load, in locale encoding.
1341 * @param readonly Whether to open the document in read-only mode.
1342 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1343 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1345 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1346 const gchar *forced_enc)
1348 const GSList *item;
1350 for (item = filenames; item != NULL; item = g_slist_next(item))
1352 document_open_file(item->data, readonly, ft, forced_enc);
1358 * Reloads the document with the specified file encoding
1359 * @a forced_enc or @c NULL to auto-detect the file encoding.
1361 * @param doc The document to reload.
1362 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1364 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1366 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1368 gint pos = 0;
1369 GeanyDocument *new_doc;
1371 g_return_val_if_fail(doc != NULL, FALSE);
1373 /* Use cancel because the response handler would call this recursively */
1374 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1375 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1377 /* try to set the cursor to the position before reloading */
1378 pos = sci_get_current_position(doc->editor->sci);
1379 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1381 return (new_doc != NULL);
1385 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1387 #ifndef USE_GIO_FILEMON
1388 struct stat st;
1390 g_return_val_if_fail(doc != NULL, FALSE);
1392 /* stat the file to get the timestamp, otherwise on Windows the actual
1393 * timestamp can be ahead of time(NULL) */
1394 if (g_stat(locale_filename, &st) != 0)
1396 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1397 g_strerror(errno));
1398 return FALSE;
1401 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1402 #endif
1403 return TRUE;
1407 /* Sets line and column to the given position byte_pos in the document.
1408 * byte_pos is the position counted in bytes, not characters */
1409 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1411 gint i;
1412 gint line_start;
1414 /* for some reason we can use byte count instead of character count here */
1415 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1416 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1417 /* get the column in the line */
1418 *column = byte_pos - line_start;
1420 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1421 * skip one byte(i++) and decrease the column number which is based on byte count */
1422 for (i = line_start; i < (line_start + *column); i++)
1424 if (sci_get_char_at(doc->editor->sci, i) < 0)
1426 (*column)--;
1427 i++;
1433 static void replace_header_filename(GeanyDocument *doc)
1435 gchar *filebase;
1436 gchar *filename;
1437 struct Sci_TextToFind ttf;
1439 g_return_if_fail(doc != NULL);
1440 g_return_if_fail(doc->file_type != NULL);
1442 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1443 if (doc->file_type->extension)
1444 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1445 else
1446 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1448 filename = g_path_get_basename(doc->file_name);
1450 /* only search the first 3 lines */
1451 ttf.chrg.cpMin = 0;
1452 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1453 ttf.lpstrText = filebase;
1455 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf, NULL) != -1)
1457 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1458 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1459 sci_replace_target(doc->editor->sci, filename, FALSE);
1461 g_free(filebase);
1462 g_free(filename);
1467 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1468 * you still have to call @ref document_save_file_as() to change the @a doc object.
1469 * It also stops monitoring for file changes to prevent receiving too many file change events
1470 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1472 * @param doc The current document which should be renamed.
1473 * @param new_filename The new filename in UTF-8 encoding.
1475 * @since 0.16
1477 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1479 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1480 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1481 gint result;
1483 /* stop file monitoring to avoid getting events for deleting/creating files,
1484 * it's re-setup in document_save_file_as() */
1485 document_stop_file_monitoring(doc);
1487 result = g_rename(old_locale_filename, new_locale_filename);
1488 if (result != 0)
1490 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1491 _("Error renaming file."), g_strerror(errno));
1493 g_free(old_locale_filename);
1494 g_free(new_locale_filename);
1498 static void protect_document(GeanyDocument *doc)
1500 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1501 if (!doc->priv->protected++)
1502 sci_set_readonly(doc->editor->sci, TRUE);
1505 static void unprotect_document(GeanyDocument *doc)
1507 g_return_if_fail(doc->priv->protected > 0);
1509 if (!--doc->priv->protected && doc->readonly == FALSE)
1510 sci_set_readonly(doc->editor->sci, FALSE);
1514 /* Return TRUE if the document doesn't have a full filename set.
1515 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1516 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1517 * new files. */
1518 gboolean document_need_save_as(GeanyDocument *doc)
1520 g_return_val_if_fail(doc != NULL, FALSE);
1522 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1527 * Saves the document, detecting the filetype.
1529 * @param doc The document for the file to save.
1530 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1531 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1533 * @see document_save_file().
1535 * @since 0.16
1537 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1539 gboolean ret;
1540 gboolean new_file;
1542 g_return_val_if_fail(doc != NULL, FALSE);
1544 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1545 if (utf8_fname != NULL)
1546 SETPTR(doc->file_name, g_strdup(utf8_fname));
1548 /* reset real path, it's retrieved again in document_save() */
1549 SETPTR(doc->real_path, NULL);
1551 /* detect filetype */
1552 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1554 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1556 document_set_filetype(doc, ft);
1557 if (document_get_current() == doc)
1559 ignore_callback = TRUE;
1560 filetypes_select_radio_item(doc->file_type);
1561 ignore_callback = FALSE;
1565 if (new_file)
1567 sci_set_readonly(doc->editor->sci, FALSE);
1568 doc->readonly = FALSE;
1569 if (doc->priv->protected > 0)
1570 unprotect_document(doc);
1573 replace_header_filename(doc);
1575 ret = document_save_file(doc, TRUE);
1577 /* file monitoring support, add file monitoring after the file has been saved
1578 * to ignore any earlier events */
1579 monitor_file_setup(doc);
1580 doc->priv->file_disk_status = FILE_IGNORE;
1582 if (ret)
1583 ui_add_recent_document(doc);
1584 return ret;
1588 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1590 GError *conv_error = NULL;
1591 gchar* conv_file_contents = NULL;
1592 gsize bytes_read;
1593 gsize conv_len;
1595 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1596 g_return_val_if_fail(len != NULL, FALSE);
1598 /* try to convert it from UTF-8 to original encoding */
1599 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1600 &bytes_read, &conv_len, &conv_error);
1602 if (conv_error != NULL)
1604 gchar *text = g_strdup_printf(
1605 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1606 doc->encoding);
1607 gchar *error_text;
1609 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1611 gint line, column;
1612 gint context_len;
1613 gunichar unic;
1614 /* don't read over the doc length */
1615 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1616 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1617 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1619 /* take only one valid Unicode character from the context and discard the leftover */
1620 unic = g_utf8_get_char_validated(context, -1);
1621 context_len = g_unichar_to_utf8(unic, context);
1622 context[context_len] = '\0';
1623 get_line_column_from_pos(doc, bytes_read, &line, &column);
1625 error_text = g_strdup_printf(
1626 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1627 conv_error->message, context, line + 1, column);
1629 else
1630 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1632 geany_debug("encoding error: %s", conv_error->message);
1633 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1634 g_error_free(conv_error);
1635 g_free(text);
1636 g_free(error_text);
1637 return FALSE;
1639 else
1641 g_free(*data);
1642 *data = conv_file_contents;
1643 *len = conv_len;
1645 return TRUE;
1649 static gchar *write_data_to_disk(const gchar *locale_filename,
1650 const gchar *data, gsize len)
1652 GError *error = NULL;
1654 if (file_prefs.use_safe_file_saving)
1656 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1657 * This is the only option that handles disk space exhaustion. */
1658 if (g_file_set_contents(locale_filename, data, len, &error))
1659 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1661 else if (file_prefs.use_gio_unsafe_file_saving)
1663 GFile *fp;
1665 /* Use GIO API to save file (GVFS-safe)
1666 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1667 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1668 fp = g_file_new_for_path(locale_filename);
1669 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1670 G_FILE_CREATE_NONE, NULL, NULL, &error);
1671 g_object_unref(fp);
1673 else
1675 FILE *fp;
1676 int save_errno;
1677 gchar *display_name = g_filename_display_name(locale_filename);
1679 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1680 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1681 errno = 0;
1682 fp = g_fopen(locale_filename, "wb");
1683 if (fp == NULL)
1685 save_errno = errno;
1687 g_set_error(&error,
1688 G_FILE_ERROR,
1689 g_file_error_from_errno(save_errno),
1690 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1691 display_name,
1692 g_strerror(save_errno));
1694 else
1696 gsize bytes_written;
1698 errno = 0;
1699 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1701 if (len != bytes_written)
1703 save_errno = errno;
1705 g_set_error(&error,
1706 G_FILE_ERROR,
1707 g_file_error_from_errno(save_errno),
1708 _("Failed to write file '%s': fwrite() failed: %s"),
1709 display_name,
1710 g_strerror(save_errno));
1713 errno = 0;
1714 /* preserve the fwrite() error if any */
1715 if (fclose(fp) != 0 && error == NULL)
1717 save_errno = errno;
1719 g_set_error(&error,
1720 G_FILE_ERROR,
1721 g_file_error_from_errno(save_errno),
1722 _("Failed to close file '%s': fclose() failed: %s"),
1723 display_name,
1724 g_strerror(save_errno));
1728 g_free(display_name);
1730 if (error != NULL)
1732 gchar *msg = g_strdup(error->message);
1733 g_error_free(error);
1734 /* geany will warn about file truncation for unsafe saving below */
1735 return msg;
1737 return NULL;
1741 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1742 const gchar *data, gsize len)
1744 gchar *err;
1746 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1747 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1749 err = write_data_to_disk(locale_filename, data, len);
1750 if (err)
1751 return err;
1753 /* now the file is on disk, set real_path */
1754 if (doc->real_path == NULL)
1756 doc->real_path = tm_get_real_path(locale_filename);
1757 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1758 monitor_file_setup(doc);
1760 return NULL;
1764 * Saves the document.
1765 * Also shows the Save As dialog if necessary.
1766 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1768 * Saving may include replacing tabs with spaces,
1769 * stripping trailing spaces and adding a final new line at the end of the file, depending
1770 * on user preferences. Then the @c "document-before-save" signal is emitted,
1771 * allowing plugins to modify the document before it is saved, and data is
1772 * actually written to disk.
1774 * On successful saving:
1775 * - GeanyDocument::real_path is set.
1776 * - The filetype is set again or auto-detected if it wasn't set yet.
1777 * - The @c "document-save" signal is emitted for plugins.
1779 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1780 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1781 * added in Geany 1.22.
1783 * @param doc The document to save.
1784 * @param force Whether to save the file even if it is not modified.
1786 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1788 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1790 gchar *errmsg;
1791 gchar *data;
1792 gsize len;
1793 gchar *locale_filename;
1794 const GeanyFilePrefs *fp;
1796 g_return_val_if_fail(doc != NULL, FALSE);
1798 if (document_need_save_as(doc))
1800 /* ensure doc is the current tab before showing the dialog */
1801 document_show_tab(doc);
1802 return dialogs_show_save_as();
1805 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1806 if (doc->readonly || doc->priv->protected)
1807 return FALSE;
1808 if (!force && !doc->changed)
1809 return FALSE;
1811 fp = project_get_file_prefs();
1812 /* replaces tabs with spaces but only if the current file is not a Makefile */
1813 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1814 editor_replace_tabs(doc->editor);
1815 /* strip trailing spaces */
1816 if (fp->strip_trailing_spaces)
1817 editor_strip_trailing_spaces(doc->editor);
1818 /* ensure the file has a newline at the end */
1819 if (fp->final_new_line)
1820 editor_ensure_final_newline(doc->editor);
1821 /* ensure newlines are consistent */
1822 if (fp->ensure_convert_new_lines)
1823 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1825 /* notify plugins which may wish to modify the document before it's saved */
1826 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1828 len = sci_get_length(doc->editor->sci) + 1;
1829 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1830 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1831 * encoding, it will be converted to doc->encoding below and this conversion
1832 * also changes the BOM */
1833 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1834 data[0] = (gchar) 0xef;
1835 data[1] = (gchar) 0xbb;
1836 data[2] = (gchar) 0xbf;
1837 sci_get_text(doc->editor->sci, len, data + 3);
1838 len += 3;
1840 else
1842 data = (gchar*) g_malloc(len);
1843 sci_get_text(doc->editor->sci, len, data);
1846 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1847 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1848 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1850 if (! save_convert_to_encoding(doc, &data, &len))
1852 g_free(data);
1853 return FALSE;
1856 else
1858 len = strlen(data);
1861 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1863 /* ignore file changed notification when the file is written */
1864 doc->priv->file_disk_status = FILE_IGNORE;
1866 /* actually write the content of data to the file on disk */
1867 errmsg = save_doc(doc, locale_filename, data, len);
1868 g_free(data);
1870 if (errmsg != NULL)
1872 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1874 if (!file_prefs.use_safe_file_saving)
1876 SETPTR(errmsg,
1877 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1879 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1880 doc->priv->file_disk_status = FILE_OK;
1881 utils_beep();
1882 g_free(locale_filename);
1883 g_free(errmsg);
1884 return FALSE;
1887 /* store the opened encoding for undo/redo */
1888 store_saved_encoding(doc);
1890 /* ignore the following things if we are quitting */
1891 if (! main_status.quitting)
1893 sci_set_savepoint(doc->editor->sci);
1895 if (file_prefs.disk_check_timeout > 0)
1896 document_update_timestamp(doc, locale_filename);
1898 /* update filetype-related things */
1899 document_set_filetype(doc, doc->file_type);
1901 document_update_tab_label(doc);
1903 msgwin_status_add(_("File %s saved."), doc->file_name);
1904 ui_update_statusbar(doc, -1);
1905 #ifdef HAVE_VTE
1906 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1907 #endif
1909 g_free(locale_filename);
1911 g_signal_emit_by_name(geany_object, "document-save", doc);
1913 return TRUE;
1917 /* special search function, used from the find entry in the toolbar
1918 * return TRUE if text was found otherwise FALSE
1919 * return also TRUE if text is empty */
1920 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1921 gboolean backwards)
1923 gint start_pos, search_pos;
1924 struct Sci_TextToFind ttf;
1926 g_return_val_if_fail(text != NULL, FALSE);
1927 g_return_val_if_fail(doc != NULL, FALSE);
1928 if (! *text)
1929 return TRUE;
1931 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1932 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1934 /* search cursor to end or start */
1935 ttf.chrg.cpMin = start_pos;
1936 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1937 ttf.lpstrText = (gchar *)text;
1938 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1940 /* if no match, search start (or end) to cursor */
1941 if (search_pos == -1)
1943 if (backwards)
1945 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1946 ttf.chrg.cpMax = start_pos;
1948 else
1950 ttf.chrg.cpMin = 0;
1951 ttf.chrg.cpMax = start_pos + strlen(text);
1953 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1956 if (search_pos != -1)
1958 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1960 /* unfold maybe folded results */
1961 sci_ensure_line_is_visible(doc->editor->sci, line);
1963 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1964 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1966 if (! editor_line_in_view(doc->editor, line))
1967 { /* we need to force scrolling in case the cursor is outside of the current visible area
1968 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1969 * while searching */
1970 editor_scroll_to_line(doc->editor, -1, 0.3F);
1972 else
1973 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1974 return TRUE;
1976 else
1978 if (! inc)
1980 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1982 utils_beep();
1983 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1984 return FALSE;
1989 /* General search function, used from the find dialog.
1990 * Returns -1 on failure or the start position of the matching text.
1991 * Will skip past any selection, ignoring it.
1993 * @param text Text to find.
1994 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1996 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
1997 gint flags, gboolean search_backwards, GeanyMatchInfo **match_,
1998 gboolean scroll, GtkWidget *parent)
2000 gint selection_end, selection_start, search_pos;
2002 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2003 if (! *text)
2004 return -1;
2006 /* Sci doesn't support searching backwards with a regex */
2007 if (flags & SCFIND_REGEXP)
2008 search_backwards = FALSE;
2010 if (!original_text)
2011 original_text = text;
2013 selection_start = sci_get_selection_start(doc->editor->sci);
2014 selection_end = sci_get_selection_end(doc->editor->sci);
2015 if ((selection_end - selection_start) > 0)
2016 { /* there's a selection so go to the end */
2017 if (search_backwards)
2018 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2019 else
2020 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2023 sci_set_search_anchor(doc->editor->sci);
2024 if (search_backwards)
2025 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2026 else
2027 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2029 if (search_pos != -1)
2031 /* unfold maybe folded results */
2032 sci_ensure_line_is_visible(doc->editor->sci,
2033 sci_get_line_from_position(doc->editor->sci, search_pos));
2034 if (scroll)
2035 doc->editor->scroll_percent = 0.3F;
2037 else
2039 gint sci_len = sci_get_length(doc->editor->sci);
2041 /* if we just searched the whole text, give up searching. */
2042 if ((selection_end == 0 && ! search_backwards) ||
2043 (selection_end == sci_len && search_backwards))
2045 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2046 utils_beep();
2047 return -1;
2050 /* we searched only part of the document, so ask whether to wraparound. */
2051 if (search_prefs.always_wrap ||
2052 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2053 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2055 gint ret;
2057 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2058 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2059 if (ret == -1)
2060 { /* return to original cursor position if not found */
2061 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2063 return ret;
2066 return search_pos;
2070 /* Replaces the selection if it matches, otherwise just finds the next match.
2071 * Returns: start of replaced text, or -1 if no replacement was made
2073 * @param find_text Text to find.
2074 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2076 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2077 const gchar *replace_text, gint flags, gboolean search_backwards)
2079 gint selection_end, selection_start, search_pos;
2080 GeanyMatchInfo *match = NULL;
2082 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2084 if (! *find_text)
2085 return -1;
2087 /* Sci doesn't support searching backwards with a regex */
2088 if (flags & SCFIND_REGEXP)
2089 search_backwards = FALSE;
2091 if (!original_find_text)
2092 original_find_text = find_text;
2094 selection_start = sci_get_selection_start(doc->editor->sci);
2095 selection_end = sci_get_selection_end(doc->editor->sci);
2096 if (selection_end == selection_start)
2098 /* no selection so just find the next match */
2099 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2100 return -1;
2102 /* there's a selection so go to the start before finding to search through it
2103 * this ensures there is a match */
2104 if (search_backwards)
2105 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2106 else
2107 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2109 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2110 /* return if the original selected text did not match (at the start of the selection) */
2111 if (search_pos != selection_start)
2113 if (search_pos != -1)
2114 geany_match_info_free(match);
2115 return -1;
2118 if (search_pos != -1)
2120 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2121 /* select the replacement - find text will skip past the selected text */
2122 sci_set_selection_start(doc->editor->sci, search_pos);
2123 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2124 geany_match_info_free(match);
2126 else
2128 /* no match in the selection */
2129 utils_beep();
2131 return search_pos;
2135 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2136 const gchar *original_replace_text)
2138 gchar *filename;
2140 if (count == 0)
2142 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2143 return;
2146 filename = g_path_get_basename(DOC_FILENAME(doc));
2147 ui_set_statusbar(TRUE, ngettext(
2148 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2149 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2150 count), filename, count, original_find_text, original_replace_text);
2151 g_free(filename);
2155 /* Replace all text matches in a certain range within document.
2156 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2157 * or -1 if no text was found.
2158 * scroll_to_match is whether to scroll the last replacement in view (which also
2159 * clears the selection).
2160 * Returns: the number of replacements made. */
2161 static guint
2162 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2163 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2165 gint count = 0;
2166 struct Sci_TextToFind ttf;
2167 ScintillaObject *sci;
2169 if (new_range_end != NULL)
2170 *new_range_end = -1;
2172 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2174 if (! *find_text || doc->readonly)
2175 return 0;
2177 sci = doc->editor->sci;
2179 ttf.chrg.cpMin = start;
2180 ttf.chrg.cpMax = end;
2181 ttf.lpstrText = (gchar*)find_text;
2183 sci_start_undo_action(sci);
2184 count = search_replace_range(sci, &ttf, flags, replace_text);
2185 sci_end_undo_action(sci);
2187 if (count > 0)
2188 { /* scroll last match in view, will destroy the existing selection */
2189 if (scroll_to_match)
2190 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2192 if (new_range_end != NULL)
2193 *new_range_end = ttf.chrg.cpMax;
2195 return count;
2199 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2200 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2202 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2203 gint max_column = 0, count = 0;
2204 gboolean replaced = FALSE;
2206 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2208 if (! *find_text)
2209 return;
2211 selection_start = sci_get_selection_start(doc->editor->sci);
2212 selection_end = sci_get_selection_end(doc->editor->sci);
2213 /* do we have a selection? */
2214 if ((selection_end - selection_start) == 0)
2216 utils_beep();
2217 return;
2220 selection_mode = sci_get_selection_mode(doc->editor->sci);
2221 selected_lines = sci_get_lines_selected(doc->editor->sci);
2222 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2223 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2225 gint first_line, line;
2227 sci_start_undo_action(doc->editor->sci);
2229 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2230 /* Find the last line with chars selected (not EOL char) */
2231 last_line = sci_get_line_from_position(doc->editor->sci,
2232 selection_end - editor_get_eol_char_len(doc->editor));
2233 last_line = MAX(first_line, last_line);
2234 for (line = first_line; line < (first_line + selected_lines); line++)
2236 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2237 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2239 /* skip line if there is no selection */
2240 if (line_start != INVALID_POSITION)
2242 /* don't let document_replace_range() scroll to match to keep our selection */
2243 gint new_sel_end;
2245 count += document_replace_range(doc, find_text, replace_text, flags,
2246 line_start, line_end, FALSE, &new_sel_end);
2247 if (new_sel_end != -1)
2249 replaced = TRUE;
2250 /* this gets the greatest column within the selection after replacing */
2251 max_column = MAX(max_column,
2252 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2256 sci_end_undo_action(doc->editor->sci);
2258 else /* handle normal line selection */
2260 count += document_replace_range(doc, find_text, replace_text, flags,
2261 selection_start, selection_end, TRUE, &selection_end);
2262 if (selection_end != -1)
2263 replaced = TRUE;
2266 if (replaced)
2267 { /* update the selection for the new endpoint */
2269 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2271 /* now we can scroll to the selection and destroy it because we rebuild it later */
2272 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2274 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2275 * the highest column on the last line. The wrapped selection is completely different
2276 * from the original one, so skip the selection at all */
2277 /* TODO is there a better way to handle the wrapped selection? */
2278 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2279 { /* for keeping and adjusting the selection in multi line rectangle selection we
2280 * need the last line of the original selection and the greatest column number after
2281 * replacing and set the selection end to the last line at the greatest column */
2282 sci_set_selection_start(doc->editor->sci, selection_start);
2283 sci_set_selection_end(doc->editor->sci,
2284 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2285 sci_set_selection_mode(doc->editor->sci, selection_mode);
2288 else
2290 sci_set_selection_start(doc->editor->sci, selection_start);
2291 sci_set_selection_end(doc->editor->sci, selection_end);
2294 else /* no replacements */
2295 utils_beep();
2297 show_replace_summary(doc, count, original_find_text, original_replace_text);
2301 /* returns number of replacements made. */
2302 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2303 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2305 gint len, count;
2306 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2308 if (! *find_text)
2309 return FALSE;
2311 len = sci_get_length(doc->editor->sci);
2312 count = document_replace_range(
2313 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2315 show_replace_summary(doc, count, original_find_text, original_replace_text);
2316 return count;
2321 * Parses or re-parses the document's buffer and updates the type
2322 * keywords and symbol list.
2324 * @param doc The document.
2326 void document_update_tags(GeanyDocument *doc)
2328 guchar *buffer_ptr;
2329 gsize len;
2331 g_return_if_fail(DOC_VALID(doc));
2332 g_return_if_fail(app->tm_workspace != NULL);
2334 /* early out if it's a new file or doesn't support tags */
2335 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2337 /* We must call sidebar_update_tag_list() before returning,
2338 * to ensure that the symbol list is always updated properly (e.g.
2339 * when creating a new document with a partial filename set. */
2340 sidebar_update_tag_list(doc, FALSE);
2341 return;
2344 /* create a new TM file if there isn't one yet */
2345 if (! doc->tm_file)
2347 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2348 const gchar *name;
2350 /* lookup the name rather than using filetype name to support custom filetypes */
2351 name = tm_source_file_get_lang_name(doc->file_type->lang);
2352 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2353 g_free(locale_filename);
2355 if (doc->tm_file && !tm_workspace_add_object(doc->tm_file))
2357 tm_work_object_free(doc->tm_file);
2358 doc->tm_file = NULL;
2362 /* early out if there's no work object and we couldn't create one */
2363 if (doc->tm_file == NULL)
2365 /* We must call sidebar_update_tag_list() before returning,
2366 * to ensure that the symbol list is always updated properly (e.g.
2367 * when creating a new document with a partial filename set. */
2368 sidebar_update_tag_list(doc, FALSE);
2369 return;
2372 len = sci_get_length(doc->editor->sci);
2373 /* tm_source_file_buffer_update() below don't support 0-length data,
2374 * so just empty the tags array and leave */
2375 if (len < 1)
2377 tm_tags_array_free(doc->tm_file->tags_array, FALSE);
2378 sidebar_update_tag_list(doc, FALSE);
2379 return;
2382 /* Parse Scintilla's buffer directly using TagManager
2383 * Note: this buffer *MUST NOT* be modified */
2384 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2385 tm_source_file_buffer_update(doc->tm_file, buffer_ptr, len, TRUE);
2387 sidebar_update_tag_list(doc, TRUE);
2388 document_highlight_tags(doc);
2392 /* Re-highlights type keywords without re-parsing the whole document. */
2393 void document_highlight_tags(GeanyDocument *doc)
2395 GString *keywords_str;
2396 gchar *keywords;
2397 gint keyword_idx;
2399 /* some filetypes support type keywords (such as struct names), but not
2400 * necessarily all filetypes for a particular scintilla lexer. this
2401 * tells us whether the filetype supports keywords, and if so
2402 * which index to use for the scintilla keywords set. */
2403 switch (doc->file_type->id)
2405 case GEANY_FILETYPES_C:
2406 case GEANY_FILETYPES_CPP:
2407 case GEANY_FILETYPES_CS:
2408 case GEANY_FILETYPES_D:
2409 case GEANY_FILETYPES_JAVA:
2410 case GEANY_FILETYPES_OBJECTIVEC:
2411 case GEANY_FILETYPES_VALA:
2412 case GEANY_FILETYPES_RUST:
2415 /* index of the keyword set in the Scintilla lexer, for
2416 * example in LexCPP.cxx, see "cppWordLists" global array.
2417 * TODO: this magic number should be a member of the filetype */
2418 keyword_idx = 3;
2419 break;
2421 default:
2422 return; /* early out if type keywords are not supported */
2424 if (!app->tm_workspace->work_object.tags_array)
2425 return;
2427 /* get any type keywords and tell scintilla about them
2428 * this will cause the type keywords to be colourized in scintilla */
2429 keywords_str = symbols_find_tags_as_string(app->tm_workspace->work_object.tags_array,
2430 TM_GLOBAL_TYPE_MASK, doc->file_type->lang);
2431 if (keywords_str)
2433 keywords = g_string_free(keywords_str, FALSE);
2434 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2435 g_free(keywords);
2436 queue_colourise(doc); /* force re-highlighting the entire document */
2441 static gboolean on_document_update_tag_list_idle(gpointer data)
2443 GeanyDocument *doc = data;
2445 if (! DOC_VALID(doc))
2446 return FALSE;
2448 if (! main_status.quitting)
2449 document_update_tags(doc);
2451 doc->priv->tag_list_update_source = 0;
2453 /* don't update the tags until another modification of the buffer */
2454 return FALSE;
2458 void document_update_tag_list_in_idle(GeanyDocument *doc)
2460 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2461 return;
2463 /* prevent "stacking up" callback handlers, we only need one to run soon */
2464 if (doc->priv->tag_list_update_source != 0)
2465 g_source_remove(doc->priv->tag_list_update_source);
2467 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2468 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2472 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2473 gboolean filetype_changed)
2475 g_return_if_fail(doc);
2476 if (type == NULL)
2477 type = filetypes[GEANY_FILETYPES_NONE];
2479 if (filetype_changed)
2481 doc->file_type = type;
2483 /* delete tm file object to force creation of a new one */
2484 if (doc->tm_file != NULL)
2486 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2487 doc->tm_file = NULL;
2489 /* load tags files before highlighting (some lexers highlight global typenames) */
2490 if (type->id != GEANY_FILETYPES_NONE)
2491 symbols_global_tags_loaded(type->id);
2493 highlighting_set_styles(doc->editor->sci, type);
2494 editor_set_indentation_guides(doc->editor);
2495 build_menu_update(doc);
2496 queue_colourise(doc);
2497 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2500 document_update_tags(doc);
2504 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2505 * @param doc The document to use.
2506 * @param type The filetype. */
2507 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2509 gboolean ft_changed;
2510 GeanyFiletype *old_ft;
2512 g_return_if_fail(doc);
2513 if (type == NULL)
2514 type = filetypes[GEANY_FILETYPES_NONE];
2516 old_ft = doc->file_type;
2517 geany_debug("%s : %s (%s)",
2518 (doc->file_name != NULL) ? doc->file_name : "unknown",
2519 type->name,
2520 (doc->encoding != NULL) ? doc->encoding : "unknown");
2522 ft_changed = (doc->file_type != type); /* filetype has changed */
2523 document_load_config(doc, type, ft_changed);
2525 if (ft_changed)
2527 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2529 /* assume that if previous filetype was none and the settings are the default ones, this
2530 * is the first time the filetype is carefully set, so we should apply indent settings */
2531 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2532 doc->editor->indent_type == iprefs->type &&
2533 doc->editor->indent_width == iprefs->width)
2535 document_apply_indent_settings(doc);
2536 ui_document_show_hide(doc);
2539 sidebar_openfiles_update(doc); /* to update the icon */
2540 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2545 void document_reload_config(GeanyDocument *doc)
2547 document_load_config(doc, doc->file_type, TRUE);
2552 * Sets the encoding of a document.
2553 * This function only set the encoding of the %document, it does not any conversions. The new
2554 * encoding is used when e.g. saving the file.
2556 * @param doc The document to use.
2557 * @param new_encoding The encoding to be set for the document.
2559 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2561 if (doc == NULL || new_encoding == NULL ||
2562 utils_str_equal(new_encoding, doc->encoding))
2563 return;
2565 g_free(doc->encoding);
2566 doc->encoding = g_strdup(new_encoding);
2568 ui_update_statusbar(doc, -1);
2569 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2570 encodings_is_unicode_charset(doc->encoding));
2574 /* own Undo / Redo implementation to be able to undo / redo changes
2575 * to the encoding or the Unicode BOM (which are Scintilla independet).
2576 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2578 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2579 void document_undo_clear(GeanyDocument *doc)
2581 undo_action *a;
2583 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2585 a = g_trash_stack_pop(&doc->priv->undo_actions);
2586 if (G_LIKELY(a != NULL))
2588 switch (a->type)
2590 case UNDO_ENCODING: g_free(a->data); break;
2591 default: break;
2593 g_free(a);
2596 doc->priv->undo_actions = NULL;
2598 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2600 a = g_trash_stack_pop(&doc->priv->redo_actions);
2601 if (G_LIKELY(a != NULL))
2603 switch (a->type)
2605 case UNDO_ENCODING: g_free(a->data); break;
2606 default: break;
2608 g_free(a);
2611 doc->priv->redo_actions = NULL;
2613 if (! main_status.quitting && doc->editor != NULL)
2614 document_set_text_changed(doc, FALSE);
2618 /* note: this is called on SCN_MODIFIED notifications */
2619 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2621 undo_action *action;
2623 g_return_if_fail(doc != NULL);
2625 action = g_new0(undo_action, 1);
2626 action->type = type;
2627 action->data = data;
2629 g_trash_stack_push(&doc->priv->undo_actions, action);
2631 /* avoid unnecessary redraws */
2632 if (type != UNDO_SCINTILLA || !doc->changed)
2633 document_set_text_changed(doc, TRUE);
2635 ui_update_popup_reundo_items(doc);
2639 gboolean document_can_undo(GeanyDocument *doc)
2641 g_return_val_if_fail(doc != NULL, FALSE);
2643 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2644 return TRUE;
2645 else
2646 return FALSE;
2650 static void update_changed_state(GeanyDocument *doc)
2652 doc->changed =
2653 (sci_is_modified(doc->editor->sci) ||
2654 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2655 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2656 document_set_text_changed(doc, doc->changed);
2660 void document_undo(GeanyDocument *doc)
2662 undo_action *action;
2664 g_return_if_fail(doc != NULL);
2666 action = g_trash_stack_pop(&doc->priv->undo_actions);
2668 if (G_UNLIKELY(action == NULL))
2670 /* fallback, should not be necessary */
2671 geany_debug("%s: fallback used", G_STRFUNC);
2672 sci_undo(doc->editor->sci);
2674 else
2676 switch (action->type)
2678 case UNDO_SCINTILLA:
2680 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2682 sci_undo(doc->editor->sci);
2683 break;
2685 case UNDO_BOM:
2687 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2689 doc->has_bom = GPOINTER_TO_INT(action->data);
2690 ui_update_statusbar(doc, -1);
2691 ui_document_show_hide(doc);
2692 break;
2694 case UNDO_ENCODING:
2696 /* use the "old" encoding */
2697 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2699 document_set_encoding(doc, (const gchar*)action->data);
2701 ignore_callback = TRUE;
2702 encodings_select_radio_item((const gchar*)action->data);
2703 ignore_callback = FALSE;
2705 g_free(action->data);
2706 break;
2708 default: break;
2711 g_free(action); /* free the action which was taken from the stack */
2713 update_changed_state(doc);
2714 ui_update_popup_reundo_items(doc);
2718 gboolean document_can_redo(GeanyDocument *doc)
2720 g_return_val_if_fail(doc != NULL, FALSE);
2722 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2723 return TRUE;
2724 else
2725 return FALSE;
2729 void document_redo(GeanyDocument *doc)
2731 undo_action *action;
2733 g_return_if_fail(doc != NULL);
2735 action = g_trash_stack_pop(&doc->priv->redo_actions);
2737 if (G_UNLIKELY(action == NULL))
2739 /* fallback, should not be necessary */
2740 geany_debug("%s: fallback used", G_STRFUNC);
2741 sci_redo(doc->editor->sci);
2743 else
2745 switch (action->type)
2747 case UNDO_SCINTILLA:
2749 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2751 sci_redo(doc->editor->sci);
2752 break;
2754 case UNDO_BOM:
2756 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2758 doc->has_bom = GPOINTER_TO_INT(action->data);
2759 ui_update_statusbar(doc, -1);
2760 ui_document_show_hide(doc);
2761 break;
2763 case UNDO_ENCODING:
2765 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2767 document_set_encoding(doc, (const gchar*)action->data);
2769 ignore_callback = TRUE;
2770 encodings_select_radio_item((const gchar*)action->data);
2771 ignore_callback = FALSE;
2773 g_free(action->data);
2774 break;
2776 default: break;
2779 g_free(action); /* free the action which was taken from the stack */
2781 update_changed_state(doc);
2782 ui_update_popup_reundo_items(doc);
2786 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2788 undo_action *action;
2790 g_return_if_fail(doc != NULL);
2792 action = g_new0(undo_action, 1);
2793 action->type = type;
2794 action->data = data;
2796 g_trash_stack_push(&doc->priv->redo_actions, action);
2798 if (type != UNDO_SCINTILLA || !doc->changed)
2799 document_set_text_changed(doc, TRUE);
2801 ui_update_popup_reundo_items(doc);
2805 enum
2807 STATUS_CHANGED,
2808 #ifdef USE_GIO_FILEMON
2809 STATUS_DISK_CHANGED,
2810 #endif
2811 STATUS_READONLY
2813 static struct
2815 const gchar *name;
2816 GdkColor color;
2817 gboolean loaded;
2818 } document_status_styles[] = {
2819 { "geany-document-status-changed", {0}, FALSE },
2820 #ifdef USE_GIO_FILEMON
2821 { "geany-document-status-disk-changed", {0}, FALSE },
2822 #endif
2823 { "geany-document-status-readonly", {0}, FALSE }
2827 static gint document_get_status_id(GeanyDocument *doc)
2829 if (doc->changed)
2830 return STATUS_CHANGED;
2831 #ifdef USE_GIO_FILEMON
2832 else if (doc->priv->file_disk_status == FILE_CHANGED)
2833 return STATUS_DISK_CHANGED;
2834 #endif
2835 else if (doc->readonly)
2836 return STATUS_READONLY;
2838 return -1;
2842 /* returns an identifier that is to be set as a widget name or class to get it styled
2843 * depending on the document status (changed, readonly, etc.)
2844 * a NULL return value means default (unchanged) style */
2845 const gchar *document_get_status_widget_class(GeanyDocument *doc)
2847 gint status;
2849 g_return_val_if_fail(doc != NULL, NULL);
2851 status = document_get_status_id(doc);
2852 if (status < 0)
2853 return NULL;
2854 else
2855 return document_status_styles[status].name;
2860 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2861 * Returned colors are red if the document has changes, green if the document is read-only
2862 * or simply @c NULL if the document is unmodified but writable.
2864 * @param doc The document to use.
2866 * @return The color for the document or @c NULL if the default color should be used. The color
2867 * object is owned by Geany and should not be modified or freed.
2869 * @since 0.16
2871 const GdkColor *document_get_status_color(GeanyDocument *doc)
2873 gint status;
2875 g_return_val_if_fail(doc != NULL, NULL);
2877 status = document_get_status_id(doc);
2878 if (status < 0)
2879 return NULL;
2880 if (! document_status_styles[status].loaded)
2882 #if GTK_CHECK_VERSION(3, 0, 0)
2883 GdkRGBA color;
2884 GtkWidgetPath *path = gtk_widget_path_new();
2885 GtkStyleContext *ctx = gtk_style_context_new();
2886 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
2887 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
2888 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
2889 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
2890 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
2891 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
2892 gtk_style_context_set_path(ctx, path);
2893 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
2894 document_status_styles[status].color.red = 0xffff * color.red;
2895 document_status_styles[status].color.green = 0xffff * color.green;
2896 document_status_styles[status].color.blue = 0xffff * color.blue;
2897 document_status_styles[status].loaded = TRUE;
2898 gtk_widget_path_unref(path);
2899 g_object_unref(ctx);
2900 #else
2901 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
2902 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
2903 document_status_styles[status].name, NULL);
2904 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
2906 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
2907 document_status_styles[status].loaded = TRUE;
2908 g_free(path);
2909 #endif
2911 return &document_status_styles[status].color;
2915 /** Accessor function for @ref documents_array items.
2916 * @warning Always check the returned document is valid (@c doc->is_valid).
2917 * @param idx @c documents_array index.
2918 * @return The document, or @c NULL if @a idx is out of range.
2920 * @since 0.16
2922 GeanyDocument *document_index(gint idx)
2924 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2928 /* create a new file and copy file content and properties */
2929 G_MODULE_EXPORT void on_clone1_activate(GtkMenuItem *menuitem, gpointer user_data)
2931 GeanyDocument *old_doc = document_get_current();
2933 if (old_doc)
2934 document_clone(old_doc);
2938 GeanyDocument *document_clone(GeanyDocument *old_doc)
2940 gchar *text;
2941 GeanyDocument *doc;
2942 ScintillaObject *old_sci;
2944 g_return_val_if_fail(old_doc, NULL);
2945 old_sci = old_doc->editor->sci;
2946 if (sci_has_selection(old_sci))
2947 text = sci_get_selection_contents(old_sci);
2948 else
2949 text = sci_get_contents(old_sci, -1);
2951 doc = document_new_file(NULL, old_doc->file_type, text);
2952 g_free(text);
2953 document_set_text_changed(doc, TRUE);
2955 /* copy file properties */
2956 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2957 doc->editor->line_breaking = old_doc->editor->line_breaking;
2958 doc->editor->auto_indent = old_doc->editor->auto_indent;
2959 editor_set_indent(doc->editor, old_doc->editor->indent_type,
2960 old_doc->editor->indent_width);
2961 doc->readonly = old_doc->readonly;
2962 doc->has_bom = old_doc->has_bom;
2963 doc->priv->protected = 0;
2964 document_set_encoding(doc, old_doc->encoding);
2965 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2966 sci_set_readonly(doc->editor->sci, doc->readonly);
2968 /* update ui */
2969 ui_document_show_hide(doc);
2970 return doc;
2974 /* @note If successful, this should always be followed up with a call to
2975 * document_close_all().
2976 * @return TRUE if all files were saved or had their changes discarded. */
2977 gboolean document_account_for_unsaved(void)
2979 guint i, p, page_count;
2981 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2982 /* iterate over documents in tabs order */
2983 for (p = 0; p < page_count; p++)
2985 GeanyDocument *doc = document_get_from_page(p);
2987 if (DOC_VALID(doc) && doc->changed)
2989 if (! dialogs_show_unsaved_file(doc))
2990 return FALSE;
2993 /* all documents should now be accounted for, so ignore any changes */
2994 foreach_document (i)
2996 documents[i]->changed = FALSE;
2998 return TRUE;
3002 static void force_close_all(void)
3004 guint i, len = documents_array->len;
3006 /* check all documents have been accounted for */
3007 for (i = 0; i < len; i++)
3009 if (documents[i]->is_valid)
3011 g_return_if_fail(!documents[i]->changed);
3014 main_status.closing_all = TRUE;
3016 foreach_document(i)
3018 document_close(documents[i]);
3021 main_status.closing_all = FALSE;
3025 gboolean document_close_all(void)
3027 if (! document_account_for_unsaved())
3028 return FALSE;
3030 force_close_all();
3032 return TRUE;
3036 /* *
3037 * Shows a message related to a document.
3039 * Use this whenever the user needs to see a document-related message,
3040 * for example when the file was externally modified or deleted.
3042 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3043 * @a response_1 response will be the default for the @c GtkInfoBar or
3044 * @c GtkDialog.
3046 * @param doc @c GeanyDocument.
3047 * @param msgtype The type of message.
3048 * @param response_cb A callback function called when there's a response.
3049 * @param btn_1 The first action area button.
3050 * @param response_1 The response for @a btn_1.
3051 * @param btn_2 The second action area button.
3052 * @param response_2 The response for @a btn_2.
3053 * @param btn_3 The third action area button.
3054 * @param response_3 The response for @a btn_3.
3055 * @param extra_text Text to show below the main message.
3056 * @param format The text format for the main message.
3057 * @param ... Used with @a format as in @c printf.
3059 * @since 1.25
3060 * */
3061 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3062 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3063 const gchar *btn_1, GtkResponseType response_1,
3064 const gchar *btn_2, GtkResponseType response_2,
3065 const gchar *btn_3, GtkResponseType response_3,
3066 const gchar *extra_text, const gchar *format, ...)
3068 va_list args;
3069 gchar *text, *markup;
3070 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3071 GtkWidget *info_widget, *parent;
3072 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook),
3073 document_get_notebook_page(doc));
3075 va_start(args, format);
3076 text = g_strdup_vprintf(format, args);
3077 va_end(args);
3079 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3080 g_free(text);
3082 info_widget = gtk_info_bar_new();
3083 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3084 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3086 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3088 if (btn_1)
3089 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3090 if (btn_2)
3091 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3092 if (btn_3)
3093 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3095 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3097 label = geany_wrap_label_new(NULL);
3098 gtk_label_set_markup(GTK_LABEL(label), markup);
3099 g_free(markup);
3101 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3102 g_signal_connect_after(info_widget, "response", G_CALLBACK(gtk_widget_destroy), NULL);
3104 hbox = gtk_hbox_new(FALSE, 12);
3105 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3107 switch (msgtype)
3109 case GTK_MESSAGE_INFO:
3110 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3111 break;
3112 case GTK_MESSAGE_WARNING:
3113 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3114 break;
3115 case GTK_MESSAGE_QUESTION:
3116 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3117 break;
3118 case GTK_MESSAGE_ERROR:
3119 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3120 break;
3121 default:
3122 icon = NULL;
3123 break;
3126 if (icon)
3127 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3129 if (extra_text)
3131 vbox = gtk_vbox_new(FALSE, 6);
3132 extra_label = geany_wrap_label_new(extra_text);
3133 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3134 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3135 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3137 else
3138 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3140 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3142 gtk_widget_show_all(info_widget);
3144 return info_widget;
3147 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3149 unprotect_document(doc);
3150 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3152 if (response_id == GTK_RESPONSE_ACCEPT)
3153 document_reload_file(doc, doc->encoding);
3156 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3158 GtkInfoBar *bar = GTK_INFO_BAR(data);
3160 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3162 switch (event->keyval)
3164 case GDK_Tab:
3165 case GDK_ISO_Left_Tab:
3167 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3168 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3169 gtk_widget_child_focus(action_area, dir);
3170 return TRUE;
3172 case GDK_Escape:
3174 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3175 return TRUE;
3177 default:
3178 return FALSE;
3182 /* g_signal_handlers_disconnect_by_data is a macro that cannot be used as GCallback */
3183 static void on_bar_unrealize(GtkWidget *bar, ScintillaObject *sci)
3185 g_signal_handlers_disconnect_by_func(sci, on_sci_key, bar);
3188 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3190 g_signal_connect(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar);
3191 /* make the signal disconnect automatically */
3192 g_signal_connect(bar, "unrealize", G_CALLBACK(on_bar_unrealize), doc->editor->sci);
3195 static void monitor_reload_file(GeanyDocument *doc)
3197 gchar *base_name = g_path_get_basename(doc->file_name);
3199 /* show this message only once */
3200 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3202 GtkWidget *bar;
3204 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3205 _("_Reload"), GTK_RESPONSE_ACCEPT,
3206 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3207 NULL, GTK_RESPONSE_NONE,
3208 _("Do you want to reload it?"),
3209 _("The file '%s' on the disk is more recent than the current buffer."),
3210 base_name);
3212 protect_document(doc);
3213 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3214 enable_key_intercept(doc, bar);
3216 g_free(base_name);
3220 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3221 gint response_id,
3222 GeanyDocument *doc)
3224 gboolean file_saved = FALSE;
3226 unprotect_document(doc);
3228 if (response_id == GTK_RESPONSE_ACCEPT)
3229 file_saved = dialogs_show_save_as();
3231 if (!file_saved)
3233 document_set_text_changed(doc, TRUE);
3234 /* don't prompt more than once */
3235 SETPTR(doc->real_path, NULL);
3238 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3242 static void monitor_resave_missing_file(GeanyDocument *doc)
3244 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3246 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3248 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3249 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3251 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3252 on_monitor_resave_missing_file_response,
3253 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
3254 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3255 NULL, GTK_RESPONSE_NONE,
3256 _("Try to resave the file?"),
3257 _("File \"%s\" was not found on disk!"),
3258 doc->file_name);
3260 protect_document(doc);
3261 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3262 enable_key_intercept(doc, bar);
3267 /* Set force to force a disk check, otherwise it is ignored if there was a check
3268 * in the last file_prefs.disk_check_timeout seconds.
3269 * @return @c TRUE if the file has changed. */
3270 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3272 gboolean ret = FALSE;
3273 gboolean use_gio_filemon;
3274 time_t cur_time = 0;
3275 struct stat st;
3276 gchar *locale_filename;
3277 FileDiskStatus old_status;
3279 g_return_val_if_fail(doc != NULL, FALSE);
3281 /* ignore remote files and documents that have never been saved to disk */
3282 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3283 || doc->real_path == NULL || doc->priv->is_remote)
3284 return FALSE;
3286 use_gio_filemon = (doc->priv->monitor != NULL);
3288 if (use_gio_filemon)
3290 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3291 return FALSE;
3293 else
3295 cur_time = time(NULL);
3296 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3297 return FALSE;
3299 doc->priv->last_check = cur_time;
3302 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3303 if (g_stat(locale_filename, &st) != 0)
3305 monitor_resave_missing_file(doc);
3306 /* doc may be closed now */
3307 ret = TRUE;
3309 else if (! use_gio_filemon && /* ignore check when using GIO */
3310 doc->priv->mtime > cur_time)
3312 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3313 /* Note: on Windows st.st_mtime can be newer than cur_time */
3315 else if (doc->priv->mtime < st.st_mtime)
3317 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3318 doc->priv->mtime = st.st_mtime;
3319 monitor_reload_file(doc);
3320 /* doc may be closed now */
3321 ret = TRUE;
3323 g_free(locale_filename);
3325 if (DOC_VALID(doc))
3326 { /* doc can get invalid when a document was closed */
3327 old_status = doc->priv->file_disk_status;
3328 doc->priv->file_disk_status = FILE_OK;
3329 if (old_status != doc->priv->file_disk_status)
3330 ui_update_tab_status(doc);
3332 return ret;
3336 /** Compares documents by their display names.
3337 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3338 * @note 'Display name' means the base name of the document's filename.
3340 * @param a @c GeanyDocument**.
3341 * @param b @c GeanyDocument**.
3342 * @warning The arguments take the address of each document pointer.
3343 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3345 * @since 0.21
3347 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3349 GeanyDocument *doc_a = *((GeanyDocument**) a);
3350 GeanyDocument *doc_b = *((GeanyDocument**) b);
3351 gchar *base_name_a, *base_name_b;
3352 gint result;
3354 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3355 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3357 result = strcmp(base_name_a, base_name_b);
3359 g_free(base_name_a);
3360 g_free(base_name_b);
3362 return result;
3366 /** Compares documents by their tab order.
3367 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3369 * @param a @c GeanyDocument**.
3370 * @param b @c GeanyDocument**.
3371 * @warning The arguments take the address of each document pointer.
3372 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3374 * @since 0.21 (GEANY_API_VERSION 209)
3376 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3378 GeanyDocument *doc_a = *((GeanyDocument**) a);
3379 GeanyDocument *doc_b = *((GeanyDocument**) b);
3380 gint notebook_position_doc_a;
3381 gint notebook_position_doc_b;
3383 notebook_position_doc_a = document_get_notebook_page(doc_a);
3384 notebook_position_doc_b = document_get_notebook_page(doc_b);
3386 if (notebook_position_doc_a < notebook_position_doc_b)
3387 return -1;
3388 if (notebook_position_doc_a > notebook_position_doc_b)
3389 return 1;
3390 /* equality */
3391 return 0;
3395 /** Compares documents by their tab order, in reverse order.
3396 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3398 * @param a @c GeanyDocument**.
3399 * @param b @c GeanyDocument**.
3400 * @warning The arguments take the address of each document pointer.
3401 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3403 * @since 0.21 (GEANY_API_VERSION 209)
3405 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3407 GeanyDocument *doc_a = *((GeanyDocument**) a);
3408 GeanyDocument *doc_b = *((GeanyDocument**) b);
3409 gint notebook_position_doc_a;
3410 gint notebook_position_doc_b;
3412 notebook_position_doc_a = document_get_notebook_page(doc_a);
3413 notebook_position_doc_b = document_get_notebook_page(doc_b);
3415 if (notebook_position_doc_a < notebook_position_doc_b)
3416 return 1;
3417 if (notebook_position_doc_a > notebook_position_doc_b)
3418 return -1;
3419 /* equality */
3420 return 0;
3424 void document_grab_focus(GeanyDocument *doc)
3426 g_return_if_fail(doc != NULL);
3428 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));