Merge pull request #1133 from techee/readme_rst
[geany-mirror.git] / src / document.c
blobe144cc1d10754265515f7b94300d05e2c7a8111e
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 "encodingsprivate.h"
39 #include "filetypesprivate.h"
40 #include "geany.h" /* FIXME: why is this needed for DOC_FILENAME()? should come from documentprivate.h/document.h */
41 #include "geanyobject.h"
42 #include "geanywraplabel.h"
43 #include "highlighting.h"
44 #include "main.h"
45 #include "msgwindow.h"
46 #include "navqueue.h"
47 #include "notebook.h"
48 #include "project.h"
49 #include "sciwrappers.h"
50 #include "sidebar.h"
51 #include "support.h"
52 #include "symbols.h"
53 #include "ui_utils.h"
54 #include "utils.h"
55 #include "vte.h"
56 #include "win32.h"
58 #include "gtkcompat.h"
60 #ifdef HAVE_SYS_TIME_H
61 # include <sys/time.h>
62 #endif
63 #include <time.h>
65 #include <unistd.h>
66 #include <string.h>
67 #include <errno.h>
69 #ifdef HAVE_SYS_TYPES_H
70 # include <sys/types.h>
71 #endif
73 #include <stdlib.h>
75 /* gstdio.h also includes sys/stat.h */
76 #include <glib/gstdio.h>
78 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
79 /*#define USE_GIO_FILEMON 1*/
80 #include <gio/gio.h>
82 #include <gdk/gdkkeysyms.h>
85 #define USE_GIO_FILE_OPERATIONS (!file_prefs.use_safe_file_saving && file_prefs.use_gio_unsafe_file_saving)
88 GeanyFilePrefs file_prefs;
89 GPtrArray *documents_array = NULL;
92 /* an undo action, also used for redo actions */
93 typedef struct
95 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
96 guint type; /* to identify the action */
97 gpointer *data; /* the old value (before the change), in case of a redo action
98 * it contains the new value */
99 } undo_action;
101 /* Custom document info bar response IDs */
102 enum
104 RESPONSE_DOCUMENT_RELOAD = 1,
105 RESPONSE_DOCUMENT_SAVE,
109 static guint doc_id_counter = 0;
112 static void document_undo_clear_stack(GTrashStack **stack);
113 static void document_undo_clear(GeanyDocument *doc);
114 static void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data);
115 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
116 static gboolean remove_page(guint page_num);
117 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
118 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
119 const gchar *btn_1, GtkResponseType response_1,
120 const gchar *btn_2, GtkResponseType response_2,
121 const gchar *btn_3, GtkResponseType response_3,
122 const gchar *extra_text, const gchar *format, ...) G_GNUC_PRINTF(11, 12);
126 * Finds a document whose @c real_path field matches the given filename.
128 * @param realname The filename to search, which should be identical to the
129 * string returned by @c tm_get_real_path().
131 * @return @transfer{none} @nullable The matching document, or @c NULL.
132 * @note This is only really useful when passing a @c TMSourceFile::file_name.
133 * @see GeanyDocument::real_path.
134 * @see document_find_by_filename().
136 * @since 0.15
138 GEANY_API_SYMBOL
139 GeanyDocument* document_find_by_real_path(const gchar *realname)
141 guint i;
143 if (! realname)
144 return NULL; /* file doesn't exist on disk */
146 for (i = 0; i < documents_array->len; i++)
148 GeanyDocument *doc = documents[i];
150 if (! doc->is_valid || ! doc->real_path)
151 continue;
153 if (utils_filenamecmp(realname, doc->real_path) == 0)
155 return doc;
158 return NULL;
162 /* dereference symlinks, /../ junk in path and return locale encoding */
163 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
165 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
166 gchar *realname = tm_get_real_path(locale_name);
168 g_free(locale_name);
169 return realname;
174 * Finds a document with the given filename.
175 * This matches either an exact GeanyDocument::file_name string, or variant
176 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
177 * match @c "/name").
179 * @param utf8_filename The filename to search (in UTF-8 encoding).
181 * @return @transfer{none} @nullable The matching document, or @c NULL.
182 * @see document_find_by_real_path().
184 GEANY_API_SYMBOL
185 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
187 guint i;
188 GeanyDocument *doc;
189 gchar *realname;
191 g_return_val_if_fail(utf8_filename != NULL, NULL);
193 /* First search GeanyDocument::file_name, so we can find documents with a
194 * filename set but not saved on disk, like vcdiff produces */
195 for (i = 0; i < documents_array->len; i++)
197 doc = documents[i];
199 if (! doc->is_valid || doc->file_name == NULL)
200 continue;
202 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
204 return doc;
207 /* Now try matching based on the realpath(), which is unique per file on disk */
208 realname = get_real_path_from_utf8(utf8_filename);
209 doc = document_find_by_real_path(realname);
210 g_free(realname);
211 return doc;
215 /* returns the document which has sci, or NULL. */
216 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
218 guint i;
220 g_return_val_if_fail(sci != NULL, NULL);
222 for (i = 0; i < documents_array->len; i++)
224 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
225 return documents[i];
227 return NULL;
231 /** Lookup an old document by its ID.
232 * Useful when the corresponding document may have been closed since the
233 * ID was retrieved.
234 * @param id The ID of the document to find
235 * @return @transfer{none} @c NULL if the document is no longer open.
237 * Example:
238 * @code
239 * static guint id;
240 * GeanyDocument *doc = ...;
241 * id = doc->id; // store ID
242 * ...
243 * // time passes - the document may have been closed by now
244 * GeanyDocument *doc = document_find_by_id(id);
245 * gboolean still_open = (doc != NULL);
246 * @endcode
247 * @since 1.25. */
248 GEANY_API_SYMBOL
249 GeanyDocument *document_find_by_id(guint id)
251 guint i;
253 if (!id)
254 return NULL;
256 foreach_document(i)
258 if (documents[i]->id == id)
259 return documents[i];
261 return NULL;
265 /* gets the widget the main_widgets.notebook consider is its child for this document */
266 static GtkWidget *document_get_notebook_child(GeanyDocument *doc)
268 GtkWidget *parent;
269 GtkWidget *child;
271 g_return_val_if_fail(doc != NULL, NULL);
273 child = GTK_WIDGET(doc->editor->sci);
274 parent = gtk_widget_get_parent(child);
275 /* search for the direct notebook child, mirroring document_get_from_page() */
276 while (parent && ! GTK_IS_NOTEBOOK(parent))
278 child = parent;
279 parent = gtk_widget_get_parent(child);
282 return child;
286 /** Gets the notebook page index for a document.
287 * @param doc The document.
288 * @return The index.
289 * @since 0.19 */
290 GEANY_API_SYMBOL
291 gint document_get_notebook_page(GeanyDocument *doc)
293 GtkWidget *child = document_get_notebook_child(doc);
295 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
300 * Recursively searches a containers children until it finds a
301 * Scintilla widget, or NULL if one was not found.
303 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
305 ScintillaObject *sci = NULL;
306 GList *children, *iter;
308 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
310 children = gtk_container_get_children(GTK_CONTAINER(container));
311 for (iter = children; iter != NULL; iter = g_list_next(iter))
313 if (IS_SCINTILLA(iter->data))
315 sci = SCINTILLA(iter->data);
316 break;
318 else if (GTK_IS_CONTAINER(iter->data))
320 sci = locate_sci_in_container(iter->data);
321 if (IS_SCINTILLA(sci))
322 break;
323 sci = NULL;
326 g_list_free(children);
328 return sci;
332 /* Finds the document for the given notebook page widget */
333 GeanyDocument *document_get_from_notebook_child(GtkWidget *page)
335 ScintillaObject *sci;
337 g_return_val_if_fail(GTK_IS_BOX(page), NULL);
339 sci = locate_sci_in_container(page);
340 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
342 return document_find_by_sci(sci);
347 * Finds the document for the given notebook page @a page_num.
349 * @param page_num The notebook page number to search.
351 * @return @transfer{none} @nullable The corresponding document for the given notebook page, or @c NULL.
353 GEANY_API_SYMBOL
354 GeanyDocument *document_get_from_page(guint page_num)
356 GtkWidget *parent;
358 if (page_num >= documents_array->len)
359 return NULL;
361 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
363 return document_get_from_notebook_child(parent);
368 * Finds the current document.
370 * @return @transfer{none} @nullable A pointer to the current document or @c NULL if there are no opened documents.
372 GEANY_API_SYMBOL
373 GeanyDocument *document_get_current(void)
375 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
377 if (cur_page == -1)
378 return NULL;
379 else
380 return document_get_from_page((guint) cur_page);
384 void document_init_doclist(void)
386 documents_array = g_ptr_array_new();
390 void document_finalize(void)
392 guint i;
394 for (i = 0; i < documents_array->len; i++)
395 g_free(documents[i]);
396 g_ptr_array_free(documents_array, TRUE);
401 * Returns the last part of the filename of the given GeanyDocument. The result is also
402 * truncated to a maximum of @a length characters in case the filename is very long.
404 * @param doc The document to use.
405 * @param length The length of the resulting string or -1 to use a default value.
407 * @return The ellipsized last part of the filename of @a doc, should be freed when no
408 * longer needed.
410 * @since 0.17
412 /* TODO make more use of this */
413 GEANY_API_SYMBOL
414 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
416 gchar *base_name, *short_name;
418 g_return_val_if_fail(doc != NULL, NULL);
420 if (length < 0)
421 length = 30;
423 base_name = g_path_get_basename(DOC_FILENAME(doc));
424 short_name = utils_str_middle_truncate(base_name, (guint)length);
426 g_free(base_name);
428 return short_name;
432 void document_update_tab_label(GeanyDocument *doc)
434 gchar *short_name;
435 GtkWidget *parent;
437 g_return_if_fail(doc != NULL);
439 short_name = document_get_basename_for_display(doc, -1);
441 /* we need to use the event box for the tooltip, labels don't get the necessary events */
442 parent = gtk_widget_get_parent(doc->priv->tab_label);
443 parent = gtk_widget_get_parent(parent);
445 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
447 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
449 g_free(short_name);
454 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
455 * according to the document's save state.
456 * This is called by Geany mostly when opening or saving files.
458 * @param doc The document to use.
459 * @param changed Whether the document state should indicate changes have been made.
461 GEANY_API_SYMBOL
462 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
464 g_return_if_fail(doc != NULL);
466 doc->changed = changed;
468 if (! main_status.quitting)
470 ui_update_tab_status(doc);
471 ui_save_buttons_toggle(changed);
472 ui_set_window_title(doc);
473 ui_update_statusbar(doc, -1);
478 /* returns the next free place in the document list,
479 * or -1 if the documents_array is full */
480 static gint document_get_new_idx(void)
482 guint i;
484 for (i = 0; i < documents_array->len; i++)
486 if (documents[i]->editor == NULL)
488 return (gint) i;
491 return -1;
495 static void queue_colourise(GeanyDocument *doc)
497 if (doc->priv->colourise_needed)
498 return;
500 /* Colourise the editor before it is next drawn */
501 doc->priv->colourise_needed = TRUE;
503 /* If the editor doesn't need drawing (e.g. after saving the current
504 * document), we need to force a redraw, so the expose event is triggered.
505 * This ensures we don't start colourising before all documents are opened/saved,
506 * only once the editor is drawn. */
507 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
511 #ifdef USE_GIO_FILEMON
512 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
513 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
514 GeanyDocument *doc)
516 g_return_if_fail(doc != NULL);
518 if (file_prefs.disk_check_timeout == 0)
519 return;
521 geany_debug("%s: event: %d previous file status: %d",
522 G_STRFUNC, event, doc->priv->file_disk_status);
523 switch (event)
525 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
527 if (doc->priv->file_disk_status == FILE_IGNORE)
528 doc->priv->file_disk_status = FILE_OK;
529 else
530 doc->priv->file_disk_status = FILE_CHANGED;
531 g_message("%s: FILE_CHANGED", G_STRFUNC);
532 break;
534 case G_FILE_MONITOR_EVENT_DELETED:
536 doc->priv->file_disk_status = FILE_CHANGED;
537 g_message("%s: FILE_MISSING", G_STRFUNC);
538 break;
540 default:
541 break;
543 if (doc->priv->file_disk_status != FILE_OK)
545 ui_update_tab_status(doc);
548 #endif
551 static void document_stop_file_monitoring(GeanyDocument *doc)
553 g_return_if_fail(doc != NULL);
555 if (doc->priv->monitor != NULL)
557 g_object_unref(doc->priv->monitor);
558 doc->priv->monitor = NULL;
563 static void monitor_file_setup(GeanyDocument *doc)
565 g_return_if_fail(doc != NULL);
566 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
567 * doesn't work at all for remote files and legacy polling is too slow. */
568 if (! doc->priv->is_remote)
570 #ifdef USE_GIO_FILEMON
571 gchar *locale_filename;
573 /* stop any previous monitoring */
574 document_stop_file_monitoring(doc);
576 locale_filename = utils_get_locale_from_utf8(doc->file_name);
577 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
579 /* get a file monitor and connect to the 'changed' signal */
580 GFile *file = g_file_new_for_path(locale_filename);
581 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
582 g_signal_connect(doc->priv->monitor, "changed",
583 G_CALLBACK(monitor_file_changed_cb), doc);
585 /* we set the rate limit according to the GUI pref but it's most probably not used */
586 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
588 g_object_unref(file);
590 g_free(locale_filename);
591 #endif
593 doc->priv->file_disk_status = FILE_OK;
597 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
599 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
600 if (DOC_VALID(doc))
602 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
603 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
605 if (source_widget == NULL)
606 source_widget = doc->priv->tag_tree;
608 if (focusw == source_widget)
609 gtk_widget_grab_focus(sci);
614 static gboolean on_idle_focus(gpointer doc)
616 document_try_focus(doc, NULL);
617 return FALSE;
621 /* Creates a new document and editor, adding a tab in the notebook.
622 * @return The created document */
623 static GeanyDocument *document_create(const gchar *utf8_filename)
625 GeanyDocument *doc;
626 gint new_idx;
627 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
629 if (cur_pages == 1)
631 doc = document_get_current();
632 /* remove the empty document first */
633 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
634 /* prevent immediately opening another new doc with
635 * new_document_after_close pref */
636 remove_page(0);
639 new_idx = document_get_new_idx();
640 if (new_idx == -1) /* expand the array, no free places */
642 doc = g_new0(GeanyDocument, 1);
644 new_idx = documents_array->len;
645 g_ptr_array_add(documents_array, doc);
648 doc = documents[new_idx];
650 /* initialize default document settings */
651 doc->priv = g_new0(GeanyDocumentPrivate, 1);
652 doc->id = ++doc_id_counter;
653 doc->index = new_idx;
654 doc->file_name = g_strdup(utf8_filename);
655 doc->editor = editor_create(doc);
656 #ifndef USE_GIO_FILEMON
657 doc->priv->last_check = time(NULL);
658 #endif
660 sidebar_openfiles_add(doc); /* sets doc->iter */
662 notebook_new_tab(doc);
664 /* select document in sidebar */
666 GtkTreeSelection *sel;
668 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
669 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
672 ui_document_buttons_update();
674 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
675 return doc;
680 * Closes the given document.
682 * @param doc The document to remove.
684 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
686 * @since 0.15
688 GEANY_API_SYMBOL
689 gboolean document_close(GeanyDocument *doc)
691 g_return_val_if_fail(doc, FALSE);
693 return document_remove_page(document_get_notebook_page(doc));
697 /* Call document_remove_page() instead, this is only needed for document_create()
698 * to prevent re-opening a new document when the last document is closed (if enabled). */
699 static gboolean remove_page(guint page_num)
701 GeanyDocument *doc = document_get_from_page(page_num);
703 g_return_val_if_fail(doc != NULL, FALSE);
705 if (doc->changed && ! dialogs_show_unsaved_file(doc))
706 return FALSE;
708 /* tell any plugins that the document is about to be closed */
709 g_signal_emit_by_name(geany_object, "document-close", doc);
711 /* Checking real_path makes it likely the file exists on disk */
712 if (! main_status.closing_all && doc->real_path != NULL)
713 ui_add_recent_document(doc);
715 doc->is_valid = FALSE;
716 doc->id = 0;
718 if (main_status.quitting)
720 /* we need to destroy the ScintillaWidget so our handlers on it are
721 * disconnected before we free any data they may use (like the editor).
722 * when not quitting, this is handled by removing the notebook page. */
723 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
725 else
727 notebook_remove_page(page_num);
728 sidebar_remove_document(doc);
729 navqueue_remove_file(doc->file_name);
730 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
732 g_free(doc->encoding);
733 g_free(doc->priv->saved_encoding.encoding);
734 g_free(doc->file_name);
735 g_free(doc->real_path);
736 if (doc->tm_file)
738 tm_workspace_remove_source_file(doc->tm_file);
739 tm_source_file_free(doc->tm_file);
742 if (doc->priv->tag_tree)
743 gtk_widget_destroy(doc->priv->tag_tree);
745 editor_destroy(doc->editor);
746 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
748 document_stop_file_monitoring(doc);
750 document_undo_clear(doc);
752 g_free(doc->priv);
754 /* reset document settings to defaults for re-use */
755 memset(doc, 0, sizeof(GeanyDocument));
757 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
759 sidebar_update_tag_list(NULL, FALSE);
760 ui_set_window_title(NULL);
761 ui_save_buttons_toggle(FALSE);
762 ui_update_popup_reundo_items(NULL);
763 ui_document_buttons_update();
764 build_menu_update(NULL);
766 return TRUE;
771 * Removes the given notebook tab at @a page_num and clears all related information
772 * in the document list.
774 * @param page_num The notebook page number to remove.
776 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
778 GEANY_API_SYMBOL
779 gboolean document_remove_page(guint page_num)
781 gboolean done = remove_page(page_num);
783 if (done && ui_prefs.new_document_after_close)
784 document_new_file_if_non_open();
786 return done;
790 /* used to keep a record of the unchanged document state encoding */
791 static void store_saved_encoding(GeanyDocument *doc)
793 g_free(doc->priv->saved_encoding.encoding);
794 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
795 doc->priv->saved_encoding.has_bom = doc->has_bom;
799 /* Opens a new empty document only if there are no other documents open */
800 GeanyDocument *document_new_file_if_non_open(void)
802 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
803 return document_new_file(NULL, NULL, NULL);
805 return NULL;
810 * Creates a new document.
811 * Line endings in @a text will be converted to the default setting.
812 * Afterwards, the @c "document-new" signal is emitted for plugins.
814 * @param utf8_filename @nullable The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
815 * @param ft @nullable The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
816 * @param text @nullable The initial content of the file (in UTF-8 encoding), or @c NULL.
818 * @return @transfer{none} The new document.
820 GEANY_API_SYMBOL
821 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
823 GeanyDocument *doc;
825 if (utf8_filename && g_path_is_absolute(utf8_filename))
827 gchar *tmp;
828 tmp = utils_strdupa(utf8_filename); /* work around const */
829 utils_tidy_path(tmp);
830 utf8_filename = tmp;
832 doc = document_create(utf8_filename);
834 g_assert(doc != NULL);
836 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
837 if (text)
839 GString *template = g_string_new(text);
840 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
842 sci_set_text(doc->editor->sci, template->str);
843 g_string_free(template, TRUE);
845 else
846 sci_clear_all(doc->editor->sci);
848 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
850 sci_set_undo_collection(doc->editor->sci, TRUE);
851 sci_empty_undo_buffer(doc->editor->sci);
853 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
854 /* store the opened encoding for undo/redo */
855 store_saved_encoding(doc);
857 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
858 ft = filetypes_detect_from_document(doc);
860 document_set_filetype(doc, ft); /* also re-parses tags */
862 /* now the document is fully ready, display it (see notebook_new_tab()) */
863 gtk_widget_show(document_get_notebook_child(doc));
865 ui_set_window_title(doc);
866 build_menu_update(doc);
867 document_set_text_changed(doc, FALSE);
868 ui_document_show_hide(doc); /* update the document menu */
870 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
871 /* bring it in front, jump to the start and grab the focus */
872 editor_goto_pos(doc->editor, 0, FALSE);
873 document_try_focus(doc, NULL);
875 #ifdef USE_GIO_FILEMON
876 monitor_file_setup(doc);
877 #else
878 doc->priv->mtime = 0;
879 #endif
881 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
882 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
884 g_signal_emit_by_name(geany_object, "document-new", doc);
886 msgwin_status_add(_("New file \"%s\" opened."),
887 DOC_FILENAME(doc));
889 return doc;
894 * Opens a document specified by @a locale_filename.
895 * Afterwards, the @c "document-open" signal is emitted for plugins.
897 * @param locale_filename The filename of the document to load, in locale encoding.
898 * @param readonly Whether to open the document in read-only mode.
899 * @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
900 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
902 * @return @transfer{none} @nullable The document opened or @c NULL.
904 GEANY_API_SYMBOL
905 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
906 GeanyFiletype *ft, const gchar *forced_enc)
908 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
912 typedef struct
914 gchar *data; /* null-terminated file data */
915 gsize len; /* string length of data */
916 gchar *enc;
917 gboolean bom;
918 time_t mtime; /* modification time, read by stat::st_mtime */
919 gboolean readonly;
920 } FileData;
923 static gboolean get_mtime(const gchar *locale_filename, time_t *time)
925 GError *error = NULL;
926 const gchar *err_msg = NULL;
928 if (USE_GIO_FILE_OPERATIONS)
930 GFile *file = g_file_new_for_path(locale_filename);
931 GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, NULL, &error);
933 if (info)
935 GTimeVal timeval;
937 g_file_info_get_modification_time(info, &timeval);
938 g_object_unref(info);
939 *time = timeval.tv_sec;
941 else if (error)
942 err_msg = error->message;
944 g_object_unref(file);
946 else
948 GStatBuf st;
950 if (g_stat(locale_filename, &st) == 0)
951 *time = st.st_mtime;
952 else
953 err_msg = g_strerror(errno);
956 if (err_msg)
958 gchar *utf8_filename = utils_get_utf8_from_locale(locale_filename);
960 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
961 utf8_filename, err_msg);
962 g_free(utf8_filename);
965 if (error)
966 g_error_free(error);
968 return err_msg == NULL;
972 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
973 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
974 FileData *filedata, const gchar *forced_enc)
976 GError *err = NULL;
978 filedata->data = NULL;
979 filedata->len = 0;
980 filedata->enc = NULL;
981 filedata->bom = FALSE;
982 filedata->readonly = FALSE;
984 if (!get_mtime(locale_filename, &filedata->mtime))
985 return FALSE;
987 if (USE_GIO_FILE_OPERATIONS)
989 GFile *file = g_file_new_for_path(locale_filename);
991 g_file_load_contents(file, NULL, &filedata->data, &filedata->len, NULL, &err);
992 g_object_unref(file);
994 else
995 g_file_get_contents(locale_filename, &filedata->data, &filedata->len, &err);
997 if (err)
999 ui_set_statusbar(TRUE, "%s", err->message);
1000 g_error_free(err);
1001 return FALSE;
1004 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
1005 &filedata->enc, &filedata->bom, &filedata->readonly))
1007 if (forced_enc)
1009 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
1010 display_filename, forced_enc);
1012 else
1014 ui_set_statusbar(TRUE,
1015 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1016 display_filename);
1018 g_free(filedata->data);
1019 return FALSE;
1022 if (filedata->readonly)
1024 const gchar *warn_msg = _(
1025 "The file \"%s\" could not be opened properly and has been truncated. " \
1026 "This can occur if the file contains a NULL byte. " \
1027 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1029 if (main_status.main_window_realized)
1030 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
1032 ui_set_statusbar(TRUE, warn_msg, display_filename);
1035 return TRUE;
1039 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1040 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1041 * if cl_options.goto_column is set.
1043 * returns the new position which may have changed */
1044 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1046 if (cl_options.goto_line >= 0)
1047 { /* goto line which was specified on command line and then undefine the line */
1048 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1049 editor->scroll_percent = 0.5F;
1050 cl_options.goto_line = -1;
1052 else if (pos > 0)
1054 sci_set_current_position(editor->sci, pos, FALSE);
1055 editor->scroll_percent = 0.5F;
1058 if (cl_options.goto_column >= 0)
1059 { /* goto column which was specified on command line and then undefine the column */
1061 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1062 sci_set_current_position(editor->sci, new_pos, FALSE);
1063 editor->scroll_percent = 0.5F;
1064 cl_options.goto_column = -1;
1065 return new_pos;
1067 return sci_get_current_position(editor->sci);
1071 /* Count lines that start with some hard tabs then a soft tab. */
1072 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1074 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1075 ScintillaObject *sci = editor->sci;
1076 gsize count = 0;
1077 struct Sci_TextToFind ttf;
1078 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
1079 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1081 g_free(soft_tab);
1083 ttf.chrg.cpMin = 0;
1084 ttf.chrg.cpMax = sci_get_length(sci);
1085 ttf.lpstrText = regex;
1086 while (1)
1088 gint pos;
1090 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1091 if (pos == -1)
1092 break; /* no more matches */
1093 count++;
1094 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1096 g_free(regex);
1097 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1098 return count > sci_get_line_count(sci) * 0.02;
1102 /* Detect the indent type based on counting the leading indent characters for each line.
1103 * Returns whether detection succeeded, and the detected type in *type_ upon success */
1104 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
1106 GeanyEditor *editor = doc->editor;
1107 ScintillaObject *sci = editor->sci;
1108 gint line, line_count;
1109 gsize tabs = 0, spaces = 0;
1111 if (detect_tabs_and_spaces(editor))
1113 *type_ = GEANY_INDENT_TYPE_BOTH;
1114 return TRUE;
1117 line_count = sci_get_line_count(sci);
1118 for (line = 0; line < line_count; line++)
1120 gint pos = sci_get_position_from_line(sci, line);
1121 gchar c;
1123 /* most code will have indent total <= 24, otherwise it's more likely to be
1124 * alignment than indentation */
1125 if (sci_get_line_indentation(sci, line) > 24)
1126 continue;
1128 c = sci_get_char_at(sci, pos);
1129 if (c == '\t')
1130 tabs++;
1131 /* check for at least 2 spaces */
1132 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1133 spaces++;
1135 if (spaces == 0 && tabs == 0)
1136 return FALSE;
1138 /* the factors may need to be tweaked */
1139 if (spaces > tabs * 4)
1140 *type_ = GEANY_INDENT_TYPE_SPACES;
1141 else if (tabs > spaces * 4)
1142 *type_ = GEANY_INDENT_TYPE_TABS;
1143 else
1144 *type_ = GEANY_INDENT_TYPE_BOTH;
1146 return TRUE;
1150 /* Detect the indent width based on counting the leading indent characters for each line.
1151 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1152 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1154 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1155 ScintillaObject *sci = editor->sci;
1156 gint line, line_count;
1157 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1158 gint count, width, i;
1160 /* can't easily detect the supposed width of a tab, guess the default is OK */
1161 if (type == GEANY_INDENT_TYPE_TABS)
1162 return FALSE;
1164 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1165 sci_set_tab_width(sci, 8);
1167 line_count = sci_get_line_count(sci);
1168 for (line = 0; line < line_count; line++)
1170 gint pos = sci_get_line_indent_position(sci, line);
1172 /* We probably don't have style info yet, because we're generally called just after
1173 * the document got created, so we can't use highlighting_is_code_style().
1174 * That's not good, but the assumption below that concerning lines start with an
1175 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1176 * without removing too much legitimate lines. */
1177 if (sci_get_char_at(sci, pos) == '*')
1178 continue;
1180 width = sci_get_line_indentation(sci, line);
1181 /* most code will have indent total <= 24, otherwise it's more likely to be
1182 * alignment than indentation */
1183 if (width > 24)
1184 continue;
1185 /* < 2 is no indentation */
1186 if (width < 2)
1187 continue;
1189 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1191 if ((width % (i + 2)) == 0)
1192 widths[i]++;
1195 count = 0;
1196 width = iprefs->width;
1197 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1199 /* give large indents higher weight not to be fooled by spurious indents */
1200 if (widths[i] >= count * 1.5)
1202 width = i + 2;
1203 count = widths[i];
1207 if (count == 0)
1208 return FALSE;
1210 *width_ = width;
1211 return TRUE;
1215 /* same as detect_indent_width() but uses editor's indent type */
1216 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1218 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1222 void document_apply_indent_settings(GeanyDocument *doc)
1224 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1225 GeanyIndentType type = iprefs->type;
1226 gint width = iprefs->width;
1228 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1230 if (type != iprefs->type)
1232 const gchar *name = NULL;
1234 switch (type)
1236 case GEANY_INDENT_TYPE_SPACES:
1237 name = _("Spaces");
1238 break;
1239 case GEANY_INDENT_TYPE_TABS:
1240 name = _("Tabs");
1241 break;
1242 case GEANY_INDENT_TYPE_BOTH:
1243 name = _("Tabs and Spaces");
1244 break;
1246 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1247 * and Spaces), the second one is the filename */
1248 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1249 DOC_FILENAME(doc));
1252 else if (doc->file_type->indent_type > -1)
1253 type = doc->file_type->indent_type;
1255 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1257 if (width != iprefs->width)
1259 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1260 DOC_FILENAME(doc));
1263 else if (doc->file_type->indent_width > -1)
1264 width = doc->file_type->indent_width;
1266 editor_set_indent(doc->editor, type, width);
1270 void document_show_tab(GeanyDocument *doc)
1272 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1273 document_get_notebook_page(doc));
1277 /* To open a new file, set doc to NULL; filename should be locale encoded.
1278 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1279 * pos is the cursor position, which can be overridden by --line and --column.
1280 * forced_enc can be NULL to detect the file encoding.
1281 * Returns: doc of the opened file or NULL if an error occurred. */
1282 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1283 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1285 gint editor_mode;
1286 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1287 gchar *utf8_filename = NULL;
1288 gchar *display_filename = NULL;
1289 gchar *locale_filename = NULL;
1290 GeanyFiletype *use_ft;
1291 FileData filedata;
1292 UndoReloadData *undo_reload_data;
1293 gboolean add_undo_reload_action;
1295 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1297 if (reload)
1299 utf8_filename = g_strdup(doc->file_name);
1300 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1302 else
1304 /* filename must not be NULL when opening a file */
1305 g_return_val_if_fail(filename, NULL);
1307 #ifdef G_OS_WIN32
1308 /* if filename is a shortcut, try to resolve it */
1309 locale_filename = win32_get_shortcut_target(filename);
1310 #else
1311 locale_filename = g_strdup(filename);
1312 #endif
1313 /* remove relative junk */
1314 utils_tidy_path(locale_filename);
1316 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1317 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1319 /* if file is already open, switch to it and go */
1320 doc = document_find_by_filename(utf8_filename);
1321 if (doc != NULL)
1323 ui_add_recent_document(doc); /* either add or reorder recent item */
1324 /* show the doc before reload dialog */
1325 document_show_tab(doc);
1326 document_check_disk_status(doc, TRUE); /* force a file changed check */
1329 if (reload || doc == NULL)
1330 { /* doc possibly changed */
1331 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1333 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1335 g_free(display_filename);
1336 g_free(utf8_filename);
1337 g_free(locale_filename);
1338 return NULL;
1341 if (! reload)
1343 doc = document_create(utf8_filename);
1344 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1346 /* file exists on disk, set real_path */
1347 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1349 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1350 monitor_file_setup(doc);
1353 if (! reload || ! file_prefs.keep_edit_history_on_reload)
1355 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1356 sci_empty_undo_buffer(doc->editor->sci);
1357 undo_reload_data = NULL;
1359 else
1361 undo_reload_data = (UndoReloadData*) g_malloc(sizeof(UndoReloadData));
1363 /* We will be adding a UNDO_RELOAD action to the undo stack that undoes
1364 * this reload. To do that, we keep collecting undo actions during
1365 * reloading, and at the end add an UNDO_RELOAD action that performs
1366 * all these actions in bulk. To keep track of how many undo actions
1367 * were added during this time, we compare the current undo-stack height
1368 * with its height at the end of the process. Note that g_trash_stack_height()
1369 * is O(N), which is a little ugly, but this seems like the most maintainable
1370 * option. */
1371 undo_reload_data->actions_count = g_trash_stack_height(&doc->priv->undo_actions);
1373 /* We use add_undo_reload_action to track any changes to the document that
1374 * require adding an undo action to revert the reload, but that do not
1375 * generate an undo action themselves. */
1376 add_undo_reload_action = FALSE;
1379 /* add the text to the ScintillaObject */
1380 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1381 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1382 queue_colourise(doc); /* Ensure the document gets colourised. */
1384 /* detect & set line endings */
1385 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1386 if (undo_reload_data)
1388 undo_reload_data->eol_mode = editor_get_eol_char_mode(doc->editor);
1389 /* Force adding an undo-reload action if the EOL mode changed. */
1390 if (editor_mode != undo_reload_data->eol_mode)
1391 add_undo_reload_action = TRUE;
1393 sci_set_eol_mode(doc->editor->sci, editor_mode);
1394 g_free(filedata.data);
1396 sci_set_undo_collection(doc->editor->sci, TRUE);
1398 /* If reloading and the current and new encodings or BOM states differ,
1399 * add appropriate undo actions. */
1400 if (undo_reload_data)
1402 if (! utils_str_equal(doc->encoding, filedata.enc))
1403 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
1404 if (doc->has_bom != filedata.bom)
1405 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
1408 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1409 g_free(doc->encoding); /* if reloading, free old encoding */
1410 doc->encoding = filedata.enc;
1411 doc->has_bom = filedata.bom;
1412 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1414 doc->readonly = readonly || filedata.readonly;
1415 sci_set_readonly(doc->editor->sci, doc->readonly);
1416 doc->priv->protected = 0;
1418 /* update line number margin width */
1419 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1420 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1422 if (! reload)
1425 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1426 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1427 doc->editor);
1429 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1431 else
1432 { /* reloading */
1433 if (undo_reload_data)
1435 /* Calculate the number of undo actions that are part of the reloading
1436 * process, and add the UNDO_RELOAD action. */
1437 undo_reload_data->actions_count =
1438 g_trash_stack_height(&doc->priv->undo_actions) - undo_reload_data->actions_count;
1440 /* We only add an undo-reload action if the document has actually changed.
1441 * At the time of writing, this condition is moot because sci_set_text
1442 * generates an undo action even when the text hasn't really changed, so
1443 * actions_count is always greater than zero. In the future this might change.
1444 * It's arguable whether we should add an undo-reload action unconditionally,
1445 * especially since it's possible (if unlikely) that there had only
1446 * been "invisible" changes to the document, such as changes in encoding and
1447 * EOL mode, but for the time being that's how we roll. */
1448 if (undo_reload_data->actions_count > 0 || add_undo_reload_action)
1449 document_undo_add(doc, UNDO_RELOAD, undo_reload_data);
1450 else
1451 g_free(undo_reload_data);
1453 /* We didn't save the document per-se, but its contents are now
1454 * synchronized with the file on disk, hence set a save point here.
1455 * We need to do this in this case only, because we don't clear
1456 * Scintilla's undo stack. */
1457 sci_set_savepoint(doc->editor->sci);
1459 else
1460 document_undo_clear(doc);
1462 use_ft = ft;
1464 /* update taglist, typedef keywords and build menu if necessary */
1465 document_set_filetype(doc, use_ft);
1467 /* set indentation settings after setting the filetype */
1468 if (reload)
1469 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1470 else
1471 document_apply_indent_settings(doc);
1473 document_set_text_changed(doc, FALSE); /* also updates tab state */
1474 ui_document_show_hide(doc); /* update the document menu */
1476 /* finally add current file to recent files menu, but not the files from the last session */
1477 if (! main_status.opening_session_files)
1478 ui_add_recent_document(doc);
1480 if (reload)
1482 g_signal_emit_by_name(geany_object, "document-reload", doc);
1483 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1485 else
1487 g_signal_emit_by_name(geany_object, "document-open", doc);
1488 /* For translators: this is the status window message for opening a file. %d is the number
1489 * of the newly opened file, %s indicates whether the file is opened read-only
1490 * (it is replaced with the string ", read-only"). */
1491 msgwin_status_add(_("File %s opened(%d%s)."),
1492 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1493 (readonly) ? _(", read-only") : "");
1496 /* now the document is fully ready, display it (see notebook_new_tab()) */
1497 gtk_widget_show(document_get_notebook_child(doc));
1500 g_free(display_filename);
1501 g_free(utf8_filename);
1502 g_free(locale_filename);
1504 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1505 pos = set_cursor_position(doc->editor, pos);
1506 /* now bring the file in front */
1507 editor_goto_pos(doc->editor, pos, FALSE);
1509 /* finally, let the editor widget grab the focus so you can start coding
1510 * right away */
1511 g_idle_add(on_idle_focus, doc);
1512 return doc;
1516 /* Takes a new line separated list of filename URIs and opens each file.
1517 * length is the length of the string */
1518 void document_open_file_list(const gchar *data, gsize length)
1520 guint i;
1521 gchar **list;
1523 g_return_if_fail(data != NULL);
1525 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1527 /* stop at the end or first empty item, because last item is empty but not null */
1528 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1530 gchar *filename = utils_get_path_from_uri(list[i]);
1532 if (filename == NULL)
1533 continue;
1534 document_open_file(filename, FALSE, NULL, NULL);
1535 g_free(filename);
1538 g_strfreev(list);
1543 * Opens each file in the list @a filenames.
1544 * Internally, document_open_file() is called for every list item.
1546 * @param filenames @elementtype{filename} A list of filenames to load, in locale encoding.
1547 * @param readonly Whether to open the document in read-only mode.
1548 * @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
1549 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1551 GEANY_API_SYMBOL
1552 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1553 const gchar *forced_enc)
1555 const GSList *item;
1557 for (item = filenames; item != NULL; item = g_slist_next(item))
1559 document_open_file(item->data, readonly, ft, forced_enc);
1564 static void on_keep_edit_history_on_reload_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
1566 if (response_id == GTK_RESPONSE_NO)
1568 file_prefs.keep_edit_history_on_reload = FALSE;
1569 document_reload_force(doc, doc->encoding);
1571 else if (response_id == GTK_RESPONSE_CANCEL)
1573 /* this condition cannot be reached via info bar buttons, but by our code
1574 * to replace this bar with a higher priority one */
1575 file_prefs.show_keep_edit_history_on_reload_msg = TRUE;
1577 doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = NULL;
1578 gtk_widget_destroy(bar);
1583 * Reloads the document with the specified file encoding.
1584 * @a forced_enc or @c NULL to auto-detect the file encoding.
1586 * @param doc The document to reload.
1587 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1589 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1591 GEANY_API_SYMBOL
1592 gboolean document_reload_force(GeanyDocument *doc, const gchar *forced_enc)
1594 gint pos = 0;
1595 GeanyDocument *new_doc;
1596 GtkWidget *bar;
1598 g_return_val_if_fail(doc != NULL, FALSE);
1600 /* Use cancel because the response handler would call this recursively */
1601 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1602 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1604 /* try to set the cursor to the position before reloading */
1605 pos = sci_get_current_position(doc->editor->sci);
1606 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1608 if (file_prefs.keep_edit_history_on_reload && file_prefs.show_keep_edit_history_on_reload_msg)
1610 bar = document_show_message(doc, GTK_MESSAGE_INFO,
1611 on_keep_edit_history_on_reload_response,
1612 GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1613 _("Discard history"), GTK_RESPONSE_NO,
1614 NULL, 0, _("The buffer's previous state is stored in the history and "
1615 "undoing restores it. You can disable this by discarding the history upon "
1616 "reload. This message will not be displayed again but "
1617 "Your choice can be changed in the various preferences."),
1618 _("The file has been reloaded."));
1619 doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = bar;
1620 file_prefs.show_keep_edit_history_on_reload_msg = FALSE;
1623 return (new_doc != NULL);
1627 /* also used for reloading when forced_enc is NULL */
1628 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1630 gchar *base_name;
1631 gboolean prompt, result = FALSE;
1633 g_return_val_if_fail(doc != NULL, FALSE);
1635 /* No need to reload "untitled" (non-file-backed) documents */
1636 if (doc->file_name == NULL)
1637 return FALSE;
1639 if (forced_enc == NULL)
1640 forced_enc = doc->encoding;
1642 base_name = g_path_get_basename(doc->file_name);
1643 /* don't prompt if edit history is maintained, or if file hasn't been edited at all */
1644 prompt = !file_prefs.keep_edit_history_on_reload &&
1645 (doc->changed || (document_can_undo(doc) || document_can_redo(doc)));
1647 if (!prompt || dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1648 doc->changed ? _("Any unsaved changes will be lost.") :
1649 _("Undo history will be lost."),
1650 _("Are you sure you want to reload '%s'?"), base_name))
1652 result = document_reload_force(doc, forced_enc);
1653 if (forced_enc != NULL)
1654 ui_update_statusbar(doc, -1);
1656 g_free(base_name);
1657 return result;
1661 static void document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1663 #ifndef USE_GIO_FILEMON
1664 g_return_if_fail(doc != NULL);
1666 get_mtime(locale_filename, &doc->priv->mtime); /* get the modification time from file and keep it */
1667 #endif
1671 /* Sets line and column to the given position byte_pos in the document.
1672 * byte_pos is the position counted in bytes, not characters */
1673 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1675 gint i;
1676 gint line_start;
1678 /* for some reason we can use byte count instead of character count here */
1679 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1680 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1681 /* get the column in the line */
1682 *column = byte_pos - line_start;
1684 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1685 * skip one byte(i++) and decrease the column number which is based on byte count */
1686 for (i = line_start; i < (line_start + *column); i++)
1688 if (sci_get_char_at(doc->editor->sci, i) < 0)
1690 (*column)--;
1691 i++;
1697 static void replace_header_filename(GeanyDocument *doc)
1699 gchar *filebase;
1700 gchar *filename;
1701 struct Sci_TextToFind ttf;
1703 g_return_if_fail(doc != NULL);
1704 g_return_if_fail(doc->file_type != NULL);
1706 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1707 if (doc->file_type->extension)
1708 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1709 else
1710 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1712 filename = g_path_get_basename(doc->file_name);
1714 /* only search the first 3 lines */
1715 ttf.chrg.cpMin = 0;
1716 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1717 ttf.lpstrText = filebase;
1719 if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1721 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1722 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1723 sci_replace_target(doc->editor->sci, filename, FALSE);
1725 g_free(filebase);
1726 g_free(filename);
1731 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1732 * you still have to call @ref document_save_file_as() to change the @a doc object.
1733 * It also stops monitoring for file changes to prevent receiving too many file change events
1734 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1736 * @param doc The current document which should be renamed.
1737 * @param new_filename The new filename in UTF-8 encoding.
1739 * @since 0.16
1741 GEANY_API_SYMBOL
1742 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1744 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1745 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1746 gint result;
1748 /* stop file monitoring to avoid getting events for deleting/creating files,
1749 * it's re-setup in document_save_file_as() */
1750 document_stop_file_monitoring(doc);
1752 result = g_rename(old_locale_filename, new_locale_filename);
1753 if (result != 0)
1755 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1756 _("Error renaming file."), g_strerror(errno));
1758 g_free(old_locale_filename);
1759 g_free(new_locale_filename);
1763 static void protect_document(GeanyDocument *doc)
1765 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1766 if (!doc->priv->protected++)
1767 sci_set_readonly(doc->editor->sci, TRUE);
1769 ui_update_tab_status(doc);
1773 static void unprotect_document(GeanyDocument *doc)
1775 g_return_if_fail(doc->priv->protected > 0);
1777 if (!--doc->priv->protected && doc->readonly == FALSE)
1778 sci_set_readonly(doc->editor->sci, FALSE);
1780 ui_update_tab_status(doc);
1784 /* Return TRUE if the document doesn't have a full filename set.
1785 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1786 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1787 * new files. */
1788 gboolean document_need_save_as(GeanyDocument *doc)
1790 g_return_val_if_fail(doc != NULL, FALSE);
1792 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1797 * Saves the document, detecting the filetype.
1799 * @param doc The document for the file to save.
1800 * @param utf8_fname @nullable The new name for the document, in UTF-8, or @c NULL.
1801 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1803 * @see document_save_file().
1805 * @since 0.16
1807 GEANY_API_SYMBOL
1808 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1810 gboolean ret;
1811 gboolean new_file;
1813 g_return_val_if_fail(doc != NULL, FALSE);
1815 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1816 if (utf8_fname != NULL)
1817 SETPTR(doc->file_name, g_strdup(utf8_fname));
1819 /* reset real path, it's retrieved again in document_save() */
1820 SETPTR(doc->real_path, NULL);
1822 /* detect filetype */
1823 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1825 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1827 document_set_filetype(doc, ft);
1828 if (document_get_current() == doc)
1830 ignore_callback = TRUE;
1831 filetypes_select_radio_item(doc->file_type);
1832 ignore_callback = FALSE;
1836 if (new_file)
1838 // assume user wants to throw away read-only setting
1839 sci_set_readonly(doc->editor->sci, FALSE);
1840 doc->readonly = FALSE;
1841 if (doc->priv->protected > 0)
1842 unprotect_document(doc);
1845 replace_header_filename(doc);
1847 ret = document_save_file(doc, TRUE);
1849 /* file monitoring support, add file monitoring after the file has been saved
1850 * to ignore any earlier events */
1851 monitor_file_setup(doc);
1852 doc->priv->file_disk_status = FILE_IGNORE;
1854 if (ret)
1855 ui_add_recent_document(doc);
1856 return ret;
1860 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1862 GError *conv_error = NULL;
1863 gchar* conv_file_contents = NULL;
1864 gsize bytes_read;
1865 gsize conv_len;
1867 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1868 g_return_val_if_fail(len != NULL, FALSE);
1870 /* try to convert it from UTF-8 to original encoding */
1871 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1872 &bytes_read, &conv_len, &conv_error);
1874 if (conv_error != NULL)
1876 gchar *text = g_strdup_printf(
1877 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1878 doc->encoding);
1879 gchar *error_text;
1881 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1883 gint line, column;
1884 gint context_len;
1885 gunichar unic;
1886 /* don't read over the doc length */
1887 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1888 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1889 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1891 /* take only one valid Unicode character from the context and discard the leftover */
1892 unic = g_utf8_get_char_validated(context, -1);
1893 context_len = g_unichar_to_utf8(unic, context);
1894 context[context_len] = '\0';
1895 get_line_column_from_pos(doc, bytes_read, &line, &column);
1897 error_text = g_strdup_printf(
1898 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1899 conv_error->message, context, line + 1, column);
1901 else
1902 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1904 geany_debug("encoding error: %s", conv_error->message);
1905 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1906 g_error_free(conv_error);
1907 g_free(text);
1908 g_free(error_text);
1909 return FALSE;
1911 else
1913 g_free(*data);
1914 *data = conv_file_contents;
1915 *len = conv_len;
1917 return TRUE;
1921 static gchar *write_data_to_disk(const gchar *locale_filename,
1922 const gchar *data, gsize len)
1924 GError *error = NULL;
1926 if (file_prefs.use_safe_file_saving)
1928 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1929 * This is the only option that handles disk space exhaustion. */
1930 if (g_file_set_contents(locale_filename, data, len, &error))
1931 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1933 else if (USE_GIO_FILE_OPERATIONS)
1935 GFile *fp;
1937 /* Use GIO API to save file (GVFS-safe)
1938 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1939 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1940 fp = g_file_new_for_path(locale_filename);
1941 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1942 G_FILE_CREATE_NONE, NULL, NULL, &error);
1943 g_object_unref(fp);
1945 else
1947 FILE *fp;
1948 int save_errno;
1949 gchar *display_name = g_filename_display_name(locale_filename);
1951 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1952 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1953 errno = 0;
1954 fp = g_fopen(locale_filename, "wb");
1955 if (fp == NULL)
1957 save_errno = errno;
1959 g_set_error(&error,
1960 G_FILE_ERROR,
1961 g_file_error_from_errno(save_errno),
1962 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1963 display_name,
1964 g_strerror(save_errno));
1966 else
1968 gsize bytes_written;
1970 errno = 0;
1971 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1973 if (len != bytes_written)
1975 save_errno = errno;
1977 g_set_error(&error,
1978 G_FILE_ERROR,
1979 g_file_error_from_errno(save_errno),
1980 _("Failed to write file '%s': fwrite() failed: %s"),
1981 display_name,
1982 g_strerror(save_errno));
1985 errno = 0;
1986 /* preserve the fwrite() error if any */
1987 if (fclose(fp) != 0 && error == NULL)
1989 save_errno = errno;
1991 g_set_error(&error,
1992 G_FILE_ERROR,
1993 g_file_error_from_errno(save_errno),
1994 _("Failed to close file '%s': fclose() failed: %s"),
1995 display_name,
1996 g_strerror(save_errno));
2000 g_free(display_name);
2002 if (error != NULL)
2004 gchar *msg = g_strdup(error->message);
2005 g_error_free(error);
2006 /* geany will warn about file truncation for unsafe saving below */
2007 return msg;
2009 return NULL;
2013 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
2014 const gchar *data, gsize len)
2016 gchar *err;
2018 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
2019 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
2021 err = write_data_to_disk(locale_filename, data, len);
2022 if (err)
2023 return err;
2025 /* now the file is on disk, set real_path */
2026 if (doc->real_path == NULL)
2028 doc->real_path = tm_get_real_path(locale_filename);
2029 doc->priv->is_remote = utils_is_remote_path(locale_filename);
2030 monitor_file_setup(doc);
2032 return NULL;
2036 static gboolean save_file_handle_infobars(GeanyDocument *doc, gboolean force)
2038 GtkWidget *bar = NULL;
2040 document_show_tab(doc);
2042 if (doc->priv->info_bars[MSG_TYPE_RELOAD])
2044 if (!dialogs_show_question_full(NULL, _("_Overwrite"), GTK_STOCK_CANCEL,
2045 _("Overwrite?"),
2046 _("The file '%s' on the disk is more recent than the current buffer."),
2047 doc->file_name))
2048 return FALSE;
2049 bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
2051 else if (doc->priv->info_bars[MSG_TYPE_RESAVE])
2053 if (!dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
2054 _("Try to resave the file?"),
2055 _("File \"%s\" was not found on disk!"),
2056 doc->file_name))
2057 return FALSE;
2058 bar = doc->priv->info_bars[MSG_TYPE_RESAVE];
2060 else
2062 g_assert_not_reached();
2063 return FALSE;
2065 gtk_info_bar_response(GTK_INFO_BAR(bar), RESPONSE_DOCUMENT_SAVE);
2066 return TRUE;
2071 * Saves the document.
2072 * Also shows the Save As dialog if necessary.
2073 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
2075 * Saving may include replacing tabs with spaces,
2076 * stripping trailing spaces and adding a final new line at the end of the file, depending
2077 * on user preferences. Then the @c "document-before-save" signal is emitted,
2078 * allowing plugins to modify the document before it is saved, and data is
2079 * actually written to disk.
2081 * On successful saving:
2082 * - GeanyDocument::real_path is set.
2083 * - The filetype is set again or auto-detected if it wasn't set yet.
2084 * - The @c "document-save" signal is emitted for plugins.
2086 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
2087 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
2088 * added in Geany 1.22.
2090 * @param doc The document to save.
2091 * @param force Whether to save the file even if it is not modified.
2093 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
2095 GEANY_API_SYMBOL
2096 gboolean document_save_file(GeanyDocument *doc, gboolean force)
2098 gchar *errmsg;
2099 gchar *data;
2100 gsize len;
2101 gchar *locale_filename;
2102 const GeanyFilePrefs *fp;
2104 g_return_val_if_fail(doc != NULL, FALSE);
2106 if (document_need_save_as(doc))
2108 /* ensure doc is the current tab before showing the dialog */
2109 document_show_tab(doc);
2110 return dialogs_show_save_as();
2113 if (!force && !doc->changed)
2114 return FALSE;
2115 if (doc->readonly)
2117 ui_set_statusbar(TRUE,
2118 _("Cannot save read-only document '%s'!"), DOC_FILENAME(doc));
2119 return FALSE;
2121 document_check_disk_status(doc, TRUE);
2122 if (doc->priv->protected)
2123 return save_file_handle_infobars(doc, force);
2125 fp = project_get_file_prefs();
2126 /* replaces tabs with spaces but only if the current file is not a Makefile */
2127 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
2128 editor_replace_tabs(doc->editor, TRUE);
2129 /* strip trailing spaces */
2130 if (fp->strip_trailing_spaces)
2131 editor_strip_trailing_spaces(doc->editor, TRUE);
2132 /* ensure the file has a newline at the end */
2133 if (fp->final_new_line)
2134 editor_ensure_final_newline(doc->editor);
2135 /* ensure newlines are consistent */
2136 if (fp->ensure_convert_new_lines)
2137 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
2139 /* notify plugins which may wish to modify the document before it's saved */
2140 g_signal_emit_by_name(geany_object, "document-before-save", doc);
2142 len = sci_get_length(doc->editor->sci) + 1;
2143 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
2144 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
2145 * encoding, it will be converted to doc->encoding below and this conversion
2146 * also changes the BOM */
2147 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
2148 data[0] = (gchar) 0xef;
2149 data[1] = (gchar) 0xbb;
2150 data[2] = (gchar) 0xbf;
2151 sci_get_text(doc->editor->sci, len, data + 3);
2152 len += 3;
2154 else
2156 data = (gchar*) g_malloc(len);
2157 sci_get_text(doc->editor->sci, len, data);
2160 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
2161 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
2162 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
2164 if (! save_convert_to_encoding(doc, &data, &len))
2166 g_free(data);
2167 return FALSE;
2170 else
2172 len = strlen(data);
2175 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2177 /* ignore file changed notification when the file is written */
2178 doc->priv->file_disk_status = FILE_IGNORE;
2180 /* actually write the content of data to the file on disk */
2181 errmsg = save_doc(doc, locale_filename, data, len);
2182 g_free(data);
2184 if (errmsg != NULL)
2186 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
2188 if (!file_prefs.use_safe_file_saving)
2190 SETPTR(errmsg,
2191 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
2193 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
2194 doc->priv->file_disk_status = FILE_OK;
2195 utils_beep();
2196 g_free(locale_filename);
2197 g_free(errmsg);
2198 return FALSE;
2201 /* store the opened encoding for undo/redo */
2202 store_saved_encoding(doc);
2204 /* ignore the following things if we are quitting */
2205 if (! main_status.quitting)
2207 sci_set_savepoint(doc->editor->sci);
2209 if (file_prefs.disk_check_timeout > 0)
2210 document_update_timestamp(doc, locale_filename);
2212 /* update filetype-related things */
2213 document_set_filetype(doc, doc->file_type);
2215 document_update_tab_label(doc);
2217 msgwin_status_add(_("File %s saved."), doc->file_name);
2218 ui_update_statusbar(doc, -1);
2219 #ifdef HAVE_VTE
2220 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
2221 #endif
2223 g_free(locale_filename);
2225 g_signal_emit_by_name(geany_object, "document-save", doc);
2227 return TRUE;
2231 /* special search function, used from the find entry in the toolbar
2232 * return TRUE if text was found otherwise FALSE
2233 * return also TRUE if text is empty */
2234 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gboolean inc,
2235 gboolean backwards)
2237 gint start_pos, search_pos;
2238 struct Sci_TextToFind ttf;
2240 g_return_val_if_fail(text != NULL, FALSE);
2241 g_return_val_if_fail(doc != NULL, FALSE);
2242 if (! *text)
2243 return TRUE;
2245 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
2246 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
2248 /* search cursor to end or start */
2249 ttf.chrg.cpMin = start_pos;
2250 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
2251 ttf.lpstrText = (gchar *)text;
2252 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2254 /* if no match, search start (or end) to cursor */
2255 if (search_pos == -1)
2257 if (backwards)
2259 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
2260 ttf.chrg.cpMax = start_pos;
2262 else
2264 ttf.chrg.cpMin = 0;
2265 ttf.chrg.cpMax = start_pos + strlen(text);
2267 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2270 if (search_pos != -1)
2272 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
2274 /* unfold maybe folded results */
2275 sci_ensure_line_is_visible(doc->editor->sci, line);
2277 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2278 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2280 if (! editor_line_in_view(doc->editor, line))
2281 { /* we need to force scrolling in case the cursor is outside of the current visible area
2282 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2283 * while searching */
2284 editor_scroll_to_line(doc->editor, -1, 0.3F);
2286 else
2287 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2288 return TRUE;
2290 else
2292 if (! inc)
2294 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2296 utils_beep();
2297 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
2298 return FALSE;
2303 /* General search function, used from the find dialog.
2304 * Returns -1 on failure or the start position of the matching text.
2305 * Will skip past any selection, ignoring it.
2307 * @param text Text to find.
2308 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2310 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2311 GeanyFindFlags flags, gboolean search_backwards, GeanyMatchInfo **match_,
2312 gboolean scroll, GtkWidget *parent)
2314 gint selection_end, selection_start, search_pos;
2316 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2317 if (! *text)
2318 return -1;
2320 /* Sci doesn't support searching backwards with a regex */
2321 if (flags & GEANY_FIND_REGEXP)
2322 search_backwards = FALSE;
2324 if (!original_text)
2325 original_text = text;
2327 selection_start = sci_get_selection_start(doc->editor->sci);
2328 selection_end = sci_get_selection_end(doc->editor->sci);
2329 if ((selection_end - selection_start) > 0)
2330 { /* there's a selection so go to the end */
2331 if (search_backwards)
2332 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2333 else
2334 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2337 sci_set_search_anchor(doc->editor->sci);
2338 if (search_backwards)
2339 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2340 else
2341 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2343 if (search_pos != -1)
2345 /* unfold maybe folded results */
2346 sci_ensure_line_is_visible(doc->editor->sci,
2347 sci_get_line_from_position(doc->editor->sci, search_pos));
2348 if (scroll)
2349 doc->editor->scroll_percent = 0.3F;
2351 else
2353 gint sci_len = sci_get_length(doc->editor->sci);
2355 /* if we just searched the whole text, give up searching. */
2356 if ((selection_end == 0 && ! search_backwards) ||
2357 (selection_end == sci_len && search_backwards))
2359 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2360 utils_beep();
2361 return -1;
2364 /* we searched only part of the document, so ask whether to wraparound. */
2365 if (search_prefs.always_wrap ||
2366 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2367 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2369 gint ret;
2371 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2372 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2373 if (ret == -1)
2374 { /* return to original cursor position if not found */
2375 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2377 return ret;
2380 return search_pos;
2384 /* Replaces the selection if it matches, otherwise just finds the next match.
2385 * Returns: start of replaced text, or -1 if no replacement was made
2387 * @param find_text Text to find.
2388 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2390 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2391 const gchar *replace_text, GeanyFindFlags flags, gboolean search_backwards)
2393 gint selection_end, selection_start, search_pos;
2394 GeanyMatchInfo *match = NULL;
2396 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2398 if (! *find_text)
2399 return -1;
2401 /* Sci doesn't support searching backwards with a regex */
2402 if (flags & GEANY_FIND_REGEXP)
2403 search_backwards = FALSE;
2405 if (!original_find_text)
2406 original_find_text = find_text;
2408 selection_start = sci_get_selection_start(doc->editor->sci);
2409 selection_end = sci_get_selection_end(doc->editor->sci);
2410 if (selection_end == selection_start)
2412 /* no selection so just find the next match */
2413 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2414 return -1;
2416 /* there's a selection so go to the start before finding to search through it
2417 * this ensures there is a match */
2418 if (search_backwards)
2419 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2420 else
2421 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2423 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2424 /* return if the original selected text did not match (at the start of the selection) */
2425 if (search_pos != selection_start)
2427 if (search_pos != -1)
2428 geany_match_info_free(match);
2429 return -1;
2432 if (search_pos != -1)
2434 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2435 /* select the replacement - find text will skip past the selected text */
2436 sci_set_selection_start(doc->editor->sci, search_pos);
2437 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2438 geany_match_info_free(match);
2440 else
2442 /* no match in the selection */
2443 utils_beep();
2445 return search_pos;
2449 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2450 const gchar *original_replace_text)
2452 gchar *filename;
2454 if (count == 0)
2456 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2457 return;
2460 filename = g_path_get_basename(DOC_FILENAME(doc));
2461 ui_set_statusbar(TRUE, ngettext(
2462 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2463 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2464 count), filename, count, original_find_text, original_replace_text);
2465 g_free(filename);
2469 /* Replace all text matches in a certain range within document.
2470 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2471 * or -1 if no text was found.
2472 * scroll_to_match is whether to scroll the last replacement in view (which also
2473 * clears the selection).
2474 * Returns: the number of replacements made. */
2475 static guint
2476 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2477 GeanyFindFlags flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2479 gint count = 0;
2480 struct Sci_TextToFind ttf;
2481 ScintillaObject *sci;
2483 if (new_range_end != NULL)
2484 *new_range_end = -1;
2486 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2488 if (! *find_text || doc->readonly)
2489 return 0;
2491 sci = doc->editor->sci;
2493 ttf.chrg.cpMin = start;
2494 ttf.chrg.cpMax = end;
2495 ttf.lpstrText = (gchar*)find_text;
2497 sci_start_undo_action(sci);
2498 count = search_replace_range(sci, &ttf, flags, replace_text);
2499 sci_end_undo_action(sci);
2501 if (count > 0)
2502 { /* scroll last match in view, will destroy the existing selection */
2503 if (scroll_to_match)
2504 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2506 if (new_range_end != NULL)
2507 *new_range_end = ttf.chrg.cpMax;
2509 return count;
2513 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2514 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2516 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2517 gint max_column = 0, count = 0;
2518 gboolean replaced = FALSE;
2520 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2522 if (! *find_text)
2523 return;
2525 selection_start = sci_get_selection_start(doc->editor->sci);
2526 selection_end = sci_get_selection_end(doc->editor->sci);
2527 /* do we have a selection? */
2528 if ((selection_end - selection_start) == 0)
2530 utils_beep();
2531 return;
2534 selection_mode = sci_get_selection_mode(doc->editor->sci);
2535 selected_lines = sci_get_lines_selected(doc->editor->sci);
2536 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2537 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2539 gint first_line, line;
2541 sci_start_undo_action(doc->editor->sci);
2543 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2544 /* Find the last line with chars selected (not EOL char) */
2545 last_line = sci_get_line_from_position(doc->editor->sci,
2546 selection_end - editor_get_eol_char_len(doc->editor));
2547 last_line = MAX(first_line, last_line);
2548 for (line = first_line; line < (first_line + selected_lines); line++)
2550 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2551 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2553 /* skip line if there is no selection */
2554 if (line_start != INVALID_POSITION)
2556 /* don't let document_replace_range() scroll to match to keep our selection */
2557 gint new_sel_end;
2559 count += document_replace_range(doc, find_text, replace_text, flags,
2560 line_start, line_end, FALSE, &new_sel_end);
2561 if (new_sel_end != -1)
2563 replaced = TRUE;
2564 /* this gets the greatest column within the selection after replacing */
2565 max_column = MAX(max_column,
2566 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2570 sci_end_undo_action(doc->editor->sci);
2572 else /* handle normal line selection */
2574 count += document_replace_range(doc, find_text, replace_text, flags,
2575 selection_start, selection_end, TRUE, &selection_end);
2576 if (selection_end != -1)
2577 replaced = TRUE;
2580 if (replaced)
2581 { /* update the selection for the new endpoint */
2583 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2585 /* now we can scroll to the selection and destroy it because we rebuild it later */
2586 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2588 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2589 * the highest column on the last line. The wrapped selection is completely different
2590 * from the original one, so skip the selection at all */
2591 /* TODO is there a better way to handle the wrapped selection? */
2592 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2593 { /* for keeping and adjusting the selection in multi line rectangle selection we
2594 * need the last line of the original selection and the greatest column number after
2595 * replacing and set the selection end to the last line at the greatest column */
2596 sci_set_selection_start(doc->editor->sci, selection_start);
2597 sci_set_selection_end(doc->editor->sci,
2598 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2599 sci_set_selection_mode(doc->editor->sci, selection_mode);
2602 else
2604 sci_set_selection_start(doc->editor->sci, selection_start);
2605 sci_set_selection_end(doc->editor->sci, selection_end);
2608 else /* no replacements */
2609 utils_beep();
2611 show_replace_summary(doc, count, original_find_text, original_replace_text);
2615 /* returns number of replacements made. */
2616 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2617 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2619 gint len, count;
2620 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2622 if (! *find_text)
2623 return FALSE;
2625 len = sci_get_length(doc->editor->sci);
2626 count = document_replace_range(
2627 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2629 show_replace_summary(doc, count, original_find_text, original_replace_text);
2630 return count;
2635 * Parses or re-parses the document's buffer and updates the type
2636 * keywords and symbol list.
2638 * @param doc The document.
2640 void document_update_tags(GeanyDocument *doc)
2642 guchar *buffer_ptr;
2643 gsize len;
2645 g_return_if_fail(DOC_VALID(doc));
2646 g_return_if_fail(app->tm_workspace != NULL);
2648 /* early out if it's a new file or doesn't support tags */
2649 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2651 /* We must call sidebar_update_tag_list() before returning,
2652 * to ensure that the symbol list is always updated properly (e.g.
2653 * when creating a new document with a partial filename set. */
2654 sidebar_update_tag_list(doc, FALSE);
2655 return;
2658 /* create a new TM file if there isn't one yet */
2659 if (! doc->tm_file)
2661 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2662 const gchar *name;
2664 /* lookup the name rather than using filetype name to support custom filetypes */
2665 name = tm_source_file_get_lang_name(doc->file_type->lang);
2666 doc->tm_file = tm_source_file_new(locale_filename, name);
2667 g_free(locale_filename);
2669 if (doc->tm_file)
2670 tm_workspace_add_source_file_noupdate(doc->tm_file);
2673 /* early out if there's no tm source file and we couldn't create one */
2674 if (doc->tm_file == NULL)
2676 /* We must call sidebar_update_tag_list() before returning,
2677 * to ensure that the symbol list is always updated properly (e.g.
2678 * when creating a new document with a partial filename set. */
2679 sidebar_update_tag_list(doc, FALSE);
2680 return;
2683 /* Parse Scintilla's buffer directly using TagManager
2684 * Note: this buffer *MUST NOT* be modified */
2685 len = sci_get_length(doc->editor->sci);
2686 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2687 tm_workspace_update_source_file_buffer(doc->tm_file, buffer_ptr, len);
2689 sidebar_update_tag_list(doc, TRUE);
2690 document_highlight_tags(doc);
2694 /* Re-highlights type keywords without re-parsing the whole document. */
2695 void document_highlight_tags(GeanyDocument *doc)
2697 GString *keywords_str;
2698 gint keyword_idx;
2700 /* some filetypes support type keywords (such as struct names), but not
2701 * necessarily all filetypes for a particular scintilla lexer. this
2702 * tells us whether the filetype supports keywords, and if so
2703 * which index to use for the scintilla keywords set. */
2704 switch (doc->file_type->id)
2706 case GEANY_FILETYPES_C:
2707 case GEANY_FILETYPES_CPP:
2708 case GEANY_FILETYPES_CS:
2709 case GEANY_FILETYPES_D:
2710 case GEANY_FILETYPES_JAVA:
2711 case GEANY_FILETYPES_OBJECTIVEC:
2712 case GEANY_FILETYPES_VALA:
2713 case GEANY_FILETYPES_RUST:
2714 case GEANY_FILETYPES_GO:
2717 /* index of the keyword set in the Scintilla lexer, for
2718 * example in LexCPP.cxx, see "cppWordLists" global array.
2719 * TODO: this magic number should be a member of the filetype */
2720 keyword_idx = 3;
2721 break;
2723 default:
2724 return; /* early out if type keywords are not supported */
2726 if (!app->tm_workspace->tags_array)
2727 return;
2729 /* get any type keywords and tell scintilla about them
2730 * this will cause the type keywords to be colourized in scintilla */
2731 keywords_str = symbols_find_typenames_as_string(doc->file_type->lang, FALSE);
2732 if (keywords_str)
2734 gchar *keywords = g_string_free(keywords_str, FALSE);
2735 guint hash = g_str_hash(keywords);
2737 if (hash != doc->priv->keyword_hash)
2739 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2740 queue_colourise(doc); /* force re-highlighting the entire document */
2741 doc->priv->keyword_hash = hash;
2743 g_free(keywords);
2748 static gboolean on_document_update_tag_list_idle(gpointer data)
2750 GeanyDocument *doc = data;
2752 if (! DOC_VALID(doc))
2753 return FALSE;
2755 if (! main_status.quitting)
2756 document_update_tags(doc);
2758 doc->priv->tag_list_update_source = 0;
2760 /* don't update the tags until another modification of the buffer */
2761 return FALSE;
2765 void document_update_tag_list_in_idle(GeanyDocument *doc)
2767 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2768 return;
2770 /* prevent "stacking up" callback handlers, we only need one to run soon */
2771 if (doc->priv->tag_list_update_source != 0)
2772 g_source_remove(doc->priv->tag_list_update_source);
2774 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2775 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2779 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2780 gboolean filetype_changed)
2782 g_return_if_fail(doc);
2783 if (type == NULL)
2784 type = filetypes[GEANY_FILETYPES_NONE];
2786 if (filetype_changed)
2788 doc->file_type = type;
2790 /* delete tm file object to force creation of a new one */
2791 if (doc->tm_file != NULL)
2793 tm_workspace_remove_source_file(doc->tm_file);
2794 tm_source_file_free(doc->tm_file);
2795 doc->tm_file = NULL;
2797 /* load tags files before highlighting (some lexers highlight global typenames) */
2798 if (type->id != GEANY_FILETYPES_NONE)
2799 symbols_global_tags_loaded(type->id);
2801 highlighting_set_styles(doc->editor->sci, type);
2802 editor_set_indentation_guides(doc->editor);
2803 build_menu_update(doc);
2804 queue_colourise(doc);
2805 if (type->priv->symbol_list_sort_mode == SYMBOLS_SORT_USE_PREVIOUS)
2806 doc->priv->symbol_list_sort_mode = interface_prefs.symbols_sort_mode;
2807 else
2808 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2811 document_update_tags(doc);
2815 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2816 * @param doc The document to use.
2817 * @param type The filetype. */
2818 GEANY_API_SYMBOL
2819 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2821 gboolean ft_changed;
2822 GeanyFiletype *old_ft;
2824 g_return_if_fail(doc);
2825 if (type == NULL)
2826 type = filetypes[GEANY_FILETYPES_NONE];
2828 old_ft = doc->file_type;
2829 geany_debug("%s : %s (%s)",
2830 (doc->file_name != NULL) ? doc->file_name : "unknown",
2831 type->name,
2832 (doc->encoding != NULL) ? doc->encoding : "unknown");
2834 ft_changed = (doc->file_type != type); /* filetype has changed */
2835 document_load_config(doc, type, ft_changed);
2837 if (ft_changed)
2839 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2841 /* assume that if previous filetype was none and the settings are the default ones, this
2842 * is the first time the filetype is carefully set, so we should apply indent settings */
2843 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2844 doc->editor->indent_type == iprefs->type &&
2845 doc->editor->indent_width == iprefs->width)
2847 document_apply_indent_settings(doc);
2848 ui_document_show_hide(doc);
2851 sidebar_openfiles_update(doc); /* to update the icon */
2852 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2857 void document_reload_config(GeanyDocument *doc)
2859 document_load_config(doc, doc->file_type, TRUE);
2864 * Sets the encoding of a document.
2865 * This function only set the encoding of the %document, it does not any conversions. The new
2866 * encoding is used when e.g. saving the file.
2868 * @param doc The document to use.
2869 * @param new_encoding The encoding to be set for the document.
2871 GEANY_API_SYMBOL
2872 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2874 if (doc == NULL || new_encoding == NULL ||
2875 utils_str_equal(new_encoding, doc->encoding))
2876 return;
2878 g_free(doc->encoding);
2879 doc->encoding = g_strdup(new_encoding);
2881 ui_update_statusbar(doc, -1);
2882 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2883 encodings_is_unicode_charset(doc->encoding));
2887 /* own Undo / Redo implementation to be able to undo / redo changes
2888 * to the encoding or the Unicode BOM (which are Scintilla independet).
2889 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2891 /* Clears an Undo or Redo buffer. */
2892 void document_undo_clear_stack(GTrashStack **stack)
2894 while (g_trash_stack_height(stack) > 0)
2896 undo_action *a = g_trash_stack_pop(stack);
2898 if (G_LIKELY(a != NULL))
2900 switch (a->type)
2902 case UNDO_ENCODING:
2903 case UNDO_RELOAD:
2904 g_free(a->data); break;
2905 default: break;
2907 g_free(a);
2910 *stack = NULL;
2913 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2914 void document_undo_clear(GeanyDocument *doc)
2916 document_undo_clear_stack(&doc->priv->undo_actions);
2917 document_undo_clear_stack(&doc->priv->redo_actions);
2919 if (! main_status.quitting && doc->editor != NULL)
2920 document_set_text_changed(doc, FALSE);
2924 /* Adds an undo action without clearing the redo stack. This function should
2925 * not be called directly, generally (use document_undo_add() instead), but is
2926 * used by document_redo() in order not to erase the redo stack while moving
2927 * an action from the redo stack to the undo stack. */
2928 void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data)
2930 undo_action *action;
2932 g_return_if_fail(doc != NULL);
2934 action = g_new0(undo_action, 1);
2935 action->type = type;
2936 action->data = data;
2938 g_trash_stack_push(&doc->priv->undo_actions, action);
2940 /* avoid unnecessary redraws */
2941 if (type != UNDO_SCINTILLA || !doc->changed)
2942 document_set_text_changed(doc, TRUE);
2944 ui_update_popup_reundo_items(doc);
2947 /* note: this is called on SCN_MODIFIED notifications */
2948 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2950 /* Clear the redo actions stack before adding the undo action. */
2951 document_undo_clear_stack(&doc->priv->redo_actions);
2953 document_undo_add_internal(doc, type, data);
2957 gboolean document_can_undo(GeanyDocument *doc)
2959 g_return_val_if_fail(doc != NULL, FALSE);
2961 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2962 return TRUE;
2963 else
2964 return FALSE;
2968 static void update_changed_state(GeanyDocument *doc)
2970 doc->changed =
2971 (sci_is_modified(doc->editor->sci) ||
2972 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2973 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2974 document_set_text_changed(doc, doc->changed);
2978 void document_undo(GeanyDocument *doc)
2980 undo_action *action;
2982 g_return_if_fail(doc != NULL);
2984 action = g_trash_stack_pop(&doc->priv->undo_actions);
2986 if (G_UNLIKELY(action == NULL))
2988 /* fallback, should not be necessary */
2989 geany_debug("%s: fallback used", G_STRFUNC);
2990 sci_undo(doc->editor->sci);
2992 else
2994 switch (action->type)
2996 case UNDO_SCINTILLA:
2998 document_redo_add(doc, UNDO_SCINTILLA, NULL);
3000 sci_undo(doc->editor->sci);
3001 break;
3003 case UNDO_BOM:
3005 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3007 doc->has_bom = GPOINTER_TO_INT(action->data);
3008 ui_update_statusbar(doc, -1);
3009 ui_document_show_hide(doc);
3010 break;
3012 case UNDO_ENCODING:
3014 /* use the "old" encoding */
3015 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3017 document_set_encoding(doc, (const gchar*)action->data);
3018 g_free(action->data);
3020 ui_update_statusbar(doc, -1);
3021 ui_document_show_hide(doc);
3022 break;
3024 case UNDO_EOL:
3026 undo_action *next_action;
3028 document_redo_add(doc, UNDO_EOL, GINT_TO_POINTER(sci_get_eol_mode(doc->editor->sci)));
3030 sci_set_eol_mode(doc->editor->sci, GPOINTER_TO_INT(action->data));
3032 ui_update_statusbar(doc, -1);
3033 ui_document_show_hide(doc);
3035 /* When undoing, UNDO_EOL is always followed by UNDO_SCINTILLA
3036 * which undos the line endings in the editor and should be
3037 * performed together with UNDO_EOL. */
3038 next_action = g_trash_stack_peek(&doc->priv->undo_actions);
3039 if (next_action && next_action->type == UNDO_SCINTILLA)
3040 document_undo(doc);
3041 break;
3043 case UNDO_RELOAD:
3045 UndoReloadData *data = (UndoReloadData*)action->data;
3046 gint eol_mode = data->eol_mode;
3047 guint i;
3049 /* We reuse 'data' for the redo action, so read the current EOL mode
3050 * into it before proceeding. */
3051 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3053 /* Undo the rest of the actions which are part of the reloading process. */
3054 for (i = 0; i < data->actions_count; i++)
3055 document_undo(doc);
3057 /* Restore the previous EOL mode. */
3058 sci_set_eol_mode(doc->editor->sci, eol_mode);
3059 /* This might affect the status bar and document menu, so update them. */
3060 ui_update_statusbar(doc, -1);
3061 ui_document_show_hide(doc);
3063 document_redo_add(doc, UNDO_RELOAD, data);
3064 break;
3066 default: break;
3069 g_free(action); /* free the action which was taken from the stack */
3071 update_changed_state(doc);
3072 ui_update_popup_reundo_items(doc);
3076 gboolean document_can_redo(GeanyDocument *doc)
3078 g_return_val_if_fail(doc != NULL, FALSE);
3080 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
3081 return TRUE;
3082 else
3083 return FALSE;
3087 void document_redo(GeanyDocument *doc)
3089 undo_action *action;
3091 g_return_if_fail(doc != NULL);
3093 action = g_trash_stack_pop(&doc->priv->redo_actions);
3095 if (G_UNLIKELY(action == NULL))
3097 /* fallback, should not be necessary */
3098 geany_debug("%s: fallback used", G_STRFUNC);
3099 sci_redo(doc->editor->sci);
3101 else
3103 switch (action->type)
3105 case UNDO_SCINTILLA:
3107 undo_action *next_action;
3109 document_undo_add_internal(doc, UNDO_SCINTILLA, NULL);
3111 sci_redo(doc->editor->sci);
3113 /* When redoing an EOL change, the UNDO_SCINTILLA which changes
3114 * the line ends in the editor is followed by UNDO_EOL
3115 * which should be performed together with UNDO_SCINTILLA. */
3116 next_action = g_trash_stack_peek(&doc->priv->redo_actions);
3117 if (next_action != NULL && next_action->type == UNDO_EOL)
3118 document_redo(doc);
3119 break;
3121 case UNDO_BOM:
3123 document_undo_add_internal(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3125 doc->has_bom = GPOINTER_TO_INT(action->data);
3126 ui_update_statusbar(doc, -1);
3127 ui_document_show_hide(doc);
3128 break;
3130 case UNDO_ENCODING:
3132 document_undo_add_internal(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3134 document_set_encoding(doc, (const gchar*)action->data);
3135 g_free(action->data);
3137 ui_update_statusbar(doc, -1);
3138 ui_document_show_hide(doc);
3139 break;
3141 case UNDO_EOL:
3143 document_undo_add_internal(doc, UNDO_EOL, GINT_TO_POINTER(sci_get_eol_mode(doc->editor->sci)));
3145 sci_set_eol_mode(doc->editor->sci, GPOINTER_TO_INT(action->data));
3147 ui_update_statusbar(doc, -1);
3148 ui_document_show_hide(doc);
3149 break;
3151 case UNDO_RELOAD:
3153 UndoReloadData *data = (UndoReloadData*)action->data;
3154 gint eol_mode = data->eol_mode;
3155 guint i;
3157 /* We reuse 'data' for the undo action, so read the current EOL mode
3158 * into it before proceeding. */
3159 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3161 /* Redo the rest of the actions which are part of the reloading process. */
3162 for (i = 0; i < data->actions_count; i++)
3163 document_redo(doc);
3165 /* Restore the previous EOL mode. */
3166 sci_set_eol_mode(doc->editor->sci, eol_mode);
3167 /* This might affect the status bar and document menu, so update them. */
3168 ui_update_statusbar(doc, -1);
3169 ui_document_show_hide(doc);
3171 document_undo_add_internal(doc, UNDO_RELOAD, data);
3172 break;
3174 default: break;
3177 g_free(action); /* free the action which was taken from the stack */
3179 update_changed_state(doc);
3180 ui_update_popup_reundo_items(doc);
3184 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
3186 undo_action *action;
3188 g_return_if_fail(doc != NULL);
3190 action = g_new0(undo_action, 1);
3191 action->type = type;
3192 action->data = data;
3194 g_trash_stack_push(&doc->priv->redo_actions, action);
3196 if (type != UNDO_SCINTILLA || !doc->changed)
3197 document_set_text_changed(doc, TRUE);
3199 ui_update_popup_reundo_items(doc);
3203 enum
3205 STATUS_CHANGED,
3206 STATUS_DISK_CHANGED,
3207 STATUS_READONLY
3210 static struct
3212 const gchar *name;
3213 GdkColor color;
3214 gboolean loaded;
3215 } document_status_styles[] = {
3216 { "geany-document-status-changed", {0}, FALSE },
3217 { "geany-document-status-disk-changed", {0}, FALSE },
3218 { "geany-document-status-readonly", {0}, FALSE }
3222 static gint document_get_status_id(GeanyDocument *doc)
3224 if (doc->changed)
3225 return STATUS_CHANGED;
3226 #ifdef USE_GIO_FILEMON
3227 else if (doc->priv->file_disk_status == FILE_CHANGED)
3228 #else
3229 else if (doc->priv->protected)
3230 #endif
3231 return STATUS_DISK_CHANGED;
3232 else if (doc->readonly)
3233 return STATUS_READONLY;
3235 return -1;
3239 /* returns an identifier that is to be set as a widget name or class to get it styled
3240 * depending on the document status (changed, readonly, etc.)
3241 * a NULL return value means default (unchanged) style */
3242 const gchar *document_get_status_widget_class(GeanyDocument *doc)
3244 gint status;
3246 g_return_val_if_fail(doc != NULL, NULL);
3248 status = document_get_status_id(doc);
3249 if (status < 0)
3250 return NULL;
3251 else
3252 return document_status_styles[status].name;
3257 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
3258 * Returned colors are red if the document has changes, green if the document is read-only
3259 * or simply @c NULL if the document is unmodified but writable.
3261 * @param doc The document to use.
3263 * @return @nullable The color for the document or @c NULL if the default color should be used.
3264 * The color object is owned by Geany and should not be modified or freed.
3266 * @since 0.16
3268 GEANY_API_SYMBOL
3269 const GdkColor *document_get_status_color(GeanyDocument *doc)
3271 gint status;
3273 g_return_val_if_fail(doc != NULL, NULL);
3275 status = document_get_status_id(doc);
3276 if (status < 0)
3277 return NULL;
3278 if (! document_status_styles[status].loaded)
3280 #if GTK_CHECK_VERSION(3, 0, 0)
3281 GdkRGBA color;
3282 GtkWidgetPath *path = gtk_widget_path_new();
3283 GtkStyleContext *ctx = gtk_style_context_new();
3284 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
3285 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
3286 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
3287 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
3288 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
3289 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
3290 gtk_style_context_set_path(ctx, path);
3291 gtk_style_context_get_color(ctx, gtk_style_context_get_state(ctx), &color);
3292 document_status_styles[status].color.red = 0xffff * color.red;
3293 document_status_styles[status].color.green = 0xffff * color.green;
3294 document_status_styles[status].color.blue = 0xffff * color.blue;
3295 document_status_styles[status].loaded = TRUE;
3296 gtk_widget_path_unref(path);
3297 g_object_unref(ctx);
3298 #else
3299 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
3300 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
3301 document_status_styles[status].name, NULL);
3302 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
3304 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
3305 document_status_styles[status].loaded = TRUE;
3306 g_free(path);
3307 #endif
3309 return &document_status_styles[status].color;
3313 /** Accessor function for @ref GeanyData::documents_array items.
3314 * @warning Always check the returned document is valid (@c doc->is_valid).
3315 * @param idx @c GeanyData::documents_array index.
3316 * @return @transfer{none} @nullable The document, or @c NULL if @a idx is out of range.
3318 * @since 0.16
3320 GEANY_API_SYMBOL
3321 GeanyDocument *document_index(gint idx)
3323 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
3327 GeanyDocument *document_clone(GeanyDocument *old_doc)
3329 gchar *text;
3330 GeanyDocument *doc;
3331 ScintillaObject *old_sci;
3333 g_return_val_if_fail(old_doc, NULL);
3334 old_sci = old_doc->editor->sci;
3335 if (sci_has_selection(old_sci))
3336 text = sci_get_selection_contents(old_sci);
3337 else
3338 text = sci_get_contents(old_sci, -1);
3340 doc = document_new_file(NULL, old_doc->file_type, text);
3341 g_free(text);
3342 document_set_text_changed(doc, TRUE);
3344 /* copy file properties */
3345 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
3346 doc->editor->line_breaking = old_doc->editor->line_breaking;
3347 doc->editor->auto_indent = old_doc->editor->auto_indent;
3348 editor_set_indent(doc->editor, old_doc->editor->indent_type,
3349 old_doc->editor->indent_width);
3350 doc->readonly = old_doc->readonly;
3351 doc->has_bom = old_doc->has_bom;
3352 doc->priv->protected = 0;
3353 document_set_encoding(doc, old_doc->encoding);
3354 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
3355 sci_set_readonly(doc->editor->sci, doc->readonly);
3357 /* update ui */
3358 ui_document_show_hide(doc);
3359 return doc;
3363 /* @note If successful, this should always be followed up with a call to
3364 * document_close_all().
3365 * @return TRUE if all files were saved or had their changes discarded. */
3366 gboolean document_account_for_unsaved(void)
3368 guint i, p, page_count;
3370 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3371 /* iterate over documents in tabs order */
3372 for (p = 0; p < page_count; p++)
3374 GeanyDocument *doc = document_get_from_page(p);
3376 if (DOC_VALID(doc) && doc->changed)
3378 if (! dialogs_show_unsaved_file(doc))
3379 return FALSE;
3382 /* all documents should now be accounted for, so ignore any changes */
3383 foreach_document (i)
3385 documents[i]->changed = FALSE;
3387 return TRUE;
3391 static void force_close_all(void)
3393 guint i, len = documents_array->len;
3395 /* check all documents have been accounted for */
3396 for (i = 0; i < len; i++)
3398 if (documents[i]->is_valid)
3400 g_return_if_fail(!documents[i]->changed);
3403 main_status.closing_all = TRUE;
3405 foreach_document(i)
3407 document_close(documents[i]);
3410 main_status.closing_all = FALSE;
3414 gboolean document_close_all(void)
3416 if (! document_account_for_unsaved())
3417 return FALSE;
3419 force_close_all();
3421 return TRUE;
3425 /* *
3426 * Shows a message related to a document.
3428 * Use this whenever the user needs to see a document-related message,
3429 * for example when the file was externally modified or deleted.
3431 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3432 * @a response_1 response will be the default for the @c GtkInfoBar or
3433 * @c GtkDialog.
3435 * @param doc @c GeanyDocument.
3436 * @param msgtype The type of message.
3437 * @param response_cb A callback function called when there's a response.
3438 * @param btn_1 The first action area button.
3439 * @param response_1 The response for @a btn_1.
3440 * @param btn_2 The second action area button.
3441 * @param response_2 The response for @a btn_2.
3442 * @param btn_3 The third action area button.
3443 * @param response_3 The response for @a btn_3.
3444 * @param extra_text Text to show below the main message.
3445 * @param format The text format for the main message.
3446 * @param ... Used with @a format as in @c printf.
3448 * @since 1.25
3449 * */
3450 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3451 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3452 const gchar *btn_1, GtkResponseType response_1,
3453 const gchar *btn_2, GtkResponseType response_2,
3454 const gchar *btn_3, GtkResponseType response_3,
3455 const gchar *extra_text, const gchar *format, ...)
3457 va_list args;
3458 gchar *text, *markup;
3459 GtkWidget *hbox, *icon, *label, *content_area;
3460 GtkWidget *info_widget, *parent;
3461 parent = document_get_notebook_child(doc);
3463 va_start(args, format);
3464 text = g_strdup_vprintf(format, args);
3465 va_end(args);
3467 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3468 g_free(text);
3470 info_widget = gtk_info_bar_new();
3471 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3472 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3474 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3476 if (btn_1)
3477 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3478 if (btn_2)
3479 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3480 if (btn_3)
3481 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3483 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3485 label = geany_wrap_label_new(NULL);
3486 gtk_label_set_markup(GTK_LABEL(label), markup);
3487 g_free(markup);
3489 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3491 hbox = gtk_hbox_new(FALSE, 12);
3492 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3494 switch (msgtype)
3496 case GTK_MESSAGE_INFO:
3497 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3498 break;
3499 case GTK_MESSAGE_WARNING:
3500 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3501 break;
3502 case GTK_MESSAGE_QUESTION:
3503 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3504 break;
3505 case GTK_MESSAGE_ERROR:
3506 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3507 break;
3508 default:
3509 icon = NULL;
3510 break;
3513 if (icon)
3514 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3516 if (extra_text)
3518 GtkWidget *vbox = gtk_vbox_new(FALSE, 6);
3519 GtkWidget *extra_label = geany_wrap_label_new(extra_text);
3521 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3522 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3523 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3525 else
3526 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3528 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3530 gtk_widget_show_all(info_widget);
3532 return info_widget;
3536 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3538 gboolean close = FALSE;
3540 // disable info bar so actions complete normally
3541 unprotect_document(doc);
3542 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3544 if (response_id == RESPONSE_DOCUMENT_RELOAD)
3546 close = doc->changed ?
3547 document_reload_prompt(doc, doc->encoding) :
3548 document_reload_force(doc, doc->encoding);
3550 else if (response_id == RESPONSE_DOCUMENT_SAVE)
3552 close = document_save_file(doc, TRUE); // force overwrite
3554 else if (response_id == GTK_RESPONSE_CANCEL)
3556 document_set_text_changed(doc, TRUE);
3557 close = TRUE;
3559 if (!close)
3561 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3562 protect_document(doc);
3563 return;
3565 gtk_widget_destroy(bar);
3569 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3571 GtkInfoBar *bar = GTK_INFO_BAR(data);
3573 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3575 switch (event->keyval)
3577 case GDK_Tab:
3578 case GDK_ISO_Left_Tab:
3580 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3581 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3582 gtk_widget_child_focus(action_area, dir);
3583 return TRUE;
3585 case GDK_Escape:
3587 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3588 return TRUE;
3590 default:
3591 return FALSE;
3596 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3597 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3599 /* automatically focus editor again on bar close */
3600 g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3601 G_CONNECT_SWAPPED);
3602 g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3606 static void monitor_reload_file(GeanyDocument *doc)
3608 gchar *base_name = g_path_get_basename(doc->file_name);
3610 /* show this message only once */
3611 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3613 GtkWidget *bar;
3615 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3616 _("_Reload"), RESPONSE_DOCUMENT_RELOAD,
3617 _("_Overwrite"), RESPONSE_DOCUMENT_SAVE,
3618 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3619 _("Do you want to reload it?"),
3620 _("The file '%s' on the disk is more recent than the current buffer."),
3621 base_name);
3623 protect_document(doc);
3624 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3625 enable_key_intercept(doc, bar);
3627 g_free(base_name);
3631 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3632 gint response_id,
3633 GeanyDocument *doc)
3635 gboolean close = TRUE;
3637 unprotect_document(doc);
3639 if (response_id == RESPONSE_DOCUMENT_SAVE)
3640 close = dialogs_show_save_as();
3642 if (close)
3644 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3645 gtk_widget_destroy(bar);
3647 else
3649 /* protect back the document if save didn't occur */
3650 protect_document(doc);
3655 static void monitor_resave_missing_file(GeanyDocument *doc)
3657 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3659 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3661 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3662 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3664 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3665 on_monitor_resave_missing_file_response,
3666 GTK_STOCK_SAVE, RESPONSE_DOCUMENT_SAVE,
3667 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3668 NULL, GTK_RESPONSE_NONE,
3669 _("Try to resave the file?"),
3670 _("File \"%s\" was not found on disk!"),
3671 doc->file_name);
3673 protect_document(doc);
3674 document_set_text_changed(doc, TRUE);
3675 /* don't prompt more than once */
3676 SETPTR(doc->real_path, NULL);
3677 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3678 enable_key_intercept(doc, bar);
3683 /* Set force to force a disk check, otherwise it is ignored if there was a check
3684 * in the last file_prefs.disk_check_timeout seconds.
3685 * @return @c TRUE if the file has changed. */
3686 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3688 gboolean ret = FALSE;
3689 gboolean use_gio_filemon;
3690 time_t mtime;
3691 gchar *locale_filename;
3692 FileDiskStatus old_status;
3694 g_return_val_if_fail(doc != NULL, FALSE);
3696 /* ignore remote files and documents that have never been saved to disk */
3697 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3698 || doc->real_path == NULL || doc->priv->is_remote)
3699 return FALSE;
3701 use_gio_filemon = (doc->priv->monitor != NULL);
3703 if (use_gio_filemon)
3705 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3706 return FALSE;
3708 else
3710 time_t cur_time = time(NULL);
3712 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3713 return FALSE;
3715 doc->priv->last_check = cur_time;
3718 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3719 if (!get_mtime(locale_filename, &mtime))
3721 monitor_resave_missing_file(doc);
3722 /* doc may be closed now */
3723 ret = TRUE;
3725 else if (doc->priv->mtime < mtime)
3727 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3728 doc->priv->mtime = mtime;
3729 monitor_reload_file(doc);
3730 /* doc may be closed now */
3731 ret = TRUE;
3733 g_free(locale_filename);
3735 if (DOC_VALID(doc))
3736 { /* doc can get invalid when a document was closed */
3737 old_status = doc->priv->file_disk_status;
3738 doc->priv->file_disk_status = FILE_OK;
3739 if (old_status != doc->priv->file_disk_status)
3740 ui_update_tab_status(doc);
3742 return ret;
3746 /** Compares documents by their display names.
3747 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3748 * @note 'Display name' means the base name of the document's filename.
3750 * @param a @c GeanyDocument**.
3751 * @param b @c GeanyDocument**.
3752 * @warning The arguments take the address of each document pointer.
3753 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3755 * @since 0.21
3757 GEANY_API_SYMBOL
3758 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3760 GeanyDocument *doc_a = *((GeanyDocument**) a);
3761 GeanyDocument *doc_b = *((GeanyDocument**) b);
3762 gchar *base_name_a, *base_name_b;
3763 gint result;
3765 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3766 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3768 result = strcmp(base_name_a, base_name_b);
3770 g_free(base_name_a);
3771 g_free(base_name_b);
3773 return result;
3777 /** Compares documents by their tab order.
3778 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3780 * @param a @c GeanyDocument**.
3781 * @param b @c GeanyDocument**.
3782 * @warning The arguments take the address of each document pointer.
3783 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3785 * @since 0.21 (GEANY_API_VERSION 209)
3787 GEANY_API_SYMBOL
3788 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3790 GeanyDocument *doc_a = *((GeanyDocument**) a);
3791 GeanyDocument *doc_b = *((GeanyDocument**) b);
3792 gint notebook_position_doc_a;
3793 gint notebook_position_doc_b;
3795 notebook_position_doc_a = document_get_notebook_page(doc_a);
3796 notebook_position_doc_b = document_get_notebook_page(doc_b);
3798 if (notebook_position_doc_a < notebook_position_doc_b)
3799 return -1;
3800 if (notebook_position_doc_a > notebook_position_doc_b)
3801 return 1;
3802 /* equality */
3803 return 0;
3807 /** Compares documents by their tab order, in reverse order.
3808 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3810 * @param a @c GeanyDocument**.
3811 * @param b @c GeanyDocument**.
3812 * @warning The arguments take the address of each document pointer.
3813 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3815 * @since 0.21 (GEANY_API_VERSION 209)
3817 GEANY_API_SYMBOL
3818 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3820 return -1 * document_compare_by_tab_order(a, b);
3824 void document_grab_focus(GeanyDocument *doc)
3826 g_return_if_fail(doc != NULL);
3828 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));
3831 static void *copy_(void *src) { return src; }
3832 static void free_(void *doc) { }
3834 /** @gironly
3835 * Gets the GType of GeanyDocument
3837 * @return the GeanyDocument type */
3838 GEANY_API_SYMBOL
3839 GType document_get_type (void);
3841 G_DEFINE_BOXED_TYPE(GeanyDocument, document, copy_, free_);