Avoid code duplication in document_get_current()
[geany-mirror.git] / src / document.c
blob3f6d6998b3d2bf7d1673d6739d39e9ddd0e50d84
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 "highlighting.h"
42 #include "main.h"
43 #include "msgwindow.h"
44 #include "navqueue.h"
45 #include "notebook.h"
46 #include "project.h"
47 #include "sciwrappers.h"
48 #include "sidebar.h"
49 #include "support.h"
50 #include "symbols.h"
51 #include "ui_utils.h"
52 #include "utils.h"
53 #include "vte.h"
55 #ifdef HAVE_SYS_TIME_H
56 # include <sys/time.h>
57 #endif
58 #include <time.h>
60 #include <unistd.h>
61 #include <string.h>
62 #include <errno.h>
64 #ifdef HAVE_SYS_TYPES_H
65 # include <sys/types.h>
66 #endif
68 #include <stdlib.h>
70 /* gstdio.h also includes sys/stat.h */
71 #include <glib/gstdio.h>
73 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
74 /*#define USE_GIO_FILEMON 1*/
75 #include <gio/gio.h>
77 #include <gdk/gdkkeysyms.h>
79 GeanyFilePrefs file_prefs;
82 /** Dynamic array of GeanyDocument pointers.
83 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
84 * to a document over time, but it may represent a different
85 * document later on, or may have been closed and become invalid.
87 * @warning You must check @c GeanyDocument::is_valid when iterating over this array.
88 * This is done automatically if you use the foreach_document() macro.
90 * @note
91 * Never assume that the order of document pointers is the same as the order of notebook tabs.
92 * One reason is that notebook tabs can be reordered.
93 * Use @c document_get_from_page() to lookup a document from a notebook tab number.
95 * @see documents. */
96 GPtrArray *documents_array = NULL;
99 /* an undo action, also used for redo actions */
100 typedef struct
102 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
103 guint type; /* to identify the action */
104 gpointer *data; /* the old value (before the change), in case of a redo action
105 * it contains the new value */
106 } undo_action;
109 static void document_undo_clear(GeanyDocument *doc);
110 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
111 static gboolean remove_page(guint page_num);
115 * Finds a document whose @c real_path field matches the given filename.
117 * @param realname The filename to search, which should be identical to the
118 * string returned by @c tm_get_real_path().
120 * @return The matching document, or @c NULL.
121 * @note This is only really useful when passing a @c TMWorkObject::file_name.
122 * @see GeanyDocument::real_path.
123 * @see document_find_by_filename().
125 * @since 0.15
127 GeanyDocument* document_find_by_real_path(const gchar *realname)
129 guint i;
131 if (! realname)
132 return NULL; /* file doesn't exist on disk */
134 for (i = 0; i < documents_array->len; i++)
136 GeanyDocument *doc = documents[i];
138 if (! doc->is_valid || ! doc->real_path)
139 continue;
141 if (utils_filenamecmp(realname, doc->real_path) == 0)
143 return doc;
146 return NULL;
150 /* dereference symlinks, /../ junk in path and return locale encoding */
151 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
153 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
154 gchar *realname = tm_get_real_path(locale_name);
156 g_free(locale_name);
157 return realname;
162 * Finds a document with the given filename.
163 * This matches either an exact GeanyDocument::file_name string, or variant
164 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
165 * match @c "/name").
167 * @param utf8_filename The filename to search (in UTF-8 encoding).
169 * @return The matching document, or @c NULL.
170 * @see document_find_by_real_path().
172 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
174 guint i;
175 GeanyDocument *doc;
176 gchar *realname;
178 g_return_val_if_fail(utf8_filename != NULL, NULL);
180 /* First search GeanyDocument::file_name, so we can find documents with a
181 * filename set but not saved on disk, like vcdiff produces */
182 for (i = 0; i < documents_array->len; i++)
184 doc = documents[i];
186 if (! doc->is_valid || doc->file_name == NULL)
187 continue;
189 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
191 return doc;
194 /* Now try matching based on the realpath(), which is unique per file on disk */
195 realname = get_real_path_from_utf8(utf8_filename);
196 doc = document_find_by_real_path(realname);
197 g_free(realname);
198 return doc;
202 /* returns the document which has sci, or NULL. */
203 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
205 guint i;
207 g_return_val_if_fail(sci != NULL, NULL);
209 for (i = 0; i < documents_array->len; i++)
211 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
212 return documents[i];
214 return NULL;
218 /** Gets the notebook page index for a document.
219 * @param doc The document.
220 * @return The index.
221 * @since 0.19 */
222 gint document_get_notebook_page(GeanyDocument *doc)
224 GtkWidget *parent;
225 GtkWidget *child;
227 g_return_val_if_fail(doc != NULL, -1);
229 child = GTK_WIDGET(doc->editor->sci);
230 parent = gtk_widget_get_parent(child);
231 /* search for the direct notebook child, mirroring document_get_from_page() */
232 while (parent && ! GTK_IS_NOTEBOOK(parent))
234 child = parent;
235 parent = gtk_widget_get_parent(child);
238 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
243 * Recursively searches a containers children until it finds a
244 * Scintilla widget, or NULL if one was not found.
246 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
248 ScintillaObject *sci = NULL;
249 GList *children, *iter;
251 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
253 children = gtk_container_get_children(GTK_CONTAINER(container));
254 for (iter = children; iter != NULL; iter = g_list_next(iter))
256 if (IS_SCINTILLA(iter->data))
258 sci = SCINTILLA(iter->data);
259 break;
261 else if (GTK_IS_CONTAINER(iter->data))
263 sci = locate_sci_in_container(iter->data);
264 if (IS_SCINTILLA(sci))
265 break;
266 sci = NULL;
269 g_list_free(children);
271 return sci;
276 * Finds the document for the given notebook page @a page_num.
278 * @param page_num The notebook page number to search.
280 * @return The corresponding document for the given notebook page, or @c NULL.
282 GeanyDocument *document_get_from_page(guint page_num)
284 GtkWidget *parent;
285 ScintillaObject *sci;
287 if (page_num >= documents_array->len)
288 return NULL;
290 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
291 g_return_val_if_fail(GTK_IS_BOX(parent), NULL);
293 sci = locate_sci_in_container(parent);
294 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
296 return document_find_by_sci(sci);
301 * Finds the current document.
303 * @return A pointer to the current document or @c NULL if there are no opened documents.
305 GeanyDocument *document_get_current(void)
307 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
309 if (cur_page == -1)
310 return NULL;
311 else
312 return document_get_from_page((guint) cur_page);
316 void document_init_doclist(void)
318 documents_array = g_ptr_array_new();
322 void document_finalize(void)
324 guint i;
326 for (i = 0; i < documents_array->len; i++)
327 g_free(documents[i]);
328 g_ptr_array_free(documents_array, TRUE);
333 * Returns the last part of the filename of the given GeanyDocument. The result is also
334 * truncated to a maximum of @a length characters in case the filename is very long.
336 * @param doc The document to use.
337 * @param length The length of the resulting string or -1 to use a default value.
339 * @return The ellipsized last part of the filename of @a doc, should be freed when no
340 * longer needed.
342 * @since 0.17
344 /* TODO make more use of this */
345 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
347 gchar *base_name, *short_name;
349 g_return_val_if_fail(doc != NULL, NULL);
351 if (length < 0)
352 length = 30;
354 base_name = g_path_get_basename(DOC_FILENAME(doc));
355 short_name = utils_str_middle_truncate(base_name, (guint)length);
357 g_free(base_name);
359 return short_name;
363 void document_update_tab_label(GeanyDocument *doc)
365 gchar *short_name;
366 GtkWidget *parent;
368 g_return_if_fail(doc != NULL);
370 short_name = document_get_basename_for_display(doc, -1);
372 /* we need to use the event box for the tooltip, labels don't get the necessary events */
373 parent = gtk_widget_get_parent(doc->priv->tab_label);
374 parent = gtk_widget_get_parent(parent);
376 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
378 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
380 g_free(short_name);
385 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
386 * according to the document's save state.
387 * This is called by Geany mostly when opening or saving files.
389 * @param doc The document to use.
390 * @param changed Whether the document state should indicate changes have been made.
392 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
394 g_return_if_fail(doc != NULL);
396 doc->changed = changed;
398 if (! main_status.quitting)
400 ui_update_tab_status(doc);
401 ui_save_buttons_toggle(changed);
402 ui_set_window_title(doc);
403 ui_update_statusbar(doc, -1);
408 /* returns the next free place in the document list,
409 * or -1 if the documents_array is full */
410 static gint document_get_new_idx(void)
412 guint i;
414 for (i = 0; i < documents_array->len; i++)
416 if (documents[i]->editor == NULL)
418 return (gint) i;
421 return -1;
425 static void queue_colourise(GeanyDocument *doc)
427 /* Colourise the editor before it is next drawn */
428 doc->priv->colourise_needed = TRUE;
430 /* If the editor doesn't need drawing (e.g. after saving the current
431 * document), we need to force a redraw, so the expose event is triggered.
432 * This ensures we don't start colourising before all documents are opened/saved,
433 * only once the editor is drawn. */
434 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
438 #ifdef USE_GIO_FILEMON
439 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
440 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
441 GeanyDocument *doc)
443 g_return_if_fail(doc != NULL);
445 if (file_prefs.disk_check_timeout == 0)
446 return;
448 geany_debug("%s: event: %d previous file status: %d",
449 G_STRFUNC, event, doc->priv->file_disk_status);
450 switch (event)
452 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
454 if (doc->priv->file_disk_status == FILE_IGNORE)
455 doc->priv->file_disk_status = FILE_OK;
456 else
457 doc->priv->file_disk_status = FILE_CHANGED;
458 g_message("%s: FILE_CHANGED", G_STRFUNC);
459 break;
461 case G_FILE_MONITOR_EVENT_DELETED:
463 doc->priv->file_disk_status = FILE_CHANGED;
464 g_message("%s: FILE_MISSING", G_STRFUNC);
465 break;
467 default:
468 break;
470 if (doc->priv->file_disk_status != FILE_OK)
472 ui_update_tab_status(doc);
475 #endif
478 static void document_stop_file_monitoring(GeanyDocument *doc)
480 g_return_if_fail(doc != NULL);
482 if (doc->priv->monitor != NULL)
484 g_object_unref(doc->priv->monitor);
485 doc->priv->monitor = NULL;
490 static void monitor_file_setup(GeanyDocument *doc)
492 g_return_if_fail(doc != NULL);
493 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
494 * doesn't work at all for remote files and legacy polling is too slow. */
495 if (! doc->priv->is_remote)
497 #ifdef USE_GIO_FILEMON
498 gchar *locale_filename;
500 /* stop any previous monitoring */
501 document_stop_file_monitoring(doc);
503 locale_filename = utils_get_locale_from_utf8(doc->file_name);
504 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
506 /* get a file monitor and connect to the 'changed' signal */
507 GFile *file = g_file_new_for_path(locale_filename);
508 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
509 g_signal_connect(doc->priv->monitor, "changed",
510 G_CALLBACK(monitor_file_changed_cb), doc);
512 /* we set the rate limit according to the GUI pref but it's most probably not used */
513 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
515 g_object_unref(file);
517 g_free(locale_filename);
518 #endif
520 doc->priv->file_disk_status = FILE_OK;
524 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
526 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
527 if (DOC_VALID(doc))
529 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
530 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
532 if (source_widget == NULL)
533 source_widget = doc->priv->tag_tree;
535 if (focusw == source_widget)
536 gtk_widget_grab_focus(sci);
541 static gboolean on_idle_focus(gpointer doc)
543 document_try_focus(doc, NULL);
544 return FALSE;
548 /* Creates a new document and editor, adding a tab in the notebook.
549 * @return The created document */
550 static GeanyDocument *document_create(const gchar *utf8_filename)
552 GeanyDocument *doc;
553 gint new_idx;
554 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
556 if (cur_pages == 1)
558 doc = document_get_current();
559 /* remove the empty document first */
560 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
561 /* prevent immediately opening another new doc with
562 * new_document_after_close pref */
563 remove_page(0);
566 new_idx = document_get_new_idx();
567 if (new_idx == -1) /* expand the array, no free places */
569 doc = g_new0(GeanyDocument, 1);
571 new_idx = documents_array->len;
572 g_ptr_array_add(documents_array, doc);
575 doc = documents[new_idx];
577 /* initialize default document settings */
578 doc->priv = g_new0(GeanyDocumentPrivate, 1);
579 doc->index = new_idx;
580 doc->file_name = g_strdup(utf8_filename);
581 doc->editor = editor_create(doc);
582 #ifndef USE_GIO_FILEMON
583 doc->priv->last_check = time(NULL);
584 #endif
586 sidebar_openfiles_add(doc); /* sets doc->iter */
588 notebook_new_tab(doc);
590 /* select document in sidebar */
592 GtkTreeSelection *sel;
594 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
595 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
598 ui_document_buttons_update();
600 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
601 return doc;
606 * Closes the given document.
608 * @param doc The document to remove.
610 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
612 * @since 0.15
614 gboolean document_close(GeanyDocument *doc)
616 g_return_val_if_fail(doc, FALSE);
618 return document_remove_page(document_get_notebook_page(doc));
622 /* Call document_remove_page() instead, this is only needed for document_create()
623 * to prevent re-opening a new document when the last document is closed (if enabled). */
624 static gboolean remove_page(guint page_num)
626 GeanyDocument *doc = document_get_from_page(page_num);
628 g_return_val_if_fail(doc != NULL, FALSE);
630 if (doc->changed && ! dialogs_show_unsaved_file(doc))
631 return FALSE;
633 /* tell any plugins that the document is about to be closed */
634 g_signal_emit_by_name(geany_object, "document-close", doc);
636 /* Checking real_path makes it likely the file exists on disk */
637 if (! main_status.closing_all && doc->real_path != NULL)
638 ui_add_recent_document(doc);
640 doc->is_valid = FALSE;
642 if (main_status.quitting)
644 /* we need to destroy the ScintillaWidget so our handlers on it are
645 * disconnected before we free any data they may use (like the editor).
646 * when not quitting, this is handled by removing the notebook page. */
647 gtk_widget_destroy(GTK_WIDGET(doc->editor->sci));
649 else
651 notebook_remove_page(page_num);
652 sidebar_remove_document(doc);
653 navqueue_remove_file(doc->file_name);
654 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
656 g_free(doc->encoding);
657 g_free(doc->priv->saved_encoding.encoding);
658 g_free(doc->file_name);
659 g_free(doc->real_path);
660 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
662 if (doc->priv->tag_tree)
663 gtk_widget_destroy(doc->priv->tag_tree);
665 editor_destroy(doc->editor);
666 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
668 document_stop_file_monitoring(doc);
670 document_undo_clear(doc);
672 g_free(doc->priv);
674 /* reset document settings to defaults for re-use */
675 memset(doc, 0, sizeof(GeanyDocument));
677 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
679 sidebar_update_tag_list(NULL, FALSE);
680 ui_set_window_title(NULL);
681 ui_save_buttons_toggle(FALSE);
682 ui_update_popup_reundo_items(NULL);
683 ui_document_buttons_update();
684 build_menu_update(NULL);
686 return TRUE;
691 * Removes the given notebook tab at @a page_num and clears all related information
692 * in the document list.
694 * @param page_num The notebook page number to remove.
696 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
698 gboolean document_remove_page(guint page_num)
700 gboolean done = remove_page(page_num);
702 if (done && ui_prefs.new_document_after_close)
703 document_new_file_if_non_open();
705 return done;
709 /* used to keep a record of the unchanged document state encoding */
710 static void store_saved_encoding(GeanyDocument *doc)
712 g_free(doc->priv->saved_encoding.encoding);
713 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
714 doc->priv->saved_encoding.has_bom = doc->has_bom;
718 /* Opens a new empty document only if there are no other documents open */
719 GeanyDocument *document_new_file_if_non_open(void)
721 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
722 return document_new_file(NULL, NULL, NULL);
724 return NULL;
729 * Creates a new document.
730 * Line endings in @a text will be converted to the default setting.
731 * Afterwards, the @c "document-new" signal is emitted for plugins.
733 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
734 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
735 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
737 * @return The new document.
739 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
741 GeanyDocument *doc;
743 if (utf8_filename && g_path_is_absolute(utf8_filename))
745 gchar *tmp;
746 tmp = utils_strdupa(utf8_filename); /* work around const */
747 utils_tidy_path(tmp);
748 utf8_filename = tmp;
750 doc = document_create(utf8_filename);
752 g_assert(doc != NULL);
754 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
755 if (text)
757 GString *template = g_string_new(text);
758 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
760 sci_set_text(doc->editor->sci, template->str);
761 g_string_free(template, TRUE);
763 else
764 sci_clear_all(doc->editor->sci);
766 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
768 sci_set_undo_collection(doc->editor->sci, TRUE);
769 sci_empty_undo_buffer(doc->editor->sci);
771 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
772 /* store the opened encoding for undo/redo */
773 store_saved_encoding(doc);
775 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
776 ft = filetypes_detect_from_document(doc);
778 document_set_filetype(doc, ft); /* also re-parses tags */
780 ui_set_window_title(doc);
781 build_menu_update(doc);
782 document_set_text_changed(doc, FALSE);
783 ui_document_show_hide(doc); /* update the document menu */
785 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
786 /* bring it in front, jump to the start and grab the focus */
787 editor_goto_pos(doc->editor, 0, FALSE);
788 document_try_focus(doc, NULL);
790 #ifdef USE_GIO_FILEMON
791 monitor_file_setup(doc);
792 #else
793 doc->priv->mtime = time(NULL);
794 #endif
796 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
797 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
799 g_signal_emit_by_name(geany_object, "document-new", doc);
801 msgwin_status_add(_("New file \"%s\" opened."),
802 DOC_FILENAME(doc));
804 return doc;
809 * Opens a document specified by @a locale_filename.
810 * Afterwards, the @c "document-open" signal is emitted for plugins.
812 * @param locale_filename The filename of the document to load, in locale encoding.
813 * @param readonly Whether to open the document in read-only mode.
814 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
815 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
817 * @return The document opened or @c NULL.
819 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
820 GeanyFiletype *ft, const gchar *forced_enc)
822 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
826 typedef struct
828 gchar *data; /* null-terminated file data */
829 gsize len; /* string length of data */
830 gchar *enc;
831 gboolean bom;
832 time_t mtime; /* modification time, read by stat::st_mtime */
833 gboolean readonly;
834 } FileData;
837 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
838 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
839 FileData *filedata, const gchar *forced_enc)
841 GError *err = NULL;
842 struct stat st;
844 filedata->data = NULL;
845 filedata->len = 0;
846 filedata->enc = NULL;
847 filedata->bom = FALSE;
848 filedata->readonly = FALSE;
850 if (g_stat(locale_filename, &st) != 0)
852 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
853 display_filename, g_strerror(errno));
854 return FALSE;
857 filedata->mtime = st.st_mtime;
859 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
861 ui_set_statusbar(TRUE, "%s", err->message);
862 g_error_free(err);
863 return FALSE;
866 filedata->len = (gsize) st.st_size;
867 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
868 &filedata->enc, &filedata->bom, &filedata->readonly))
870 if (forced_enc)
872 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
873 display_filename, forced_enc);
875 else
877 ui_set_statusbar(TRUE,
878 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
879 display_filename);
881 g_free(filedata->data);
882 return FALSE;
885 if (filedata->readonly)
887 const gchar *warn_msg = _(
888 "The file \"%s\" could not be opened properly and has been truncated. " \
889 "This can occur if the file contains a NULL byte. " \
890 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
892 if (main_status.main_window_realized)
893 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
895 ui_set_statusbar(TRUE, warn_msg, display_filename);
898 return TRUE;
902 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
903 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
904 * if cl_options.goto_column is set.
906 * returns the new position which may have changed */
907 static gint set_cursor_position(GeanyEditor *editor, gint pos)
909 if (cl_options.goto_line >= 0)
910 { /* goto line which was specified on command line and then undefine the line */
911 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
912 editor->scroll_percent = 0.5F;
913 cl_options.goto_line = -1;
915 else if (pos > 0)
917 sci_set_current_position(editor->sci, pos, FALSE);
918 editor->scroll_percent = 0.5F;
921 if (cl_options.goto_column >= 0)
922 { /* goto column which was specified on command line and then undefine the column */
924 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
925 sci_set_current_position(editor->sci, new_pos, FALSE);
926 editor->scroll_percent = 0.5F;
927 cl_options.goto_column = -1;
928 return new_pos;
930 return sci_get_current_position(editor->sci);
934 /* Count lines that start with some hard tabs then a soft tab. */
935 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
937 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
938 ScintillaObject *sci = editor->sci;
939 gsize count = 0;
940 struct Sci_TextToFind ttf;
941 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
942 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
944 g_free(soft_tab);
946 ttf.chrg.cpMin = 0;
947 ttf.chrg.cpMax = sci_get_length(sci);
948 ttf.lpstrText = regex;
949 while (1)
951 gint pos;
953 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
954 if (pos == -1)
955 break; /* no more matches */
956 count++;
957 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
959 g_free(regex);
960 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
961 return count > sci_get_line_count(sci) * 0.02;
965 /* Detect the indent type based on counting the leading indent characters for each line.
966 * Returns whether detection succeeded, and the detected type in *type_ upon success */
967 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
969 GeanyEditor *editor = doc->editor;
970 ScintillaObject *sci = editor->sci;
971 gint line, line_count;
972 gsize tabs = 0, spaces = 0;
974 if (detect_tabs_and_spaces(editor))
976 *type_ = GEANY_INDENT_TYPE_BOTH;
977 return TRUE;
980 line_count = sci_get_line_count(sci);
981 for (line = 0; line < line_count; line++)
983 gint pos = sci_get_position_from_line(sci, line);
984 gchar c;
986 /* most code will have indent total <= 24, otherwise it's more likely to be
987 * alignment than indentation */
988 if (sci_get_line_indentation(sci, line) > 24)
989 continue;
991 c = sci_get_char_at(sci, pos);
992 if (c == '\t')
993 tabs++;
994 /* check for at least 2 spaces */
995 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
996 spaces++;
998 if (spaces == 0 && tabs == 0)
999 return FALSE;
1001 /* the factors may need to be tweaked */
1002 if (spaces > tabs * 4)
1003 *type_ = GEANY_INDENT_TYPE_SPACES;
1004 else if (tabs > spaces * 4)
1005 *type_ = GEANY_INDENT_TYPE_TABS;
1006 else
1007 *type_ = GEANY_INDENT_TYPE_BOTH;
1009 return TRUE;
1013 /* Detect the indent width based on counting the leading indent characters for each line.
1014 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1015 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1017 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1018 ScintillaObject *sci = editor->sci;
1019 gint line, line_count;
1020 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1021 gint count, width, i;
1023 /* can't easily detect the supposed width of a tab, guess the default is OK */
1024 if (type == GEANY_INDENT_TYPE_TABS)
1025 return FALSE;
1027 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1028 sci_set_tab_width(sci, 8);
1030 line_count = sci_get_line_count(sci);
1031 for (line = 0; line < line_count; line++)
1033 gint pos = sci_get_line_indent_position(sci, line);
1035 /* We probably don't have style info yet, because we're generally called just after
1036 * the document got created, so we can't use highlighting_is_code_style().
1037 * That's not good, but the assumption below that concerning lines start with an
1038 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1039 * without removing too much legitimate lines. */
1040 if (sci_get_char_at(sci, pos) == '*')
1041 continue;
1043 width = sci_get_line_indentation(sci, line);
1044 /* most code will have indent total <= 24, otherwise it's more likely to be
1045 * alignment than indentation */
1046 if (width > 24)
1047 continue;
1048 /* < 2 is no indentation */
1049 if (width < 2)
1050 continue;
1052 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1054 if ((width % (i + 2)) == 0)
1055 widths[i]++;
1058 count = 0;
1059 width = iprefs->width;
1060 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1062 /* give large indents higher weight not to be fooled by spurious indents */
1063 if (widths[i] >= count * 1.5)
1065 width = i + 2;
1066 count = widths[i];
1070 if (count == 0)
1071 return FALSE;
1073 *width_ = width;
1074 return TRUE;
1078 /* same as detect_indent_width() but uses editor's indent type */
1079 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1081 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1085 void document_apply_indent_settings(GeanyDocument *doc)
1087 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1088 GeanyIndentType type = iprefs->type;
1089 gint width = iprefs->width;
1091 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1093 if (type != iprefs->type)
1095 const gchar *name = NULL;
1097 switch (type)
1099 case GEANY_INDENT_TYPE_SPACES:
1100 name = _("Spaces");
1101 break;
1102 case GEANY_INDENT_TYPE_TABS:
1103 name = _("Tabs");
1104 break;
1105 case GEANY_INDENT_TYPE_BOTH:
1106 name = _("Tabs and Spaces");
1107 break;
1109 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1110 * and Spaces), the second one is the filename */
1111 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1112 DOC_FILENAME(doc));
1115 else if (doc->file_type->indent_type > -1)
1116 type = doc->file_type->indent_type;
1118 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1120 if (width != iprefs->width)
1122 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1123 DOC_FILENAME(doc));
1126 else if (doc->file_type->indent_width > -1)
1127 width = doc->file_type->indent_width;
1129 editor_set_indent(doc->editor, type, width);
1133 void document_show_tab(GeanyDocument *doc)
1135 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1136 document_get_notebook_page(doc));
1140 /* To open a new file, set doc to NULL; filename should be locale encoded.
1141 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1142 * pos is the cursor position, which can be overridden by --line and --column.
1143 * forced_enc can be NULL to detect the file encoding.
1144 * Returns: doc of the opened file or NULL if an error occurred. */
1145 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1146 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1148 gint editor_mode;
1149 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1150 gchar *utf8_filename = NULL;
1151 gchar *display_filename = NULL;
1152 gchar *locale_filename = NULL;
1153 GeanyFiletype *use_ft;
1154 FileData filedata;
1156 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1158 if (reload)
1160 utf8_filename = g_strdup(doc->file_name);
1161 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1163 else
1165 /* filename must not be NULL when opening a file */
1166 g_return_val_if_fail(filename, NULL);
1168 #ifdef G_OS_WIN32
1169 /* if filename is a shortcut, try to resolve it */
1170 locale_filename = win32_get_shortcut_target(filename);
1171 #else
1172 locale_filename = g_strdup(filename);
1173 #endif
1174 /* remove relative junk */
1175 utils_tidy_path(locale_filename);
1177 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1178 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1180 /* if file is already open, switch to it and go */
1181 doc = document_find_by_filename(utf8_filename);
1182 if (doc != NULL)
1184 ui_add_recent_document(doc); /* either add or reorder recent item */
1185 /* show the doc before reload dialog */
1186 document_show_tab(doc);
1187 document_check_disk_status(doc, TRUE); /* force a file changed check */
1190 if (reload || doc == NULL)
1191 { /* doc possibly changed */
1192 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1194 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1196 g_free(display_filename);
1197 g_free(utf8_filename);
1198 g_free(locale_filename);
1199 return NULL;
1202 if (! reload)
1204 doc = document_create(utf8_filename);
1205 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1207 /* file exists on disk, set real_path */
1208 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1210 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1211 monitor_file_setup(doc);
1214 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1215 sci_empty_undo_buffer(doc->editor->sci);
1217 /* add the text to the ScintillaObject */
1218 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1219 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1220 queue_colourise(doc); /* Ensure the document gets colourised. */
1222 /* detect & set line endings */
1223 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1224 sci_set_eol_mode(doc->editor->sci, editor_mode);
1225 g_free(filedata.data);
1227 sci_set_undo_collection(doc->editor->sci, TRUE);
1229 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1230 g_free(doc->encoding); /* if reloading, free old encoding */
1231 doc->encoding = filedata.enc;
1232 doc->has_bom = filedata.bom;
1233 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1235 doc->readonly = readonly || filedata.readonly;
1236 sci_set_readonly(doc->editor->sci, doc->readonly);
1237 doc->priv->protected = 0;
1239 /* update line number margin width */
1240 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1241 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1243 if (! reload)
1246 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1247 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1248 doc->editor);
1250 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1252 else
1253 { /* reloading */
1254 document_undo_clear(doc);
1256 use_ft = ft;
1258 /* update taglist, typedef keywords and build menu if necessary */
1259 document_set_filetype(doc, use_ft);
1261 /* set indentation settings after setting the filetype */
1262 if (reload)
1263 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1264 else
1265 document_apply_indent_settings(doc);
1267 document_set_text_changed(doc, FALSE); /* also updates tab state */
1268 ui_document_show_hide(doc); /* update the document menu */
1270 /* finally add current file to recent files menu, but not the files from the last session */
1271 if (! main_status.opening_session_files)
1272 ui_add_recent_document(doc);
1274 if (reload)
1276 g_signal_emit_by_name(geany_object, "document-reload", doc);
1277 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1279 else
1281 g_signal_emit_by_name(geany_object, "document-open", doc);
1282 /* For translators: this is the status window message for opening a file. %d is the number
1283 * of the newly opened file, %s indicates whether the file is opened read-only
1284 * (it is replaced with the string ", read-only"). */
1285 msgwin_status_add(_("File %s opened(%d%s)."),
1286 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1287 (readonly) ? _(", read-only") : "");
1291 g_free(display_filename);
1292 g_free(utf8_filename);
1293 g_free(locale_filename);
1295 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1296 pos = set_cursor_position(doc->editor, pos);
1297 /* now bring the file in front */
1298 editor_goto_pos(doc->editor, pos, FALSE);
1300 /* finally, let the editor widget grab the focus so you can start coding
1301 * right away */
1302 g_idle_add(on_idle_focus, doc);
1303 return doc;
1307 /* Takes a new line separated list of filename URIs and opens each file.
1308 * length is the length of the string */
1309 void document_open_file_list(const gchar *data, gsize length)
1311 guint i;
1312 gchar *filename;
1313 gchar **list;
1315 g_return_if_fail(data != NULL);
1317 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1319 /* stop at the end or first empty item, because last item is empty but not null */
1320 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1322 filename = utils_get_path_from_uri(list[i]);
1323 if (filename == NULL)
1324 continue;
1325 document_open_file(filename, FALSE, NULL, NULL);
1326 g_free(filename);
1329 g_strfreev(list);
1334 * Opens each file in the list @a filenames.
1335 * Internally, document_open_file() is called for every list item.
1337 * @param filenames A list of filenames to load, in locale encoding.
1338 * @param readonly Whether to open the document in read-only mode.
1339 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1340 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1342 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1343 const gchar *forced_enc)
1345 const GSList *item;
1347 for (item = filenames; item != NULL; item = g_slist_next(item))
1349 document_open_file(item->data, readonly, ft, forced_enc);
1355 * Reloads the document with the specified file encoding
1356 * @a forced_enc or @c NULL to auto-detect the file encoding.
1358 * @param doc The document to reload.
1359 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1361 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1363 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1365 gint pos = 0;
1366 GeanyDocument *new_doc;
1368 g_return_val_if_fail(doc != NULL, FALSE);
1370 /* Use cancel because the response handler would call this recursively */
1371 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1372 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1374 /* try to set the cursor to the position before reloading */
1375 pos = sci_get_current_position(doc->editor->sci);
1376 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1378 return (new_doc != NULL);
1382 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1384 #ifndef USE_GIO_FILEMON
1385 struct stat st;
1387 g_return_val_if_fail(doc != NULL, FALSE);
1389 /* stat the file to get the timestamp, otherwise on Windows the actual
1390 * timestamp can be ahead of time(NULL) */
1391 if (g_stat(locale_filename, &st) != 0)
1393 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1394 g_strerror(errno));
1395 return FALSE;
1398 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1399 #endif
1400 return TRUE;
1404 /* Sets line and column to the given position byte_pos in the document.
1405 * byte_pos is the position counted in bytes, not characters */
1406 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1408 gint i;
1409 gint line_start;
1411 /* for some reason we can use byte count instead of character count here */
1412 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1413 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1414 /* get the column in the line */
1415 *column = byte_pos - line_start;
1417 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1418 * skip one byte(i++) and decrease the column number which is based on byte count */
1419 for (i = line_start; i < (line_start + *column); i++)
1421 if (sci_get_char_at(doc->editor->sci, i) < 0)
1423 (*column)--;
1424 i++;
1430 static void replace_header_filename(GeanyDocument *doc)
1432 gchar *filebase;
1433 gchar *filename;
1434 struct Sci_TextToFind ttf;
1436 g_return_if_fail(doc != NULL);
1437 g_return_if_fail(doc->file_type != NULL);
1439 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1440 if (doc->file_type->extension)
1441 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1442 else
1443 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1445 filename = g_path_get_basename(doc->file_name);
1447 /* only search the first 3 lines */
1448 ttf.chrg.cpMin = 0;
1449 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1450 ttf.lpstrText = filebase;
1452 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf, NULL) != -1)
1454 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1455 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1456 sci_replace_target(doc->editor->sci, filename, FALSE);
1458 g_free(filebase);
1459 g_free(filename);
1464 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1465 * you still have to call @ref document_save_file_as() to change the @a doc object.
1466 * It also stops monitoring for file changes to prevent receiving too many file change events
1467 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1469 * @param doc The current document which should be renamed.
1470 * @param new_filename The new filename in UTF-8 encoding.
1472 * @since 0.16
1474 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1476 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1477 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1478 gint result;
1480 /* stop file monitoring to avoid getting events for deleting/creating files,
1481 * it's re-setup in document_save_file_as() */
1482 document_stop_file_monitoring(doc);
1484 result = g_rename(old_locale_filename, new_locale_filename);
1485 if (result != 0)
1487 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1488 _("Error renaming file."), g_strerror(errno));
1490 g_free(old_locale_filename);
1491 g_free(new_locale_filename);
1495 static void protect_document(GeanyDocument *doc)
1497 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1498 if (!doc->priv->protected++)
1499 sci_set_readonly(doc->editor->sci, TRUE);
1502 static void unprotect_document(GeanyDocument *doc)
1504 g_return_if_fail(doc->priv->protected > 0);
1506 if (!--doc->priv->protected && doc->readonly == FALSE)
1507 sci_set_readonly(doc->editor->sci, FALSE);
1511 /* Return TRUE if the document doesn't have a full filename set.
1512 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1513 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1514 * new files. */
1515 gboolean document_need_save_as(GeanyDocument *doc)
1517 g_return_val_if_fail(doc != NULL, FALSE);
1519 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1524 * Saves the document, detecting the filetype.
1526 * @param doc The document for the file to save.
1527 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1528 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1530 * @see document_save_file().
1532 * @since 0.16
1534 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1536 gboolean ret;
1537 gboolean new_file;
1539 g_return_val_if_fail(doc != NULL, FALSE);
1541 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1542 if (utf8_fname != NULL)
1543 SETPTR(doc->file_name, g_strdup(utf8_fname));
1545 /* reset real path, it's retrieved again in document_save() */
1546 SETPTR(doc->real_path, NULL);
1548 /* detect filetype */
1549 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1551 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1553 document_set_filetype(doc, ft);
1554 if (document_get_current() == doc)
1556 ignore_callback = TRUE;
1557 filetypes_select_radio_item(doc->file_type);
1558 ignore_callback = FALSE;
1562 if (new_file)
1564 sci_set_readonly(doc->editor->sci, FALSE);
1565 doc->readonly = FALSE;
1566 if (doc->priv->protected > 0)
1567 unprotect_document(doc);
1570 replace_header_filename(doc);
1572 ret = document_save_file(doc, TRUE);
1574 /* file monitoring support, add file monitoring after the file has been saved
1575 * to ignore any earlier events */
1576 monitor_file_setup(doc);
1577 doc->priv->file_disk_status = FILE_IGNORE;
1579 if (ret)
1580 ui_add_recent_document(doc);
1581 return ret;
1585 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1587 GError *conv_error = NULL;
1588 gchar* conv_file_contents = NULL;
1589 gsize bytes_read;
1590 gsize conv_len;
1592 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1593 g_return_val_if_fail(len != NULL, FALSE);
1595 /* try to convert it from UTF-8 to original encoding */
1596 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1597 &bytes_read, &conv_len, &conv_error);
1599 if (conv_error != NULL)
1601 gchar *text = g_strdup_printf(
1602 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1603 doc->encoding);
1604 gchar *error_text;
1606 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1608 gint line, column;
1609 gint context_len;
1610 gunichar unic;
1611 /* don't read over the doc length */
1612 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1613 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1614 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1616 /* take only one valid Unicode character from the context and discard the leftover */
1617 unic = g_utf8_get_char_validated(context, -1);
1618 context_len = g_unichar_to_utf8(unic, context);
1619 context[context_len] = '\0';
1620 get_line_column_from_pos(doc, bytes_read, &line, &column);
1622 error_text = g_strdup_printf(
1623 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1624 conv_error->message, context, line + 1, column);
1626 else
1627 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1629 geany_debug("encoding error: %s", conv_error->message);
1630 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1631 g_error_free(conv_error);
1632 g_free(text);
1633 g_free(error_text);
1634 return FALSE;
1636 else
1638 g_free(*data);
1639 *data = conv_file_contents;
1640 *len = conv_len;
1642 return TRUE;
1646 static gchar *write_data_to_disk(const gchar *locale_filename,
1647 const gchar *data, gsize len)
1649 GError *error = NULL;
1651 if (file_prefs.use_safe_file_saving)
1653 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1654 * This is the only option that handles disk space exhaustion. */
1655 if (g_file_set_contents(locale_filename, data, len, &error))
1656 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1658 else if (file_prefs.use_gio_unsafe_file_saving)
1660 GFile *fp;
1662 /* Use GIO API to save file (GVFS-safe)
1663 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1664 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1665 fp = g_file_new_for_path(locale_filename);
1666 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1667 G_FILE_CREATE_NONE, NULL, NULL, &error);
1668 g_object_unref(fp);
1670 else
1672 FILE *fp;
1673 int save_errno;
1674 gchar *display_name = g_filename_display_name(locale_filename);
1676 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1677 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1678 errno = 0;
1679 fp = g_fopen(locale_filename, "wb");
1680 if (fp == NULL)
1682 save_errno = errno;
1684 g_set_error(&error,
1685 G_FILE_ERROR,
1686 g_file_error_from_errno(save_errno),
1687 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1688 display_name,
1689 g_strerror(save_errno));
1691 else
1693 gsize bytes_written;
1695 errno = 0;
1696 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1698 if (len != bytes_written)
1700 save_errno = errno;
1702 g_set_error(&error,
1703 G_FILE_ERROR,
1704 g_file_error_from_errno(save_errno),
1705 _("Failed to write file '%s': fwrite() failed: %s"),
1706 display_name,
1707 g_strerror(save_errno));
1710 errno = 0;
1711 /* preserve the fwrite() error if any */
1712 if (fclose(fp) != 0 && error == NULL)
1714 save_errno = errno;
1716 g_set_error(&error,
1717 G_FILE_ERROR,
1718 g_file_error_from_errno(save_errno),
1719 _("Failed to close file '%s': fclose() failed: %s"),
1720 display_name,
1721 g_strerror(save_errno));
1725 g_free(display_name);
1727 if (error != NULL)
1729 gchar *msg = g_strdup(error->message);
1730 g_error_free(error);
1731 /* geany will warn about file truncation for unsafe saving below */
1732 return msg;
1734 return NULL;
1738 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1739 const gchar *data, gsize len)
1741 gchar *err;
1743 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1744 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1746 err = write_data_to_disk(locale_filename, data, len);
1747 if (err)
1748 return err;
1750 /* now the file is on disk, set real_path */
1751 if (doc->real_path == NULL)
1753 doc->real_path = tm_get_real_path(locale_filename);
1754 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1755 monitor_file_setup(doc);
1757 return NULL;
1761 * Saves the document.
1762 * Also shows the Save As dialog if necessary.
1763 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1765 * Saving may include replacing tabs with spaces,
1766 * stripping trailing spaces and adding a final new line at the end of the file, depending
1767 * on user preferences. Then the @c "document-before-save" signal is emitted,
1768 * allowing plugins to modify the document before it is saved, and data is
1769 * actually written to disk.
1771 * On successful saving:
1772 * - GeanyDocument::real_path is set.
1773 * - The filetype is set again or auto-detected if it wasn't set yet.
1774 * - The @c "document-save" signal is emitted for plugins.
1776 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1777 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1778 * added in Geany 1.22.
1780 * @param doc The document to save.
1781 * @param force Whether to save the file even if it is not modified.
1783 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1785 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1787 gchar *errmsg;
1788 gchar *data;
1789 gsize len;
1790 gchar *locale_filename;
1791 const GeanyFilePrefs *fp;
1793 g_return_val_if_fail(doc != NULL, FALSE);
1795 if (document_need_save_as(doc))
1797 /* ensure doc is the current tab before showing the dialog */
1798 document_show_tab(doc);
1799 return dialogs_show_save_as();
1802 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1803 if (doc->readonly || doc->priv->protected)
1804 return FALSE;
1805 if (!force && !doc->changed)
1806 return FALSE;
1808 fp = project_get_file_prefs();
1809 /* replaces tabs with spaces but only if the current file is not a Makefile */
1810 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1811 editor_replace_tabs(doc->editor);
1812 /* strip trailing spaces */
1813 if (fp->strip_trailing_spaces)
1814 editor_strip_trailing_spaces(doc->editor);
1815 /* ensure the file has a newline at the end */
1816 if (fp->final_new_line)
1817 editor_ensure_final_newline(doc->editor);
1818 /* ensure newlines are consistent */
1819 if (fp->ensure_convert_new_lines)
1820 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1822 /* notify plugins which may wish to modify the document before it's saved */
1823 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1825 len = sci_get_length(doc->editor->sci) + 1;
1826 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1827 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1828 * encoding, it will be converted to doc->encoding below and this conversion
1829 * also changes the BOM */
1830 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1831 data[0] = (gchar) 0xef;
1832 data[1] = (gchar) 0xbb;
1833 data[2] = (gchar) 0xbf;
1834 sci_get_text(doc->editor->sci, len, data + 3);
1835 len += 3;
1837 else
1839 data = (gchar*) g_malloc(len);
1840 sci_get_text(doc->editor->sci, len, data);
1843 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1844 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1845 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1847 if (! save_convert_to_encoding(doc, &data, &len))
1849 g_free(data);
1850 return FALSE;
1853 else
1855 len = strlen(data);
1858 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1860 /* ignore file changed notification when the file is written */
1861 doc->priv->file_disk_status = FILE_IGNORE;
1863 /* actually write the content of data to the file on disk */
1864 errmsg = save_doc(doc, locale_filename, data, len);
1865 g_free(data);
1867 if (errmsg != NULL)
1869 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1871 if (!file_prefs.use_safe_file_saving)
1873 SETPTR(errmsg,
1874 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1876 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1877 doc->priv->file_disk_status = FILE_OK;
1878 utils_beep();
1879 g_free(locale_filename);
1880 g_free(errmsg);
1881 return FALSE;
1884 /* store the opened encoding for undo/redo */
1885 store_saved_encoding(doc);
1887 /* ignore the following things if we are quitting */
1888 if (! main_status.quitting)
1890 sci_set_savepoint(doc->editor->sci);
1892 if (file_prefs.disk_check_timeout > 0)
1893 document_update_timestamp(doc, locale_filename);
1895 /* update filetype-related things */
1896 document_set_filetype(doc, doc->file_type);
1898 document_update_tab_label(doc);
1900 msgwin_status_add(_("File %s saved."), doc->file_name);
1901 ui_update_statusbar(doc, -1);
1902 #ifdef HAVE_VTE
1903 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1904 #endif
1906 g_free(locale_filename);
1908 g_signal_emit_by_name(geany_object, "document-save", doc);
1910 return TRUE;
1914 /* special search function, used from the find entry in the toolbar
1915 * return TRUE if text was found otherwise FALSE
1916 * return also TRUE if text is empty */
1917 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1918 gboolean backwards)
1920 gint start_pos, search_pos;
1921 struct Sci_TextToFind ttf;
1923 g_return_val_if_fail(text != NULL, FALSE);
1924 g_return_val_if_fail(doc != NULL, FALSE);
1925 if (! *text)
1926 return TRUE;
1928 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1929 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1931 /* search cursor to end or start */
1932 ttf.chrg.cpMin = start_pos;
1933 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1934 ttf.lpstrText = (gchar *)text;
1935 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1937 /* if no match, search start (or end) to cursor */
1938 if (search_pos == -1)
1940 if (backwards)
1942 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1943 ttf.chrg.cpMax = start_pos;
1945 else
1947 ttf.chrg.cpMin = 0;
1948 ttf.chrg.cpMax = start_pos + strlen(text);
1950 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1953 if (search_pos != -1)
1955 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1957 /* unfold maybe folded results */
1958 sci_ensure_line_is_visible(doc->editor->sci, line);
1960 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1961 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1963 if (! editor_line_in_view(doc->editor, line))
1964 { /* we need to force scrolling in case the cursor is outside of the current visible area
1965 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1966 * while searching */
1967 editor_scroll_to_line(doc->editor, -1, 0.3F);
1969 else
1970 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1971 return TRUE;
1973 else
1975 if (! inc)
1977 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1979 utils_beep();
1980 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1981 return FALSE;
1986 /* General search function, used from the find dialog.
1987 * Returns -1 on failure or the start position of the matching text.
1988 * Will skip past any selection, ignoring it.
1990 * @param text Text to find.
1991 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1993 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
1994 gint flags, gboolean search_backwards, GeanyMatchInfo **match_,
1995 gboolean scroll, GtkWidget *parent)
1997 gint selection_end, selection_start, search_pos;
1999 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2000 if (! *text)
2001 return -1;
2003 /* Sci doesn't support searching backwards with a regex */
2004 if (flags & SCFIND_REGEXP)
2005 search_backwards = FALSE;
2007 if (!original_text)
2008 original_text = text;
2010 selection_start = sci_get_selection_start(doc->editor->sci);
2011 selection_end = sci_get_selection_end(doc->editor->sci);
2012 if ((selection_end - selection_start) > 0)
2013 { /* there's a selection so go to the end */
2014 if (search_backwards)
2015 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2016 else
2017 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2020 sci_set_search_anchor(doc->editor->sci);
2021 if (search_backwards)
2022 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2023 else
2024 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2026 if (search_pos != -1)
2028 /* unfold maybe folded results */
2029 sci_ensure_line_is_visible(doc->editor->sci,
2030 sci_get_line_from_position(doc->editor->sci, search_pos));
2031 if (scroll)
2032 doc->editor->scroll_percent = 0.3F;
2034 else
2036 gint sci_len = sci_get_length(doc->editor->sci);
2038 /* if we just searched the whole text, give up searching. */
2039 if ((selection_end == 0 && ! search_backwards) ||
2040 (selection_end == sci_len && search_backwards))
2042 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2043 utils_beep();
2044 return -1;
2047 /* we searched only part of the document, so ask whether to wraparound. */
2048 if (search_prefs.always_wrap ||
2049 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2050 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2052 gint ret;
2054 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2055 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2056 if (ret == -1)
2057 { /* return to original cursor position if not found */
2058 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2060 return ret;
2063 return search_pos;
2067 /* Replaces the selection if it matches, otherwise just finds the next match.
2068 * Returns: start of replaced text, or -1 if no replacement was made
2070 * @param find_text Text to find.
2071 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2073 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2074 const gchar *replace_text, gint flags, gboolean search_backwards)
2076 gint selection_end, selection_start, search_pos;
2077 GeanyMatchInfo *match = NULL;
2079 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2081 if (! *find_text)
2082 return -1;
2084 /* Sci doesn't support searching backwards with a regex */
2085 if (flags & SCFIND_REGEXP)
2086 search_backwards = FALSE;
2088 if (!original_find_text)
2089 original_find_text = find_text;
2091 selection_start = sci_get_selection_start(doc->editor->sci);
2092 selection_end = sci_get_selection_end(doc->editor->sci);
2093 if (selection_end == selection_start)
2095 /* no selection so just find the next match */
2096 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2097 return -1;
2099 /* there's a selection so go to the start before finding to search through it
2100 * this ensures there is a match */
2101 if (search_backwards)
2102 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2103 else
2104 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2106 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2107 /* return if the original selected text did not match (at the start of the selection) */
2108 if (search_pos != selection_start)
2110 if (search_pos != -1)
2111 geany_match_info_free(match);
2112 return -1;
2115 if (search_pos != -1)
2117 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2118 /* select the replacement - find text will skip past the selected text */
2119 sci_set_selection_start(doc->editor->sci, search_pos);
2120 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2121 geany_match_info_free(match);
2123 else
2125 /* no match in the selection */
2126 utils_beep();
2128 return search_pos;
2132 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2133 const gchar *original_replace_text)
2135 gchar *filename;
2137 if (count == 0)
2139 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2140 return;
2143 filename = g_path_get_basename(DOC_FILENAME(doc));
2144 ui_set_statusbar(TRUE, ngettext(
2145 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2146 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2147 count), filename, count, original_find_text, original_replace_text);
2148 g_free(filename);
2152 /* Replace all text matches in a certain range within document.
2153 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2154 * or -1 if no text was found.
2155 * scroll_to_match is whether to scroll the last replacement in view (which also
2156 * clears the selection).
2157 * Returns: the number of replacements made. */
2158 static guint
2159 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2160 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2162 gint count = 0;
2163 struct Sci_TextToFind ttf;
2164 ScintillaObject *sci;
2166 if (new_range_end != NULL)
2167 *new_range_end = -1;
2169 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2171 if (! *find_text || doc->readonly)
2172 return 0;
2174 sci = doc->editor->sci;
2176 ttf.chrg.cpMin = start;
2177 ttf.chrg.cpMax = end;
2178 ttf.lpstrText = (gchar*)find_text;
2180 sci_start_undo_action(sci);
2181 count = search_replace_range(sci, &ttf, flags, replace_text);
2182 sci_end_undo_action(sci);
2184 if (count > 0)
2185 { /* scroll last match in view, will destroy the existing selection */
2186 if (scroll_to_match)
2187 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2189 if (new_range_end != NULL)
2190 *new_range_end = ttf.chrg.cpMax;
2192 return count;
2196 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2197 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2199 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2200 gint max_column = 0, count = 0;
2201 gboolean replaced = FALSE;
2203 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2205 if (! *find_text)
2206 return;
2208 selection_start = sci_get_selection_start(doc->editor->sci);
2209 selection_end = sci_get_selection_end(doc->editor->sci);
2210 /* do we have a selection? */
2211 if ((selection_end - selection_start) == 0)
2213 utils_beep();
2214 return;
2217 selection_mode = sci_get_selection_mode(doc->editor->sci);
2218 selected_lines = sci_get_lines_selected(doc->editor->sci);
2219 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2220 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2222 gint first_line, line;
2224 sci_start_undo_action(doc->editor->sci);
2226 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2227 /* Find the last line with chars selected (not EOL char) */
2228 last_line = sci_get_line_from_position(doc->editor->sci,
2229 selection_end - editor_get_eol_char_len(doc->editor));
2230 last_line = MAX(first_line, last_line);
2231 for (line = first_line; line < (first_line + selected_lines); line++)
2233 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2234 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2236 /* skip line if there is no selection */
2237 if (line_start != INVALID_POSITION)
2239 /* don't let document_replace_range() scroll to match to keep our selection */
2240 gint new_sel_end;
2242 count += document_replace_range(doc, find_text, replace_text, flags,
2243 line_start, line_end, FALSE, &new_sel_end);
2244 if (new_sel_end != -1)
2246 replaced = TRUE;
2247 /* this gets the greatest column within the selection after replacing */
2248 max_column = MAX(max_column,
2249 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2253 sci_end_undo_action(doc->editor->sci);
2255 else /* handle normal line selection */
2257 count += document_replace_range(doc, find_text, replace_text, flags,
2258 selection_start, selection_end, TRUE, &selection_end);
2259 if (selection_end != -1)
2260 replaced = TRUE;
2263 if (replaced)
2264 { /* update the selection for the new endpoint */
2266 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2268 /* now we can scroll to the selection and destroy it because we rebuild it later */
2269 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2271 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2272 * the highest column on the last line. The wrapped selection is completely different
2273 * from the original one, so skip the selection at all */
2274 /* TODO is there a better way to handle the wrapped selection? */
2275 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2276 { /* for keeping and adjusting the selection in multi line rectangle selection we
2277 * need the last line of the original selection and the greatest column number after
2278 * replacing and set the selection end to the last line at the greatest column */
2279 sci_set_selection_start(doc->editor->sci, selection_start);
2280 sci_set_selection_end(doc->editor->sci,
2281 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2282 sci_set_selection_mode(doc->editor->sci, selection_mode);
2285 else
2287 sci_set_selection_start(doc->editor->sci, selection_start);
2288 sci_set_selection_end(doc->editor->sci, selection_end);
2291 else /* no replacements */
2292 utils_beep();
2294 show_replace_summary(doc, count, original_find_text, original_replace_text);
2298 /* returns number of replacements made. */
2299 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2300 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2302 gint len, count;
2303 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2305 if (! *find_text)
2306 return FALSE;
2308 len = sci_get_length(doc->editor->sci);
2309 count = document_replace_range(
2310 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2312 show_replace_summary(doc, count, original_find_text, original_replace_text);
2313 return count;
2318 * Parses or re-parses the document's buffer and updates the type
2319 * keywords and symbol list.
2321 * @param doc The document.
2323 void document_update_tags(GeanyDocument *doc)
2325 guchar *buffer_ptr;
2326 gsize len;
2328 g_return_if_fail(DOC_VALID(doc));
2329 g_return_if_fail(app->tm_workspace != NULL);
2331 /* early out if it's a new file or doesn't support tags */
2332 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2334 /* We must call sidebar_update_tag_list() before returning,
2335 * to ensure that the symbol list is always updated properly (e.g.
2336 * when creating a new document with a partial filename set. */
2337 sidebar_update_tag_list(doc, FALSE);
2338 return;
2341 /* create a new TM file if there isn't one yet */
2342 if (! doc->tm_file)
2344 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2345 const gchar *name;
2347 /* lookup the name rather than using filetype name to support custom filetypes */
2348 name = tm_source_file_get_lang_name(doc->file_type->lang);
2349 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2350 g_free(locale_filename);
2352 if (doc->tm_file && !tm_workspace_add_object(doc->tm_file))
2354 tm_work_object_free(doc->tm_file);
2355 doc->tm_file = NULL;
2359 /* early out if there's no work object and we couldn't create one */
2360 if (doc->tm_file == NULL)
2362 /* We must call sidebar_update_tag_list() before returning,
2363 * to ensure that the symbol list is always updated properly (e.g.
2364 * when creating a new document with a partial filename set. */
2365 sidebar_update_tag_list(doc, FALSE);
2366 return;
2369 len = sci_get_length(doc->editor->sci);
2370 /* tm_source_file_buffer_update() below don't support 0-length data,
2371 * so just empty the tags array and leave */
2372 if (len < 1)
2374 tm_tags_array_free(doc->tm_file->tags_array, FALSE);
2375 sidebar_update_tag_list(doc, FALSE);
2376 return;
2379 /* Parse Scintilla's buffer directly using TagManager
2380 * Note: this buffer *MUST NOT* be modified */
2381 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2382 tm_source_file_buffer_update(doc->tm_file, buffer_ptr, len, TRUE);
2384 sidebar_update_tag_list(doc, TRUE);
2385 document_highlight_tags(doc);
2389 /* Re-highlights type keywords without re-parsing the whole document. */
2390 void document_highlight_tags(GeanyDocument *doc)
2392 GString *keywords_str;
2393 gchar *keywords;
2394 gint keyword_idx;
2396 /* some filetypes support type keywords (such as struct names), but not
2397 * necessarily all filetypes for a particular scintilla lexer. this
2398 * tells us whether the filetype supports keywords, and if so
2399 * which index to use for the scintilla keywords set. */
2400 switch (doc->file_type->id)
2402 case GEANY_FILETYPES_C:
2403 case GEANY_FILETYPES_CPP:
2404 case GEANY_FILETYPES_CS:
2405 case GEANY_FILETYPES_D:
2406 case GEANY_FILETYPES_JAVA:
2407 case GEANY_FILETYPES_OBJECTIVEC:
2408 case GEANY_FILETYPES_VALA:
2409 case GEANY_FILETYPES_RUST:
2412 /* index of the keyword set in the Scintilla lexer, for
2413 * example in LexCPP.cxx, see "cppWordLists" global array.
2414 * TODO: this magic number should be a member of the filetype */
2415 keyword_idx = 3;
2416 break;
2418 default:
2419 return; /* early out if type keywords are not supported */
2421 if (!app->tm_workspace->work_object.tags_array)
2422 return;
2424 /* get any type keywords and tell scintilla about them
2425 * this will cause the type keywords to be colourized in scintilla */
2426 keywords_str = symbols_find_tags_as_string(app->tm_workspace->work_object.tags_array,
2427 TM_GLOBAL_TYPE_MASK, doc->file_type->lang);
2428 if (keywords_str)
2430 keywords = g_string_free(keywords_str, FALSE);
2431 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2432 g_free(keywords);
2433 queue_colourise(doc); /* force re-highlighting the entire document */
2438 static gboolean on_document_update_tag_list_idle(gpointer data)
2440 GeanyDocument *doc = data;
2442 if (! DOC_VALID(doc))
2443 return FALSE;
2445 if (! main_status.quitting)
2446 document_update_tags(doc);
2448 doc->priv->tag_list_update_source = 0;
2450 /* don't update the tags until another modification of the buffer */
2451 return FALSE;
2455 void document_update_tag_list_in_idle(GeanyDocument *doc)
2457 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2458 return;
2460 /* prevent "stacking up" callback handlers, we only need one to run soon */
2461 if (doc->priv->tag_list_update_source != 0)
2462 g_source_remove(doc->priv->tag_list_update_source);
2464 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2465 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2469 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2470 gboolean filetype_changed)
2472 g_return_if_fail(doc);
2473 if (type == NULL)
2474 type = filetypes[GEANY_FILETYPES_NONE];
2476 if (filetype_changed)
2478 doc->file_type = type;
2480 /* delete tm file object to force creation of a new one */
2481 if (doc->tm_file != NULL)
2483 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2484 doc->tm_file = NULL;
2486 /* load tags files before highlighting (some lexers highlight global typenames) */
2487 if (type->id != GEANY_FILETYPES_NONE)
2488 symbols_global_tags_loaded(type->id);
2490 highlighting_set_styles(doc->editor->sci, type);
2491 editor_set_indentation_guides(doc->editor);
2492 build_menu_update(doc);
2493 queue_colourise(doc);
2494 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2497 document_update_tags(doc);
2501 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2502 * @param doc The document to use.
2503 * @param type The filetype. */
2504 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2506 gboolean ft_changed;
2507 GeanyFiletype *old_ft;
2509 g_return_if_fail(doc);
2510 if (type == NULL)
2511 type = filetypes[GEANY_FILETYPES_NONE];
2513 old_ft = doc->file_type;
2514 geany_debug("%s : %s (%s)",
2515 (doc->file_name != NULL) ? doc->file_name : "unknown",
2516 type->name,
2517 (doc->encoding != NULL) ? doc->encoding : "unknown");
2519 ft_changed = (doc->file_type != type); /* filetype has changed */
2520 document_load_config(doc, type, ft_changed);
2522 if (ft_changed)
2524 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2526 /* assume that if previous filetype was none and the settings are the default ones, this
2527 * is the first time the filetype is carefully set, so we should apply indent settings */
2528 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2529 doc->editor->indent_type == iprefs->type &&
2530 doc->editor->indent_width == iprefs->width)
2532 document_apply_indent_settings(doc);
2533 ui_document_show_hide(doc);
2536 sidebar_openfiles_update(doc); /* to update the icon */
2537 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2542 void document_reload_config(GeanyDocument *doc)
2544 document_load_config(doc, doc->file_type, TRUE);
2549 * Sets the encoding of a document.
2550 * This function only set the encoding of the %document, it does not any conversions. The new
2551 * encoding is used when e.g. saving the file.
2553 * @param doc The document to use.
2554 * @param new_encoding The encoding to be set for the document.
2556 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2558 if (doc == NULL || new_encoding == NULL ||
2559 utils_str_equal(new_encoding, doc->encoding))
2560 return;
2562 g_free(doc->encoding);
2563 doc->encoding = g_strdup(new_encoding);
2565 ui_update_statusbar(doc, -1);
2566 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2567 encodings_is_unicode_charset(doc->encoding));
2571 /* own Undo / Redo implementation to be able to undo / redo changes
2572 * to the encoding or the Unicode BOM (which are Scintilla independet).
2573 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2575 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2576 void document_undo_clear(GeanyDocument *doc)
2578 undo_action *a;
2580 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2582 a = g_trash_stack_pop(&doc->priv->undo_actions);
2583 if (G_LIKELY(a != NULL))
2585 switch (a->type)
2587 case UNDO_ENCODING: g_free(a->data); break;
2588 default: break;
2590 g_free(a);
2593 doc->priv->undo_actions = NULL;
2595 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2597 a = g_trash_stack_pop(&doc->priv->redo_actions);
2598 if (G_LIKELY(a != NULL))
2600 switch (a->type)
2602 case UNDO_ENCODING: g_free(a->data); break;
2603 default: break;
2605 g_free(a);
2608 doc->priv->redo_actions = NULL;
2610 if (! main_status.quitting && doc->editor != NULL)
2611 document_set_text_changed(doc, FALSE);
2615 /* note: this is called on SCN_MODIFIED notifications */
2616 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2618 undo_action *action;
2620 g_return_if_fail(doc != NULL);
2622 action = g_new0(undo_action, 1);
2623 action->type = type;
2624 action->data = data;
2626 g_trash_stack_push(&doc->priv->undo_actions, action);
2628 /* avoid unnecessary redraws */
2629 if (type != UNDO_SCINTILLA || !doc->changed)
2630 document_set_text_changed(doc, TRUE);
2632 ui_update_popup_reundo_items(doc);
2636 gboolean document_can_undo(GeanyDocument *doc)
2638 g_return_val_if_fail(doc != NULL, FALSE);
2640 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2641 return TRUE;
2642 else
2643 return FALSE;
2647 static void update_changed_state(GeanyDocument *doc)
2649 doc->changed =
2650 (sci_is_modified(doc->editor->sci) ||
2651 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2652 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2653 document_set_text_changed(doc, doc->changed);
2657 void document_undo(GeanyDocument *doc)
2659 undo_action *action;
2661 g_return_if_fail(doc != NULL);
2663 action = g_trash_stack_pop(&doc->priv->undo_actions);
2665 if (G_UNLIKELY(action == NULL))
2667 /* fallback, should not be necessary */
2668 geany_debug("%s: fallback used", G_STRFUNC);
2669 sci_undo(doc->editor->sci);
2671 else
2673 switch (action->type)
2675 case UNDO_SCINTILLA:
2677 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2679 sci_undo(doc->editor->sci);
2680 break;
2682 case UNDO_BOM:
2684 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2686 doc->has_bom = GPOINTER_TO_INT(action->data);
2687 ui_update_statusbar(doc, -1);
2688 ui_document_show_hide(doc);
2689 break;
2691 case UNDO_ENCODING:
2693 /* use the "old" encoding */
2694 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2696 document_set_encoding(doc, (const gchar*)action->data);
2698 ignore_callback = TRUE;
2699 encodings_select_radio_item((const gchar*)action->data);
2700 ignore_callback = FALSE;
2702 g_free(action->data);
2703 break;
2705 default: break;
2708 g_free(action); /* free the action which was taken from the stack */
2710 update_changed_state(doc);
2711 ui_update_popup_reundo_items(doc);
2715 gboolean document_can_redo(GeanyDocument *doc)
2717 g_return_val_if_fail(doc != NULL, FALSE);
2719 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2720 return TRUE;
2721 else
2722 return FALSE;
2726 void document_redo(GeanyDocument *doc)
2728 undo_action *action;
2730 g_return_if_fail(doc != NULL);
2732 action = g_trash_stack_pop(&doc->priv->redo_actions);
2734 if (G_UNLIKELY(action == NULL))
2736 /* fallback, should not be necessary */
2737 geany_debug("%s: fallback used", G_STRFUNC);
2738 sci_redo(doc->editor->sci);
2740 else
2742 switch (action->type)
2744 case UNDO_SCINTILLA:
2746 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2748 sci_redo(doc->editor->sci);
2749 break;
2751 case UNDO_BOM:
2753 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2755 doc->has_bom = GPOINTER_TO_INT(action->data);
2756 ui_update_statusbar(doc, -1);
2757 ui_document_show_hide(doc);
2758 break;
2760 case UNDO_ENCODING:
2762 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2764 document_set_encoding(doc, (const gchar*)action->data);
2766 ignore_callback = TRUE;
2767 encodings_select_radio_item((const gchar*)action->data);
2768 ignore_callback = FALSE;
2770 g_free(action->data);
2771 break;
2773 default: break;
2776 g_free(action); /* free the action which was taken from the stack */
2778 update_changed_state(doc);
2779 ui_update_popup_reundo_items(doc);
2783 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2785 undo_action *action;
2787 g_return_if_fail(doc != NULL);
2789 action = g_new0(undo_action, 1);
2790 action->type = type;
2791 action->data = data;
2793 g_trash_stack_push(&doc->priv->redo_actions, action);
2795 if (type != UNDO_SCINTILLA || !doc->changed)
2796 document_set_text_changed(doc, TRUE);
2798 ui_update_popup_reundo_items(doc);
2802 enum
2804 STATUS_CHANGED,
2805 #ifdef USE_GIO_FILEMON
2806 STATUS_DISK_CHANGED,
2807 #endif
2808 STATUS_READONLY
2810 static struct
2812 const gchar *name;
2813 GdkColor color;
2814 gboolean loaded;
2815 } document_status_styles[] = {
2816 { "geany-document-status-changed", {0}, FALSE },
2817 #ifdef USE_GIO_FILEMON
2818 { "geany-document-status-disk-changed", {0}, FALSE },
2819 #endif
2820 { "geany-document-status-readonly", {0}, FALSE }
2824 static gint document_get_status_id(GeanyDocument *doc)
2826 if (doc->changed)
2827 return STATUS_CHANGED;
2828 #ifdef USE_GIO_FILEMON
2829 else if (doc->priv->file_disk_status == FILE_CHANGED)
2830 return STATUS_DISK_CHANGED;
2831 #endif
2832 else if (doc->readonly)
2833 return STATUS_READONLY;
2835 return -1;
2839 /* returns an identifier that is to be set as a widget name or class to get it styled
2840 * depending on the document status (changed, readonly, etc.)
2841 * a NULL return value means default (unchanged) style */
2842 const gchar *document_get_status_widget_class(GeanyDocument *doc)
2844 gint status;
2846 g_return_val_if_fail(doc != NULL, NULL);
2848 status = document_get_status_id(doc);
2849 if (status < 0)
2850 return NULL;
2851 else
2852 return document_status_styles[status].name;
2857 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2858 * Returned colors are red if the document has changes, green if the document is read-only
2859 * or simply @c NULL if the document is unmodified but writable.
2861 * @param doc The document to use.
2863 * @return The color for the document or @c NULL if the default color should be used. The color
2864 * object is owned by Geany and should not be modified or freed.
2866 * @since 0.16
2868 const GdkColor *document_get_status_color(GeanyDocument *doc)
2870 gint status;
2872 g_return_val_if_fail(doc != NULL, NULL);
2874 status = document_get_status_id(doc);
2875 if (status < 0)
2876 return NULL;
2877 if (! document_status_styles[status].loaded)
2879 #if GTK_CHECK_VERSION(3, 0, 0)
2880 GdkRGBA color;
2881 GtkWidgetPath *path = gtk_widget_path_new();
2882 GtkStyleContext *ctx = gtk_style_context_new();
2883 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
2884 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
2885 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
2886 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
2887 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
2888 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
2889 gtk_style_context_set_path(ctx, path);
2890 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
2891 document_status_styles[status].color.red = 0xffff * color.red;
2892 document_status_styles[status].color.green = 0xffff * color.green;
2893 document_status_styles[status].color.blue = 0xffff * color.blue;
2894 document_status_styles[status].loaded = TRUE;
2895 gtk_widget_path_unref(path);
2896 g_object_unref(ctx);
2897 #else
2898 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
2899 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
2900 document_status_styles[status].name, NULL);
2901 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
2903 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
2904 document_status_styles[status].loaded = TRUE;
2905 g_free(path);
2906 #endif
2908 return &document_status_styles[status].color;
2912 /** Accessor function for @ref documents_array items.
2913 * @warning Always check the returned document is valid (@c doc->is_valid).
2914 * @param idx @c documents_array index.
2915 * @return The document, or @c NULL if @a idx is out of range.
2917 * @since 0.16
2919 GeanyDocument *document_index(gint idx)
2921 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2925 /* create a new file and copy file content and properties */
2926 G_MODULE_EXPORT void on_clone1_activate(GtkMenuItem *menuitem, gpointer user_data)
2928 GeanyDocument *old_doc = document_get_current();
2930 if (old_doc)
2931 document_clone(old_doc);
2935 GeanyDocument *document_clone(GeanyDocument *old_doc)
2937 gchar *text;
2938 GeanyDocument *doc;
2939 ScintillaObject *old_sci;
2941 g_return_val_if_fail(old_doc, NULL);
2942 old_sci = old_doc->editor->sci;
2943 if (sci_has_selection(old_sci))
2944 text = sci_get_selection_contents(old_sci);
2945 else
2946 text = sci_get_contents(old_sci, -1);
2948 doc = document_new_file(NULL, old_doc->file_type, text);
2949 g_free(text);
2950 document_set_text_changed(doc, TRUE);
2952 /* copy file properties */
2953 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2954 doc->editor->line_breaking = old_doc->editor->line_breaking;
2955 doc->editor->auto_indent = old_doc->editor->auto_indent;
2956 editor_set_indent(doc->editor, old_doc->editor->indent_type,
2957 old_doc->editor->indent_width);
2958 doc->readonly = old_doc->readonly;
2959 doc->has_bom = old_doc->has_bom;
2960 doc->priv->protected = 0;
2961 document_set_encoding(doc, old_doc->encoding);
2962 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2963 sci_set_readonly(doc->editor->sci, doc->readonly);
2965 /* update ui */
2966 ui_document_show_hide(doc);
2967 return doc;
2971 /* @note If successful, this should always be followed up with a call to
2972 * document_close_all().
2973 * @return TRUE if all files were saved or had their changes discarded. */
2974 gboolean document_account_for_unsaved(void)
2976 guint i, p, page_count;
2978 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2979 /* iterate over documents in tabs order */
2980 for (p = 0; p < page_count; p++)
2982 GeanyDocument *doc = document_get_from_page(p);
2984 if (DOC_VALID(doc) && doc->changed)
2986 if (! dialogs_show_unsaved_file(doc))
2987 return FALSE;
2990 /* all documents should now be accounted for, so ignore any changes */
2991 foreach_document (i)
2993 documents[i]->changed = FALSE;
2995 return TRUE;
2999 static void force_close_all(void)
3001 guint i, len = documents_array->len;
3003 /* check all documents have been accounted for */
3004 for (i = 0; i < len; i++)
3006 if (documents[i]->is_valid)
3008 g_return_if_fail(!documents[i]->changed);
3011 main_status.closing_all = TRUE;
3013 foreach_document(i)
3015 document_close(documents[i]);
3018 main_status.closing_all = FALSE;
3022 gboolean document_close_all(void)
3024 if (! document_account_for_unsaved())
3025 return FALSE;
3027 force_close_all();
3029 return TRUE;
3033 /* *
3034 * Shows a message related to a document.
3036 * Use this whenever the user needs to see a document-related message,
3037 * for example when the file was externally modified or deleted.
3039 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3040 * @a response_1 response will be the default for the @c GtkInfoBar or
3041 * @c GtkDialog.
3043 * @param doc @c GeanyDocument.
3044 * @param msgtype The type of message.
3045 * @param response_cb A callback function called when there's a response.
3046 * @param btn_1 The first action area button.
3047 * @param response_1 The response for @a btn_1.
3048 * @param btn_2 The second action area button.
3049 * @param response_2 The response for @a btn_2.
3050 * @param btn_3 The third action area button.
3051 * @param response_3 The response for @a btn_3.
3052 * @param extra_text Text to show below the main message.
3053 * @param format The text format for the main message.
3054 * @param ... Used with @a format as in @c printf.
3056 * @since 1.25
3057 * */
3058 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3059 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3060 const gchar *btn_1, GtkResponseType response_1,
3061 const gchar *btn_2, GtkResponseType response_2,
3062 const gchar *btn_3, GtkResponseType response_3,
3063 const gchar *extra_text, const gchar *format, ...)
3065 va_list args;
3066 gchar *text, *markup;
3067 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3068 GtkWidget *info_widget, *parent;
3069 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook),
3070 document_get_notebook_page(doc));
3072 va_start(args, format);
3073 text = g_strdup_vprintf(format, args);
3074 va_end(args);
3076 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3077 g_free(text);
3079 info_widget = gtk_info_bar_new();
3080 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3081 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3083 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3085 if (btn_1)
3086 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3087 if (btn_2)
3088 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3089 if (btn_3)
3090 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3092 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3094 label = gtk_label_new(NULL);
3095 gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
3097 gtk_label_set_markup(GTK_LABEL(label), markup);
3098 g_free(markup);
3100 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3101 g_signal_connect_after(info_widget, "response", G_CALLBACK(gtk_widget_destroy), NULL);
3103 hbox = gtk_hbox_new(FALSE, 12);
3104 gtk_container_add(GTK_CONTAINER(content_area), hbox);
3106 switch (msgtype)
3108 case GTK_MESSAGE_INFO:
3109 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3110 break;
3111 case GTK_MESSAGE_WARNING:
3112 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3113 break;
3114 case GTK_MESSAGE_QUESTION:
3115 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3116 break;
3117 case GTK_MESSAGE_ERROR:
3118 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3119 break;
3120 default:
3121 icon = NULL;
3122 break;
3125 if (icon)
3126 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3128 if (extra_text)
3130 vbox = gtk_vbox_new(FALSE, 6);
3131 extra_label = gtk_label_new(extra_text);
3132 gtk_misc_set_alignment(GTK_MISC(extra_label), 0.0, 0.5);
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_container_add(GTK_CONTAINER(hbox), vbox);
3137 else
3138 gtk_container_add(GTK_CONTAINER(hbox), label);
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_KEY_Tab:
3165 case GDK_KEY_ISO_Left_Tab:
3167 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3168 GtkDirectionType dir = event->keyval == GDK_KEY_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3169 gtk_widget_child_focus(action_area, dir);
3170 return TRUE;
3172 case GDK_KEY_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 gint nonmacro_g_signal_handlers_disconnect_by_data(gpointer instance, gpointer data)
3185 return g_signal_handlers_disconnect_by_data(instance, data);
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_swapped(bar, "unrealize",
3193 G_CALLBACK(nonmacro_g_signal_handlers_disconnect_by_data), doc->editor->sci);
3196 static void monitor_reload_file(GeanyDocument *doc)
3198 gchar *base_name = g_path_get_basename(doc->file_name);
3200 /* show this message only once */
3201 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3203 GtkWidget *bar;
3205 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3206 _("_Reload"), GTK_RESPONSE_ACCEPT,
3207 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3208 NULL, GTK_RESPONSE_NONE,
3209 _("Do you want to reload it?"),
3210 _("The file '%s' on the disk is more recent than the current buffer."),
3211 base_name);
3213 protect_document(doc);
3214 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3215 enable_key_intercept(doc, bar);
3217 g_free(base_name);
3221 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3222 gint response_id,
3223 GeanyDocument *doc)
3225 gboolean file_saved = FALSE;
3227 unprotect_document(doc);
3229 if (response_id == GTK_RESPONSE_ACCEPT)
3230 file_saved = dialogs_show_save_as();
3232 if (!file_saved)
3234 document_set_text_changed(doc, TRUE);
3235 /* don't prompt more than once */
3236 SETPTR(doc->real_path, NULL);
3239 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3243 static void monitor_resave_missing_file(GeanyDocument *doc)
3245 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3247 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3249 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3250 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3252 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3253 on_monitor_resave_missing_file_response,
3254 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
3255 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3256 NULL, GTK_RESPONSE_NONE,
3257 _("Try to resave the file?"),
3258 _("File \"%s\" was not found on disk!"),
3259 doc->file_name);
3261 protect_document(doc);
3262 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3263 enable_key_intercept(doc, bar);
3268 /* Set force to force a disk check, otherwise it is ignored if there was a check
3269 * in the last file_prefs.disk_check_timeout seconds.
3270 * @return @c TRUE if the file has changed. */
3271 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3273 gboolean ret = FALSE;
3274 gboolean use_gio_filemon;
3275 time_t cur_time = 0;
3276 struct stat st;
3277 gchar *locale_filename;
3278 FileDiskStatus old_status;
3280 g_return_val_if_fail(doc != NULL, FALSE);
3282 /* ignore remote files and documents that have never been saved to disk */
3283 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3284 || doc->real_path == NULL || doc->priv->is_remote)
3285 return FALSE;
3287 use_gio_filemon = (doc->priv->monitor != NULL);
3289 if (use_gio_filemon)
3291 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3292 return FALSE;
3294 else
3296 cur_time = time(NULL);
3297 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3298 return FALSE;
3300 doc->priv->last_check = cur_time;
3303 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3304 if (g_stat(locale_filename, &st) != 0)
3306 monitor_resave_missing_file(doc);
3307 /* doc may be closed now */
3308 ret = TRUE;
3310 else if (! use_gio_filemon && /* ignore check when using GIO */
3311 doc->priv->mtime > cur_time)
3313 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3314 /* Note: on Windows st.st_mtime can be newer than cur_time */
3316 else if (doc->priv->mtime < st.st_mtime)
3318 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3319 doc->priv->mtime = st.st_mtime;
3320 monitor_reload_file(doc);
3321 /* doc may be closed now */
3322 ret = TRUE;
3324 g_free(locale_filename);
3326 if (DOC_VALID(doc))
3327 { /* doc can get invalid when a document was closed */
3328 old_status = doc->priv->file_disk_status;
3329 doc->priv->file_disk_status = FILE_OK;
3330 if (old_status != doc->priv->file_disk_status)
3331 ui_update_tab_status(doc);
3333 return ret;
3337 /** Compares documents by their display names.
3338 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3339 * @note 'Display name' means the base name of the document's filename.
3341 * @param a @c GeanyDocument**.
3342 * @param b @c GeanyDocument**.
3343 * @warning The arguments take the address of each document pointer.
3344 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3346 * @since 0.21
3348 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3350 GeanyDocument *doc_a = *((GeanyDocument**) a);
3351 GeanyDocument *doc_b = *((GeanyDocument**) b);
3352 gchar *base_name_a, *base_name_b;
3353 gint result;
3355 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3356 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3358 result = strcmp(base_name_a, base_name_b);
3360 g_free(base_name_a);
3361 g_free(base_name_b);
3363 return result;
3367 /** Compares documents by their tab order.
3368 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3370 * @param a @c GeanyDocument**.
3371 * @param b @c GeanyDocument**.
3372 * @warning The arguments take the address of each document pointer.
3373 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3375 * @since 0.21 (GEANY_API_VERSION 209)
3377 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3379 GeanyDocument *doc_a = *((GeanyDocument**) a);
3380 GeanyDocument *doc_b = *((GeanyDocument**) b);
3381 gint notebook_position_doc_a;
3382 gint notebook_position_doc_b;
3384 notebook_position_doc_a = document_get_notebook_page(doc_a);
3385 notebook_position_doc_b = document_get_notebook_page(doc_b);
3387 if (notebook_position_doc_a < notebook_position_doc_b)
3388 return -1;
3389 if (notebook_position_doc_a > notebook_position_doc_b)
3390 return 1;
3391 /* equality */
3392 return 0;
3396 /** Compares documents by their tab order, in reverse order.
3397 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3399 * @param a @c GeanyDocument**.
3400 * @param b @c GeanyDocument**.
3401 * @warning The arguments take the address of each document pointer.
3402 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3404 * @since 0.21 (GEANY_API_VERSION 209)
3406 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3408 GeanyDocument *doc_a = *((GeanyDocument**) a);
3409 GeanyDocument *doc_b = *((GeanyDocument**) b);
3410 gint notebook_position_doc_a;
3411 gint notebook_position_doc_b;
3413 notebook_position_doc_a = document_get_notebook_page(doc_a);
3414 notebook_position_doc_b = document_get_notebook_page(doc_b);
3416 if (notebook_position_doc_a < notebook_position_doc_b)
3417 return 1;
3418 if (notebook_position_doc_a > notebook_position_doc_b)
3419 return -1;
3420 /* equality */
3421 return 0;
3425 void document_grab_focus(GeanyDocument *doc)
3427 g_return_if_fail(doc != NULL);
3429 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));