Revert "Colourise only the visible area when highlighting typenames"
[geany-mirror.git] / src / document.c
blobc6edac07ecee7adf17d7a5048c3d38ce99511c5a
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;
91 /** Dynamic array of GeanyDocument pointers.
92 * Once a pointer is added to this, it is never freed. This means the same document pointer
93 * can represent a different document later on, or it may have been closed and become invalid.
94 * For this reason, you should use document_find_by_id() instead of storing
95 * document pointers over time if there is a chance the user can close the
96 * document.
98 * @warning You must check @c GeanyDocument::is_valid when iterating over this array.
99 * This is done automatically if you use the foreach_document() macro.
101 * @note
102 * Never assume that the order of document pointers is the same as the order of notebook tabs.
103 * One reason is that notebook tabs can be reordered.
104 * Use @c document_get_from_page() to lookup a document from a notebook tab number.
106 * @see documents. */
107 GPtrArray *documents_array = NULL;
110 /* an undo action, also used for redo actions */
111 typedef struct
113 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
114 guint type; /* to identify the action */
115 gpointer *data; /* the old value (before the change), in case of a redo action
116 * it contains the new value */
117 } undo_action;
119 /* Custom document info bar response IDs */
120 enum
122 RESPONSE_DOCUMENT_RELOAD = 1,
123 RESPONSE_DOCUMENT_SAVE,
127 static guint doc_id_counter = 0;
130 static void document_undo_clear_stack(GTrashStack **stack);
131 static void document_undo_clear(GeanyDocument *doc);
132 static void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data);
133 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
134 static gboolean remove_page(guint page_num);
135 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
136 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
137 const gchar *btn_1, GtkResponseType response_1,
138 const gchar *btn_2, GtkResponseType response_2,
139 const gchar *btn_3, GtkResponseType response_3,
140 const gchar *extra_text, const gchar *format, ...) G_GNUC_PRINTF(11, 12);
144 * Finds a document whose @c real_path field matches the given filename.
146 * @param realname The filename to search, which should be identical to the
147 * string returned by @c tm_get_real_path().
149 * @return @transfer{none} @nullable The matching document, or @c NULL.
150 * @note This is only really useful when passing a @c TMSourceFile::file_name.
151 * @see GeanyDocument::real_path.
152 * @see document_find_by_filename().
154 * @since 0.15
156 GEANY_API_SYMBOL
157 GeanyDocument* document_find_by_real_path(const gchar *realname)
159 guint i;
161 if (! realname)
162 return NULL; /* file doesn't exist on disk */
164 for (i = 0; i < documents_array->len; i++)
166 GeanyDocument *doc = documents[i];
168 if (! doc->is_valid || ! doc->real_path)
169 continue;
171 if (utils_filenamecmp(realname, doc->real_path) == 0)
173 return doc;
176 return NULL;
180 /* dereference symlinks, /../ junk in path and return locale encoding */
181 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
183 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
184 gchar *realname = tm_get_real_path(locale_name);
186 g_free(locale_name);
187 return realname;
192 * Finds a document with the given filename.
193 * This matches either an exact GeanyDocument::file_name string, or variant
194 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
195 * match @c "/name").
197 * @param utf8_filename The filename to search (in UTF-8 encoding).
199 * @return @transfer{none} @nullable The matching document, or @c NULL.
200 * @see document_find_by_real_path().
202 GEANY_API_SYMBOL
203 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
205 guint i;
206 GeanyDocument *doc;
207 gchar *realname;
209 g_return_val_if_fail(utf8_filename != NULL, NULL);
211 /* First search GeanyDocument::file_name, so we can find documents with a
212 * filename set but not saved on disk, like vcdiff produces */
213 for (i = 0; i < documents_array->len; i++)
215 doc = documents[i];
217 if (! doc->is_valid || doc->file_name == NULL)
218 continue;
220 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
222 return doc;
225 /* Now try matching based on the realpath(), which is unique per file on disk */
226 realname = get_real_path_from_utf8(utf8_filename);
227 doc = document_find_by_real_path(realname);
228 g_free(realname);
229 return doc;
233 /* returns the document which has sci, or NULL. */
234 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
236 guint i;
238 g_return_val_if_fail(sci != NULL, NULL);
240 for (i = 0; i < documents_array->len; i++)
242 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
243 return documents[i];
245 return NULL;
249 /** Lookup an old document by its ID.
250 * Useful when the corresponding document may have been closed since the
251 * ID was retrieved.
252 * @param id The ID of the document to find
253 * @return @transfer{none} @c NULL if the document is no longer open.
255 * Example:
256 * @code
257 * static guint id;
258 * GeanyDocument *doc = ...;
259 * id = doc->id; // store ID
260 * ...
261 * // time passes - the document may have been closed by now
262 * GeanyDocument *doc = document_find_by_id(id);
263 * gboolean still_open = (doc != NULL);
264 * @endcode
265 * @since 1.25. */
266 GEANY_API_SYMBOL
267 GeanyDocument *document_find_by_id(guint id)
269 guint i;
271 if (!id)
272 return NULL;
274 foreach_document(i)
276 if (documents[i]->id == id)
277 return documents[i];
279 return NULL;
283 /* gets the widget the main_widgets.notebook consider is its child for this document */
284 static GtkWidget *document_get_notebook_child(GeanyDocument *doc)
286 GtkWidget *parent;
287 GtkWidget *child;
289 g_return_val_if_fail(doc != NULL, NULL);
291 child = GTK_WIDGET(doc->editor->sci);
292 parent = gtk_widget_get_parent(child);
293 /* search for the direct notebook child, mirroring document_get_from_page() */
294 while (parent && ! GTK_IS_NOTEBOOK(parent))
296 child = parent;
297 parent = gtk_widget_get_parent(child);
300 return child;
304 /** Gets the notebook page index for a document.
305 * @param doc The document.
306 * @return The index.
307 * @since 0.19 */
308 GEANY_API_SYMBOL
309 gint document_get_notebook_page(GeanyDocument *doc)
311 GtkWidget *child = document_get_notebook_child(doc);
313 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
318 * Recursively searches a containers children until it finds a
319 * Scintilla widget, or NULL if one was not found.
321 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
323 ScintillaObject *sci = NULL;
324 GList *children, *iter;
326 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
328 children = gtk_container_get_children(GTK_CONTAINER(container));
329 for (iter = children; iter != NULL; iter = g_list_next(iter))
331 if (IS_SCINTILLA(iter->data))
333 sci = SCINTILLA(iter->data);
334 break;
336 else if (GTK_IS_CONTAINER(iter->data))
338 sci = locate_sci_in_container(iter->data);
339 if (IS_SCINTILLA(sci))
340 break;
341 sci = NULL;
344 g_list_free(children);
346 return sci;
350 /* Finds the document for the given notebook page widget */
351 GeanyDocument *document_get_from_notebook_child(GtkWidget *page)
353 ScintillaObject *sci;
355 g_return_val_if_fail(GTK_IS_BOX(page), NULL);
357 sci = locate_sci_in_container(page);
358 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
360 return document_find_by_sci(sci);
365 * Finds the document for the given notebook page @a page_num.
367 * @param page_num The notebook page number to search.
369 * @return @transfer{none} @nullable The corresponding document for the given notebook page, or @c NULL.
371 GEANY_API_SYMBOL
372 GeanyDocument *document_get_from_page(guint page_num)
374 GtkWidget *parent;
376 if (page_num >= documents_array->len)
377 return NULL;
379 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
381 return document_get_from_notebook_child(parent);
386 * Finds the current document.
388 * @return @transfer{none} @nullable A pointer to the current document or @c NULL if there are no opened documents.
390 GEANY_API_SYMBOL
391 GeanyDocument *document_get_current(void)
393 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
395 if (cur_page == -1)
396 return NULL;
397 else
398 return document_get_from_page((guint) cur_page);
402 void document_init_doclist(void)
404 documents_array = g_ptr_array_new();
408 void document_finalize(void)
410 guint i;
412 for (i = 0; i < documents_array->len; i++)
413 g_free(documents[i]);
414 g_ptr_array_free(documents_array, TRUE);
419 * Returns the last part of the filename of the given GeanyDocument. The result is also
420 * truncated to a maximum of @a length characters in case the filename is very long.
422 * @param doc The document to use.
423 * @param length The length of the resulting string or -1 to use a default value.
425 * @return The ellipsized last part of the filename of @a doc, should be freed when no
426 * longer needed.
428 * @since 0.17
430 /* TODO make more use of this */
431 GEANY_API_SYMBOL
432 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
434 gchar *base_name, *short_name;
436 g_return_val_if_fail(doc != NULL, NULL);
438 if (length < 0)
439 length = 30;
441 base_name = g_path_get_basename(DOC_FILENAME(doc));
442 short_name = utils_str_middle_truncate(base_name, (guint)length);
444 g_free(base_name);
446 return short_name;
450 void document_update_tab_label(GeanyDocument *doc)
452 gchar *short_name;
453 GtkWidget *parent;
455 g_return_if_fail(doc != NULL);
457 short_name = document_get_basename_for_display(doc, -1);
459 /* we need to use the event box for the tooltip, labels don't get the necessary events */
460 parent = gtk_widget_get_parent(doc->priv->tab_label);
461 parent = gtk_widget_get_parent(parent);
463 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
465 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
467 g_free(short_name);
472 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
473 * according to the document's save state.
474 * This is called by Geany mostly when opening or saving files.
476 * @param doc The document to use.
477 * @param changed Whether the document state should indicate changes have been made.
479 GEANY_API_SYMBOL
480 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
482 g_return_if_fail(doc != NULL);
484 doc->changed = changed;
486 if (! main_status.quitting)
488 ui_update_tab_status(doc);
489 ui_save_buttons_toggle(changed);
490 ui_set_window_title(doc);
491 ui_update_statusbar(doc, -1);
496 /* returns the next free place in the document list,
497 * or -1 if the documents_array is full */
498 static gint document_get_new_idx(void)
500 guint i;
502 for (i = 0; i < documents_array->len; i++)
504 if (documents[i]->editor == NULL)
506 return (gint) i;
509 return -1;
513 static void queue_colourise(GeanyDocument *doc)
515 /* Colourise the editor before it is next drawn */
516 doc->priv->colourise_needed = TRUE;
518 /* If the editor doesn't need drawing (e.g. after saving the current
519 * document), we need to force a redraw, so the expose event is triggered.
520 * This ensures we don't start colourising before all documents are opened/saved,
521 * only once the editor is drawn. */
522 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
526 #ifdef USE_GIO_FILEMON
527 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
528 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
529 GeanyDocument *doc)
531 g_return_if_fail(doc != NULL);
533 if (file_prefs.disk_check_timeout == 0)
534 return;
536 geany_debug("%s: event: %d previous file status: %d",
537 G_STRFUNC, event, doc->priv->file_disk_status);
538 switch (event)
540 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
542 if (doc->priv->file_disk_status == FILE_IGNORE)
543 doc->priv->file_disk_status = FILE_OK;
544 else
545 doc->priv->file_disk_status = FILE_CHANGED;
546 g_message("%s: FILE_CHANGED", G_STRFUNC);
547 break;
549 case G_FILE_MONITOR_EVENT_DELETED:
551 doc->priv->file_disk_status = FILE_CHANGED;
552 g_message("%s: FILE_MISSING", G_STRFUNC);
553 break;
555 default:
556 break;
558 if (doc->priv->file_disk_status != FILE_OK)
560 ui_update_tab_status(doc);
563 #endif
566 static void document_stop_file_monitoring(GeanyDocument *doc)
568 g_return_if_fail(doc != NULL);
570 if (doc->priv->monitor != NULL)
572 g_object_unref(doc->priv->monitor);
573 doc->priv->monitor = NULL;
578 static void monitor_file_setup(GeanyDocument *doc)
580 g_return_if_fail(doc != NULL);
581 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
582 * doesn't work at all for remote files and legacy polling is too slow. */
583 if (! doc->priv->is_remote)
585 #ifdef USE_GIO_FILEMON
586 gchar *locale_filename;
588 /* stop any previous monitoring */
589 document_stop_file_monitoring(doc);
591 locale_filename = utils_get_locale_from_utf8(doc->file_name);
592 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
594 /* get a file monitor and connect to the 'changed' signal */
595 GFile *file = g_file_new_for_path(locale_filename);
596 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
597 g_signal_connect(doc->priv->monitor, "changed",
598 G_CALLBACK(monitor_file_changed_cb), doc);
600 /* we set the rate limit according to the GUI pref but it's most probably not used */
601 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
603 g_object_unref(file);
605 g_free(locale_filename);
606 #endif
608 doc->priv->file_disk_status = FILE_OK;
612 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
614 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
615 if (DOC_VALID(doc))
617 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
618 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
620 if (source_widget == NULL)
621 source_widget = doc->priv->tag_tree;
623 if (focusw == source_widget)
624 gtk_widget_grab_focus(sci);
629 static gboolean on_idle_focus(gpointer doc)
631 document_try_focus(doc, NULL);
632 return FALSE;
636 /* Creates a new document and editor, adding a tab in the notebook.
637 * @return The created document */
638 static GeanyDocument *document_create(const gchar *utf8_filename)
640 GeanyDocument *doc;
641 gint new_idx;
642 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
644 if (cur_pages == 1)
646 doc = document_get_current();
647 /* remove the empty document first */
648 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
649 /* prevent immediately opening another new doc with
650 * new_document_after_close pref */
651 remove_page(0);
654 new_idx = document_get_new_idx();
655 if (new_idx == -1) /* expand the array, no free places */
657 doc = g_new0(GeanyDocument, 1);
659 new_idx = documents_array->len;
660 g_ptr_array_add(documents_array, doc);
663 doc = documents[new_idx];
665 /* initialize default document settings */
666 doc->priv = g_new0(GeanyDocumentPrivate, 1);
667 doc->id = ++doc_id_counter;
668 doc->index = new_idx;
669 doc->file_name = g_strdup(utf8_filename);
670 doc->editor = editor_create(doc);
671 #ifndef USE_GIO_FILEMON
672 doc->priv->last_check = time(NULL);
673 #endif
675 sidebar_openfiles_add(doc); /* sets doc->iter */
677 notebook_new_tab(doc);
679 /* select document in sidebar */
681 GtkTreeSelection *sel;
683 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
684 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
687 ui_document_buttons_update();
689 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
690 return doc;
695 * Closes the given document.
697 * @param doc The document to remove.
699 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
701 * @since 0.15
703 GEANY_API_SYMBOL
704 gboolean document_close(GeanyDocument *doc)
706 g_return_val_if_fail(doc, FALSE);
708 return document_remove_page(document_get_notebook_page(doc));
712 /* Call document_remove_page() instead, this is only needed for document_create()
713 * to prevent re-opening a new document when the last document is closed (if enabled). */
714 static gboolean remove_page(guint page_num)
716 GeanyDocument *doc = document_get_from_page(page_num);
718 g_return_val_if_fail(doc != NULL, FALSE);
720 if (doc->changed && ! dialogs_show_unsaved_file(doc))
721 return FALSE;
723 /* tell any plugins that the document is about to be closed */
724 g_signal_emit_by_name(geany_object, "document-close", doc);
726 /* Checking real_path makes it likely the file exists on disk */
727 if (! main_status.closing_all && doc->real_path != NULL)
728 ui_add_recent_document(doc);
730 doc->is_valid = FALSE;
731 doc->id = 0;
733 if (main_status.quitting)
735 /* we need to destroy the ScintillaWidget so our handlers on it are
736 * disconnected before we free any data they may use (like the editor).
737 * when not quitting, this is handled by removing the notebook page. */
738 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
740 else
742 notebook_remove_page(page_num);
743 sidebar_remove_document(doc);
744 navqueue_remove_file(doc->file_name);
745 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
747 g_free(doc->encoding);
748 g_free(doc->priv->saved_encoding.encoding);
749 g_free(doc->file_name);
750 g_free(doc->real_path);
751 if (doc->tm_file)
753 tm_workspace_remove_source_file(doc->tm_file);
754 tm_source_file_free(doc->tm_file);
757 if (doc->priv->tag_tree)
758 gtk_widget_destroy(doc->priv->tag_tree);
760 editor_destroy(doc->editor);
761 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
763 document_stop_file_monitoring(doc);
765 document_undo_clear(doc);
767 g_free(doc->priv);
769 /* reset document settings to defaults for re-use */
770 memset(doc, 0, sizeof(GeanyDocument));
772 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
774 sidebar_update_tag_list(NULL, FALSE);
775 ui_set_window_title(NULL);
776 ui_save_buttons_toggle(FALSE);
777 ui_update_popup_reundo_items(NULL);
778 ui_document_buttons_update();
779 build_menu_update(NULL);
781 return TRUE;
786 * Removes the given notebook tab at @a page_num and clears all related information
787 * in the document list.
789 * @param page_num The notebook page number to remove.
791 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
793 GEANY_API_SYMBOL
794 gboolean document_remove_page(guint page_num)
796 gboolean done = remove_page(page_num);
798 if (done && ui_prefs.new_document_after_close)
799 document_new_file_if_non_open();
801 return done;
805 /* used to keep a record of the unchanged document state encoding */
806 static void store_saved_encoding(GeanyDocument *doc)
808 g_free(doc->priv->saved_encoding.encoding);
809 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
810 doc->priv->saved_encoding.has_bom = doc->has_bom;
814 /* Opens a new empty document only if there are no other documents open */
815 GeanyDocument *document_new_file_if_non_open(void)
817 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
818 return document_new_file(NULL, NULL, NULL);
820 return NULL;
825 * Creates a new document.
826 * Line endings in @a text will be converted to the default setting.
827 * Afterwards, the @c "document-new" signal is emitted for plugins.
829 * @param utf8_filename @nullable The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
830 * @param ft @nullable The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
831 * @param text @nullable The initial content of the file (in UTF-8 encoding), or @c NULL.
833 * @return @transfer{none} The new document.
835 GEANY_API_SYMBOL
836 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
838 GeanyDocument *doc;
840 if (utf8_filename && g_path_is_absolute(utf8_filename))
842 gchar *tmp;
843 tmp = utils_strdupa(utf8_filename); /* work around const */
844 utils_tidy_path(tmp);
845 utf8_filename = tmp;
847 doc = document_create(utf8_filename);
849 g_assert(doc != NULL);
851 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
852 if (text)
854 GString *template = g_string_new(text);
855 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
857 sci_set_text(doc->editor->sci, template->str);
858 g_string_free(template, TRUE);
860 else
861 sci_clear_all(doc->editor->sci);
863 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
865 sci_set_undo_collection(doc->editor->sci, TRUE);
866 sci_empty_undo_buffer(doc->editor->sci);
868 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
869 /* store the opened encoding for undo/redo */
870 store_saved_encoding(doc);
872 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
873 ft = filetypes_detect_from_document(doc);
875 document_set_filetype(doc, ft); /* also re-parses tags */
877 /* now the document is fully ready, display it (see notebook_new_tab()) */
878 gtk_widget_show(document_get_notebook_child(doc));
880 ui_set_window_title(doc);
881 build_menu_update(doc);
882 document_set_text_changed(doc, FALSE);
883 ui_document_show_hide(doc); /* update the document menu */
885 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
886 /* bring it in front, jump to the start and grab the focus */
887 editor_goto_pos(doc->editor, 0, FALSE);
888 document_try_focus(doc, NULL);
890 #ifdef USE_GIO_FILEMON
891 monitor_file_setup(doc);
892 #else
893 doc->priv->mtime = 0;
894 #endif
896 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
897 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
899 g_signal_emit_by_name(geany_object, "document-new", doc);
901 msgwin_status_add(_("New file \"%s\" opened."),
902 DOC_FILENAME(doc));
904 return doc;
909 * Opens a document specified by @a locale_filename.
910 * Afterwards, the @c "document-open" signal is emitted for plugins.
912 * @param locale_filename The filename of the document to load, in locale encoding.
913 * @param readonly Whether to open the document in read-only mode.
914 * @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
915 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
917 * @return @transfer{none} @nullable The document opened or @c NULL.
919 GEANY_API_SYMBOL
920 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
921 GeanyFiletype *ft, const gchar *forced_enc)
923 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
927 typedef struct
929 gchar *data; /* null-terminated file data */
930 gsize len; /* string length of data */
931 gchar *enc;
932 gboolean bom;
933 time_t mtime; /* modification time, read by stat::st_mtime */
934 gboolean readonly;
935 } FileData;
938 static gboolean get_mtime(const gchar *locale_filename, time_t *time)
940 GError *error = NULL;
941 const gchar *err_msg = NULL;
943 if (USE_GIO_FILE_OPERATIONS)
945 GFile *file = g_file_new_for_path(locale_filename);
946 GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, NULL, &error);
948 if (info)
950 GTimeVal timeval;
952 g_file_info_get_modification_time(info, &timeval);
953 g_object_unref(info);
954 *time = timeval.tv_sec;
956 else if (error)
957 err_msg = error->message;
959 g_object_unref(file);
961 else
963 GStatBuf st;
965 if (g_stat(locale_filename, &st) == 0)
966 *time = st.st_mtime;
967 else
968 err_msg = g_strerror(errno);
971 if (err_msg)
973 gchar *utf8_filename = utils_get_utf8_from_locale(locale_filename);
975 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
976 utf8_filename, err_msg);
977 g_free(utf8_filename);
980 if (error)
981 g_error_free(error);
983 return err_msg == NULL;
987 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
988 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
989 FileData *filedata, const gchar *forced_enc)
991 GError *err = NULL;
993 filedata->data = NULL;
994 filedata->len = 0;
995 filedata->enc = NULL;
996 filedata->bom = FALSE;
997 filedata->readonly = FALSE;
999 if (!get_mtime(locale_filename, &filedata->mtime))
1000 return FALSE;
1002 if (USE_GIO_FILE_OPERATIONS)
1004 GFile *file = g_file_new_for_path(locale_filename);
1006 g_file_load_contents(file, NULL, &filedata->data, &filedata->len, NULL, &err);
1007 g_object_unref(file);
1009 else
1010 g_file_get_contents(locale_filename, &filedata->data, &filedata->len, &err);
1012 if (err)
1014 ui_set_statusbar(TRUE, "%s", err->message);
1015 g_error_free(err);
1016 return FALSE;
1019 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
1020 &filedata->enc, &filedata->bom, &filedata->readonly))
1022 if (forced_enc)
1024 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
1025 display_filename, forced_enc);
1027 else
1029 ui_set_statusbar(TRUE,
1030 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1031 display_filename);
1033 g_free(filedata->data);
1034 return FALSE;
1037 if (filedata->readonly)
1039 const gchar *warn_msg = _(
1040 "The file \"%s\" could not be opened properly and has been truncated. " \
1041 "This can occur if the file contains a NULL byte. " \
1042 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1044 if (main_status.main_window_realized)
1045 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
1047 ui_set_statusbar(TRUE, warn_msg, display_filename);
1050 return TRUE;
1054 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1055 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1056 * if cl_options.goto_column is set.
1058 * returns the new position which may have changed */
1059 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1061 if (cl_options.goto_line >= 0)
1062 { /* goto line which was specified on command line and then undefine the line */
1063 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1064 editor->scroll_percent = 0.5F;
1065 cl_options.goto_line = -1;
1067 else if (pos > 0)
1069 sci_set_current_position(editor->sci, pos, FALSE);
1070 editor->scroll_percent = 0.5F;
1073 if (cl_options.goto_column >= 0)
1074 { /* goto column which was specified on command line and then undefine the column */
1076 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1077 sci_set_current_position(editor->sci, new_pos, FALSE);
1078 editor->scroll_percent = 0.5F;
1079 cl_options.goto_column = -1;
1080 return new_pos;
1082 return sci_get_current_position(editor->sci);
1086 /* Count lines that start with some hard tabs then a soft tab. */
1087 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1089 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1090 ScintillaObject *sci = editor->sci;
1091 gsize count = 0;
1092 struct Sci_TextToFind ttf;
1093 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
1094 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1096 g_free(soft_tab);
1098 ttf.chrg.cpMin = 0;
1099 ttf.chrg.cpMax = sci_get_length(sci);
1100 ttf.lpstrText = regex;
1101 while (1)
1103 gint pos;
1105 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1106 if (pos == -1)
1107 break; /* no more matches */
1108 count++;
1109 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1111 g_free(regex);
1112 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1113 return count > sci_get_line_count(sci) * 0.02;
1117 /* Detect the indent type based on counting the leading indent characters for each line.
1118 * Returns whether detection succeeded, and the detected type in *type_ upon success */
1119 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
1121 GeanyEditor *editor = doc->editor;
1122 ScintillaObject *sci = editor->sci;
1123 gint line, line_count;
1124 gsize tabs = 0, spaces = 0;
1126 if (detect_tabs_and_spaces(editor))
1128 *type_ = GEANY_INDENT_TYPE_BOTH;
1129 return TRUE;
1132 line_count = sci_get_line_count(sci);
1133 for (line = 0; line < line_count; line++)
1135 gint pos = sci_get_position_from_line(sci, line);
1136 gchar c;
1138 /* most code will have indent total <= 24, otherwise it's more likely to be
1139 * alignment than indentation */
1140 if (sci_get_line_indentation(sci, line) > 24)
1141 continue;
1143 c = sci_get_char_at(sci, pos);
1144 if (c == '\t')
1145 tabs++;
1146 /* check for at least 2 spaces */
1147 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1148 spaces++;
1150 if (spaces == 0 && tabs == 0)
1151 return FALSE;
1153 /* the factors may need to be tweaked */
1154 if (spaces > tabs * 4)
1155 *type_ = GEANY_INDENT_TYPE_SPACES;
1156 else if (tabs > spaces * 4)
1157 *type_ = GEANY_INDENT_TYPE_TABS;
1158 else
1159 *type_ = GEANY_INDENT_TYPE_BOTH;
1161 return TRUE;
1165 /* Detect the indent width based on counting the leading indent characters for each line.
1166 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1167 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1169 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1170 ScintillaObject *sci = editor->sci;
1171 gint line, line_count;
1172 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1173 gint count, width, i;
1175 /* can't easily detect the supposed width of a tab, guess the default is OK */
1176 if (type == GEANY_INDENT_TYPE_TABS)
1177 return FALSE;
1179 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1180 sci_set_tab_width(sci, 8);
1182 line_count = sci_get_line_count(sci);
1183 for (line = 0; line < line_count; line++)
1185 gint pos = sci_get_line_indent_position(sci, line);
1187 /* We probably don't have style info yet, because we're generally called just after
1188 * the document got created, so we can't use highlighting_is_code_style().
1189 * That's not good, but the assumption below that concerning lines start with an
1190 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1191 * without removing too much legitimate lines. */
1192 if (sci_get_char_at(sci, pos) == '*')
1193 continue;
1195 width = sci_get_line_indentation(sci, line);
1196 /* most code will have indent total <= 24, otherwise it's more likely to be
1197 * alignment than indentation */
1198 if (width > 24)
1199 continue;
1200 /* < 2 is no indentation */
1201 if (width < 2)
1202 continue;
1204 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1206 if ((width % (i + 2)) == 0)
1207 widths[i]++;
1210 count = 0;
1211 width = iprefs->width;
1212 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1214 /* give large indents higher weight not to be fooled by spurious indents */
1215 if (widths[i] >= count * 1.5)
1217 width = i + 2;
1218 count = widths[i];
1222 if (count == 0)
1223 return FALSE;
1225 *width_ = width;
1226 return TRUE;
1230 /* same as detect_indent_width() but uses editor's indent type */
1231 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1233 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1237 void document_apply_indent_settings(GeanyDocument *doc)
1239 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1240 GeanyIndentType type = iprefs->type;
1241 gint width = iprefs->width;
1243 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1245 if (type != iprefs->type)
1247 const gchar *name = NULL;
1249 switch (type)
1251 case GEANY_INDENT_TYPE_SPACES:
1252 name = _("Spaces");
1253 break;
1254 case GEANY_INDENT_TYPE_TABS:
1255 name = _("Tabs");
1256 break;
1257 case GEANY_INDENT_TYPE_BOTH:
1258 name = _("Tabs and Spaces");
1259 break;
1261 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1262 * and Spaces), the second one is the filename */
1263 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1264 DOC_FILENAME(doc));
1267 else if (doc->file_type->indent_type > -1)
1268 type = doc->file_type->indent_type;
1270 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1272 if (width != iprefs->width)
1274 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1275 DOC_FILENAME(doc));
1278 else if (doc->file_type->indent_width > -1)
1279 width = doc->file_type->indent_width;
1281 editor_set_indent(doc->editor, type, width);
1285 void document_show_tab(GeanyDocument *doc)
1287 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1288 document_get_notebook_page(doc));
1292 /* To open a new file, set doc to NULL; filename should be locale encoded.
1293 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1294 * pos is the cursor position, which can be overridden by --line and --column.
1295 * forced_enc can be NULL to detect the file encoding.
1296 * Returns: doc of the opened file or NULL if an error occurred. */
1297 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1298 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1300 gint editor_mode;
1301 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1302 gchar *utf8_filename = NULL;
1303 gchar *display_filename = NULL;
1304 gchar *locale_filename = NULL;
1305 GeanyFiletype *use_ft;
1306 FileData filedata;
1307 UndoReloadData *undo_reload_data;
1308 gboolean add_undo_reload_action;
1310 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1312 if (reload)
1314 utf8_filename = g_strdup(doc->file_name);
1315 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1317 else
1319 /* filename must not be NULL when opening a file */
1320 g_return_val_if_fail(filename, NULL);
1322 #ifdef G_OS_WIN32
1323 /* if filename is a shortcut, try to resolve it */
1324 locale_filename = win32_get_shortcut_target(filename);
1325 #else
1326 locale_filename = g_strdup(filename);
1327 #endif
1328 /* remove relative junk */
1329 utils_tidy_path(locale_filename);
1331 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1332 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1334 /* if file is already open, switch to it and go */
1335 doc = document_find_by_filename(utf8_filename);
1336 if (doc != NULL)
1338 ui_add_recent_document(doc); /* either add or reorder recent item */
1339 /* show the doc before reload dialog */
1340 document_show_tab(doc);
1341 document_check_disk_status(doc, TRUE); /* force a file changed check */
1344 if (reload || doc == NULL)
1345 { /* doc possibly changed */
1346 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1348 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1350 g_free(display_filename);
1351 g_free(utf8_filename);
1352 g_free(locale_filename);
1353 return NULL;
1356 if (! reload)
1358 doc = document_create(utf8_filename);
1359 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1361 /* file exists on disk, set real_path */
1362 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1364 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1365 monitor_file_setup(doc);
1368 if (! reload || ! file_prefs.keep_edit_history_on_reload)
1370 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1371 sci_empty_undo_buffer(doc->editor->sci);
1372 undo_reload_data = NULL;
1374 else
1376 undo_reload_data = (UndoReloadData*) g_malloc(sizeof(UndoReloadData));
1378 /* We will be adding a UNDO_RELOAD action to the undo stack that undoes
1379 * this reload. To do that, we keep collecting undo actions during
1380 * reloading, and at the end add an UNDO_RELOAD action that performs
1381 * all these actions in bulk. To keep track of how many undo actions
1382 * were added during this time, we compare the current undo-stack height
1383 * with its height at the end of the process. Note that g_trash_stack_height()
1384 * is O(N), which is a little ugly, but this seems like the most maintainable
1385 * option. */
1386 undo_reload_data->actions_count = g_trash_stack_height(&doc->priv->undo_actions);
1388 /* We use add_undo_reload_action to track any changes to the document that
1389 * require adding an undo action to revert the reload, but that do not
1390 * generate an undo action themselves. */
1391 add_undo_reload_action = FALSE;
1394 /* add the text to the ScintillaObject */
1395 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1396 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1397 queue_colourise(doc); /* Ensure the document gets colourised. */
1399 /* detect & set line endings */
1400 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1401 if (undo_reload_data)
1403 undo_reload_data->eol_mode = editor_get_eol_char_mode(doc->editor);
1404 /* Force adding an undo-reload action if the EOL mode changed. */
1405 if (editor_mode != undo_reload_data->eol_mode)
1406 add_undo_reload_action = TRUE;
1408 sci_set_eol_mode(doc->editor->sci, editor_mode);
1409 g_free(filedata.data);
1411 sci_set_undo_collection(doc->editor->sci, TRUE);
1413 /* If reloading and the current and new encodings or BOM states differ,
1414 * add appropriate undo actions. */
1415 if (undo_reload_data)
1417 if (! utils_str_equal(doc->encoding, filedata.enc))
1418 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
1419 if (doc->has_bom != filedata.bom)
1420 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
1423 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1424 g_free(doc->encoding); /* if reloading, free old encoding */
1425 doc->encoding = filedata.enc;
1426 doc->has_bom = filedata.bom;
1427 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1429 doc->readonly = readonly || filedata.readonly;
1430 sci_set_readonly(doc->editor->sci, doc->readonly);
1431 doc->priv->protected = 0;
1433 /* update line number margin width */
1434 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1435 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1437 if (! reload)
1440 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1441 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1442 doc->editor);
1444 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1446 else
1447 { /* reloading */
1448 if (undo_reload_data)
1450 /* Calculate the number of undo actions that are part of the reloading
1451 * process, and add the UNDO_RELOAD action. */
1452 undo_reload_data->actions_count =
1453 g_trash_stack_height(&doc->priv->undo_actions) - undo_reload_data->actions_count;
1455 /* We only add an undo-reload action if the document has actually changed.
1456 * At the time of writing, this condition is moot because sci_set_text
1457 * generates an undo action even when the text hasn't really changed, so
1458 * actions_count is always greater than zero. In the future this might change.
1459 * It's arguable whether we should add an undo-reload action unconditionally,
1460 * especially since it's possible (if unlikely) that there had only
1461 * been "invisible" changes to the document, such as changes in encoding and
1462 * EOL mode, but for the time being that's how we roll. */
1463 if (undo_reload_data->actions_count > 0 || add_undo_reload_action)
1464 document_undo_add(doc, UNDO_RELOAD, undo_reload_data);
1465 else
1466 g_free(undo_reload_data);
1468 /* We didn't save the document per-se, but its contents are now
1469 * synchronized with the file on disk, hence set a save point here.
1470 * We need to do this in this case only, because we don't clear
1471 * Scintilla's undo stack. */
1472 sci_set_savepoint(doc->editor->sci);
1474 else
1475 document_undo_clear(doc);
1477 use_ft = ft;
1479 /* update taglist, typedef keywords and build menu if necessary */
1480 document_set_filetype(doc, use_ft);
1482 /* set indentation settings after setting the filetype */
1483 if (reload)
1484 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1485 else
1486 document_apply_indent_settings(doc);
1488 document_set_text_changed(doc, FALSE); /* also updates tab state */
1489 ui_document_show_hide(doc); /* update the document menu */
1491 /* finally add current file to recent files menu, but not the files from the last session */
1492 if (! main_status.opening_session_files)
1493 ui_add_recent_document(doc);
1495 if (reload)
1497 g_signal_emit_by_name(geany_object, "document-reload", doc);
1498 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1500 else
1502 g_signal_emit_by_name(geany_object, "document-open", doc);
1503 /* For translators: this is the status window message for opening a file. %d is the number
1504 * of the newly opened file, %s indicates whether the file is opened read-only
1505 * (it is replaced with the string ", read-only"). */
1506 msgwin_status_add(_("File %s opened(%d%s)."),
1507 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1508 (readonly) ? _(", read-only") : "");
1511 /* now the document is fully ready, display it (see notebook_new_tab()) */
1512 gtk_widget_show(document_get_notebook_child(doc));
1515 g_free(display_filename);
1516 g_free(utf8_filename);
1517 g_free(locale_filename);
1519 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1520 pos = set_cursor_position(doc->editor, pos);
1521 /* now bring the file in front */
1522 editor_goto_pos(doc->editor, pos, FALSE);
1524 /* finally, let the editor widget grab the focus so you can start coding
1525 * right away */
1526 g_idle_add(on_idle_focus, doc);
1527 return doc;
1531 /* Takes a new line separated list of filename URIs and opens each file.
1532 * length is the length of the string */
1533 void document_open_file_list(const gchar *data, gsize length)
1535 guint i;
1536 gchar *filename;
1537 gchar **list;
1539 g_return_if_fail(data != NULL);
1541 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1543 /* stop at the end or first empty item, because last item is empty but not null */
1544 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1546 filename = utils_get_path_from_uri(list[i]);
1547 if (filename == NULL)
1548 continue;
1549 document_open_file(filename, FALSE, NULL, NULL);
1550 g_free(filename);
1553 g_strfreev(list);
1558 * Opens each file in the list @a filenames.
1559 * Internally, document_open_file() is called for every list item.
1561 * @param filenames @elementtype{filename} A list of filenames to load, in locale encoding.
1562 * @param readonly Whether to open the document in read-only mode.
1563 * @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
1564 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1566 GEANY_API_SYMBOL
1567 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1568 const gchar *forced_enc)
1570 const GSList *item;
1572 for (item = filenames; item != NULL; item = g_slist_next(item))
1574 document_open_file(item->data, readonly, ft, forced_enc);
1579 static void on_keep_edit_history_on_reload_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
1581 if (response_id == GTK_RESPONSE_NO)
1583 file_prefs.keep_edit_history_on_reload = FALSE;
1584 document_reload_force(doc, doc->encoding);
1586 else if (response_id == GTK_RESPONSE_CANCEL)
1588 /* this condition cannot be reached via info bar buttons, but by our code
1589 * to replace this bar with a higher priority one */
1590 file_prefs.show_keep_edit_history_on_reload_msg = TRUE;
1592 doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = NULL;
1593 gtk_widget_destroy(bar);
1598 * Reloads the document with the specified file encoding.
1599 * @a forced_enc or @c NULL to auto-detect the file encoding.
1601 * @param doc The document to reload.
1602 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1604 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1606 GEANY_API_SYMBOL
1607 gboolean document_reload_force(GeanyDocument *doc, const gchar *forced_enc)
1609 gint pos = 0;
1610 GeanyDocument *new_doc;
1611 GtkWidget *bar;
1613 g_return_val_if_fail(doc != NULL, FALSE);
1615 /* Use cancel because the response handler would call this recursively */
1616 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1617 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1619 /* try to set the cursor to the position before reloading */
1620 pos = sci_get_current_position(doc->editor->sci);
1621 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1623 if (file_prefs.keep_edit_history_on_reload && file_prefs.show_keep_edit_history_on_reload_msg)
1625 bar = document_show_message(doc, GTK_MESSAGE_INFO,
1626 on_keep_edit_history_on_reload_response,
1627 GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1628 _("Discard history"), GTK_RESPONSE_NO,
1629 NULL, 0, _("The buffer's previous state is stored in the history and "
1630 "undoing restores it. You can disable this by discarding the history upon "
1631 "reload. This message will not be displayed again but "
1632 "Your choice can be changed in the various preferences."),
1633 _("The file has been reloaded."));
1634 doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = bar;
1635 file_prefs.show_keep_edit_history_on_reload_msg = FALSE;
1638 return (new_doc != NULL);
1642 /* also used for reloading when forced_enc is NULL */
1643 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1645 gchar *base_name;
1646 gboolean prompt, result = FALSE;
1648 g_return_val_if_fail(doc != NULL, FALSE);
1650 /* No need to reload "untitled" (non-file-backed) documents */
1651 if (doc->file_name == NULL)
1652 return FALSE;
1654 if (forced_enc == NULL)
1655 forced_enc = doc->encoding;
1657 base_name = g_path_get_basename(doc->file_name);
1658 /* don't prompt if edit history is maintained, or if file hasn't been edited at all */
1659 prompt = !file_prefs.keep_edit_history_on_reload &&
1660 (doc->changed || (document_can_undo(doc) || document_can_redo(doc)));
1662 if (!prompt || dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1663 doc->changed ? _("Any unsaved changes will be lost.") :
1664 _("Undo history will be lost."),
1665 _("Are you sure you want to reload '%s'?"), base_name))
1667 result = document_reload_force(doc, forced_enc);
1668 if (forced_enc != NULL)
1669 ui_update_statusbar(doc, -1);
1671 g_free(base_name);
1672 return result;
1676 static void document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1678 #ifndef USE_GIO_FILEMON
1679 g_return_if_fail(doc != NULL);
1681 get_mtime(locale_filename, &doc->priv->mtime); /* get the modification time from file and keep it */
1682 #endif
1686 /* Sets line and column to the given position byte_pos in the document.
1687 * byte_pos is the position counted in bytes, not characters */
1688 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1690 gint i;
1691 gint line_start;
1693 /* for some reason we can use byte count instead of character count here */
1694 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1695 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1696 /* get the column in the line */
1697 *column = byte_pos - line_start;
1699 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1700 * skip one byte(i++) and decrease the column number which is based on byte count */
1701 for (i = line_start; i < (line_start + *column); i++)
1703 if (sci_get_char_at(doc->editor->sci, i) < 0)
1705 (*column)--;
1706 i++;
1712 static void replace_header_filename(GeanyDocument *doc)
1714 gchar *filebase;
1715 gchar *filename;
1716 struct Sci_TextToFind ttf;
1718 g_return_if_fail(doc != NULL);
1719 g_return_if_fail(doc->file_type != NULL);
1721 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1722 if (doc->file_type->extension)
1723 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1724 else
1725 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1727 filename = g_path_get_basename(doc->file_name);
1729 /* only search the first 3 lines */
1730 ttf.chrg.cpMin = 0;
1731 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1732 ttf.lpstrText = filebase;
1734 if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1736 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1737 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1738 sci_replace_target(doc->editor->sci, filename, FALSE);
1740 g_free(filebase);
1741 g_free(filename);
1746 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1747 * you still have to call @ref document_save_file_as() to change the @a doc object.
1748 * It also stops monitoring for file changes to prevent receiving too many file change events
1749 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1751 * @param doc The current document which should be renamed.
1752 * @param new_filename The new filename in UTF-8 encoding.
1754 * @since 0.16
1756 GEANY_API_SYMBOL
1757 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1759 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1760 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1761 gint result;
1763 /* stop file monitoring to avoid getting events for deleting/creating files,
1764 * it's re-setup in document_save_file_as() */
1765 document_stop_file_monitoring(doc);
1767 result = g_rename(old_locale_filename, new_locale_filename);
1768 if (result != 0)
1770 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1771 _("Error renaming file."), g_strerror(errno));
1773 g_free(old_locale_filename);
1774 g_free(new_locale_filename);
1778 static void protect_document(GeanyDocument *doc)
1780 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1781 if (!doc->priv->protected++)
1782 sci_set_readonly(doc->editor->sci, TRUE);
1784 ui_update_tab_status(doc);
1788 static void unprotect_document(GeanyDocument *doc)
1790 g_return_if_fail(doc->priv->protected > 0);
1792 if (!--doc->priv->protected && doc->readonly == FALSE)
1793 sci_set_readonly(doc->editor->sci, FALSE);
1795 ui_update_tab_status(doc);
1799 /* Return TRUE if the document doesn't have a full filename set.
1800 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1801 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1802 * new files. */
1803 gboolean document_need_save_as(GeanyDocument *doc)
1805 g_return_val_if_fail(doc != NULL, FALSE);
1807 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1812 * Saves the document, detecting the filetype.
1814 * @param doc The document for the file to save.
1815 * @param utf8_fname @nullable The new name for the document, in UTF-8, or @c NULL.
1816 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1818 * @see document_save_file().
1820 * @since 0.16
1822 GEANY_API_SYMBOL
1823 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1825 gboolean ret;
1826 gboolean new_file;
1828 g_return_val_if_fail(doc != NULL, FALSE);
1830 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1831 if (utf8_fname != NULL)
1832 SETPTR(doc->file_name, g_strdup(utf8_fname));
1834 /* reset real path, it's retrieved again in document_save() */
1835 SETPTR(doc->real_path, NULL);
1837 /* detect filetype */
1838 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1840 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1842 document_set_filetype(doc, ft);
1843 if (document_get_current() == doc)
1845 ignore_callback = TRUE;
1846 filetypes_select_radio_item(doc->file_type);
1847 ignore_callback = FALSE;
1851 if (new_file)
1853 // assume user wants to throw away read-only setting
1854 sci_set_readonly(doc->editor->sci, FALSE);
1855 doc->readonly = FALSE;
1856 if (doc->priv->protected > 0)
1857 unprotect_document(doc);
1860 replace_header_filename(doc);
1862 ret = document_save_file(doc, TRUE);
1864 /* file monitoring support, add file monitoring after the file has been saved
1865 * to ignore any earlier events */
1866 monitor_file_setup(doc);
1867 doc->priv->file_disk_status = FILE_IGNORE;
1869 if (ret)
1870 ui_add_recent_document(doc);
1871 return ret;
1875 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1877 GError *conv_error = NULL;
1878 gchar* conv_file_contents = NULL;
1879 gsize bytes_read;
1880 gsize conv_len;
1882 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1883 g_return_val_if_fail(len != NULL, FALSE);
1885 /* try to convert it from UTF-8 to original encoding */
1886 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1887 &bytes_read, &conv_len, &conv_error);
1889 if (conv_error != NULL)
1891 gchar *text = g_strdup_printf(
1892 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1893 doc->encoding);
1894 gchar *error_text;
1896 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1898 gint line, column;
1899 gint context_len;
1900 gunichar unic;
1901 /* don't read over the doc length */
1902 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1903 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1904 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1906 /* take only one valid Unicode character from the context and discard the leftover */
1907 unic = g_utf8_get_char_validated(context, -1);
1908 context_len = g_unichar_to_utf8(unic, context);
1909 context[context_len] = '\0';
1910 get_line_column_from_pos(doc, bytes_read, &line, &column);
1912 error_text = g_strdup_printf(
1913 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1914 conv_error->message, context, line + 1, column);
1916 else
1917 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1919 geany_debug("encoding error: %s", conv_error->message);
1920 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1921 g_error_free(conv_error);
1922 g_free(text);
1923 g_free(error_text);
1924 return FALSE;
1926 else
1928 g_free(*data);
1929 *data = conv_file_contents;
1930 *len = conv_len;
1932 return TRUE;
1936 static gchar *write_data_to_disk(const gchar *locale_filename,
1937 const gchar *data, gsize len)
1939 GError *error = NULL;
1941 if (file_prefs.use_safe_file_saving)
1943 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1944 * This is the only option that handles disk space exhaustion. */
1945 if (g_file_set_contents(locale_filename, data, len, &error))
1946 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1948 else if (USE_GIO_FILE_OPERATIONS)
1950 GFile *fp;
1952 /* Use GIO API to save file (GVFS-safe)
1953 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1954 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1955 fp = g_file_new_for_path(locale_filename);
1956 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1957 G_FILE_CREATE_NONE, NULL, NULL, &error);
1958 g_object_unref(fp);
1960 else
1962 FILE *fp;
1963 int save_errno;
1964 gchar *display_name = g_filename_display_name(locale_filename);
1966 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1967 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1968 errno = 0;
1969 fp = g_fopen(locale_filename, "wb");
1970 if (fp == NULL)
1972 save_errno = errno;
1974 g_set_error(&error,
1975 G_FILE_ERROR,
1976 g_file_error_from_errno(save_errno),
1977 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1978 display_name,
1979 g_strerror(save_errno));
1981 else
1983 gsize bytes_written;
1985 errno = 0;
1986 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1988 if (len != bytes_written)
1990 save_errno = errno;
1992 g_set_error(&error,
1993 G_FILE_ERROR,
1994 g_file_error_from_errno(save_errno),
1995 _("Failed to write file '%s': fwrite() failed: %s"),
1996 display_name,
1997 g_strerror(save_errno));
2000 errno = 0;
2001 /* preserve the fwrite() error if any */
2002 if (fclose(fp) != 0 && error == NULL)
2004 save_errno = errno;
2006 g_set_error(&error,
2007 G_FILE_ERROR,
2008 g_file_error_from_errno(save_errno),
2009 _("Failed to close file '%s': fclose() failed: %s"),
2010 display_name,
2011 g_strerror(save_errno));
2015 g_free(display_name);
2017 if (error != NULL)
2019 gchar *msg = g_strdup(error->message);
2020 g_error_free(error);
2021 /* geany will warn about file truncation for unsafe saving below */
2022 return msg;
2024 return NULL;
2028 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
2029 const gchar *data, gsize len)
2031 gchar *err;
2033 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
2034 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
2036 err = write_data_to_disk(locale_filename, data, len);
2037 if (err)
2038 return err;
2040 /* now the file is on disk, set real_path */
2041 if (doc->real_path == NULL)
2043 doc->real_path = tm_get_real_path(locale_filename);
2044 doc->priv->is_remote = utils_is_remote_path(locale_filename);
2045 monitor_file_setup(doc);
2047 return NULL;
2051 static gboolean save_file_handle_infobars(GeanyDocument *doc, gboolean force)
2053 GtkWidget *bar = NULL;
2055 document_show_tab(doc);
2057 if (doc->priv->info_bars[MSG_TYPE_RELOAD])
2059 if (!dialogs_show_question_full(NULL, _("_Overwrite"), GTK_STOCK_CANCEL,
2060 _("Overwrite?"),
2061 _("The file '%s' on the disk is more recent than the current buffer."),
2062 doc->file_name))
2063 return FALSE;
2064 bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
2066 else if (doc->priv->info_bars[MSG_TYPE_RESAVE])
2068 if (!dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
2069 _("Try to resave the file?"),
2070 _("File \"%s\" was not found on disk!"),
2071 doc->file_name))
2072 return FALSE;
2073 bar = doc->priv->info_bars[MSG_TYPE_RESAVE];
2075 else
2077 g_assert_not_reached();
2078 return FALSE;
2080 gtk_info_bar_response(GTK_INFO_BAR(bar), RESPONSE_DOCUMENT_SAVE);
2081 return TRUE;
2086 * Saves the document.
2087 * Also shows the Save As dialog if necessary.
2088 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
2090 * Saving may include replacing tabs with spaces,
2091 * stripping trailing spaces and adding a final new line at the end of the file, depending
2092 * on user preferences. Then the @c "document-before-save" signal is emitted,
2093 * allowing plugins to modify the document before it is saved, and data is
2094 * actually written to disk.
2096 * On successful saving:
2097 * - GeanyDocument::real_path is set.
2098 * - The filetype is set again or auto-detected if it wasn't set yet.
2099 * - The @c "document-save" signal is emitted for plugins.
2101 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
2102 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
2103 * added in Geany 1.22.
2105 * @param doc The document to save.
2106 * @param force Whether to save the file even if it is not modified.
2108 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
2110 GEANY_API_SYMBOL
2111 gboolean document_save_file(GeanyDocument *doc, gboolean force)
2113 gchar *errmsg;
2114 gchar *data;
2115 gsize len;
2116 gchar *locale_filename;
2117 const GeanyFilePrefs *fp;
2119 g_return_val_if_fail(doc != NULL, FALSE);
2121 if (document_need_save_as(doc))
2123 /* ensure doc is the current tab before showing the dialog */
2124 document_show_tab(doc);
2125 return dialogs_show_save_as();
2128 if (!force && !doc->changed)
2129 return FALSE;
2130 if (doc->readonly)
2132 ui_set_statusbar(TRUE,
2133 _("Cannot save read-only document '%s'!"), DOC_FILENAME(doc));
2134 return FALSE;
2136 document_check_disk_status(doc, TRUE);
2137 if (doc->priv->protected)
2138 return save_file_handle_infobars(doc, force);
2140 fp = project_get_file_prefs();
2141 /* replaces tabs with spaces but only if the current file is not a Makefile */
2142 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
2143 editor_replace_tabs(doc->editor, TRUE);
2144 /* strip trailing spaces */
2145 if (fp->strip_trailing_spaces)
2146 editor_strip_trailing_spaces(doc->editor, TRUE);
2147 /* ensure the file has a newline at the end */
2148 if (fp->final_new_line)
2149 editor_ensure_final_newline(doc->editor);
2150 /* ensure newlines are consistent */
2151 if (fp->ensure_convert_new_lines)
2152 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
2154 /* notify plugins which may wish to modify the document before it's saved */
2155 g_signal_emit_by_name(geany_object, "document-before-save", doc);
2157 len = sci_get_length(doc->editor->sci) + 1;
2158 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
2159 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
2160 * encoding, it will be converted to doc->encoding below and this conversion
2161 * also changes the BOM */
2162 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
2163 data[0] = (gchar) 0xef;
2164 data[1] = (gchar) 0xbb;
2165 data[2] = (gchar) 0xbf;
2166 sci_get_text(doc->editor->sci, len, data + 3);
2167 len += 3;
2169 else
2171 data = (gchar*) g_malloc(len);
2172 sci_get_text(doc->editor->sci, len, data);
2175 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
2176 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
2177 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
2179 if (! save_convert_to_encoding(doc, &data, &len))
2181 g_free(data);
2182 return FALSE;
2185 else
2187 len = strlen(data);
2190 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2192 /* ignore file changed notification when the file is written */
2193 doc->priv->file_disk_status = FILE_IGNORE;
2195 /* actually write the content of data to the file on disk */
2196 errmsg = save_doc(doc, locale_filename, data, len);
2197 g_free(data);
2199 if (errmsg != NULL)
2201 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
2203 if (!file_prefs.use_safe_file_saving)
2205 SETPTR(errmsg,
2206 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
2208 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
2209 doc->priv->file_disk_status = FILE_OK;
2210 utils_beep();
2211 g_free(locale_filename);
2212 g_free(errmsg);
2213 return FALSE;
2216 /* store the opened encoding for undo/redo */
2217 store_saved_encoding(doc);
2219 /* ignore the following things if we are quitting */
2220 if (! main_status.quitting)
2222 sci_set_savepoint(doc->editor->sci);
2224 if (file_prefs.disk_check_timeout > 0)
2225 document_update_timestamp(doc, locale_filename);
2227 /* update filetype-related things */
2228 document_set_filetype(doc, doc->file_type);
2230 document_update_tab_label(doc);
2232 msgwin_status_add(_("File %s saved."), doc->file_name);
2233 ui_update_statusbar(doc, -1);
2234 #ifdef HAVE_VTE
2235 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
2236 #endif
2238 g_free(locale_filename);
2240 g_signal_emit_by_name(geany_object, "document-save", doc);
2242 return TRUE;
2246 /* special search function, used from the find entry in the toolbar
2247 * return TRUE if text was found otherwise FALSE
2248 * return also TRUE if text is empty */
2249 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gboolean inc,
2250 gboolean backwards)
2252 gint start_pos, search_pos;
2253 struct Sci_TextToFind ttf;
2255 g_return_val_if_fail(text != NULL, FALSE);
2256 g_return_val_if_fail(doc != NULL, FALSE);
2257 if (! *text)
2258 return TRUE;
2260 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
2261 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
2263 /* search cursor to end or start */
2264 ttf.chrg.cpMin = start_pos;
2265 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
2266 ttf.lpstrText = (gchar *)text;
2267 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2269 /* if no match, search start (or end) to cursor */
2270 if (search_pos == -1)
2272 if (backwards)
2274 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
2275 ttf.chrg.cpMax = start_pos;
2277 else
2279 ttf.chrg.cpMin = 0;
2280 ttf.chrg.cpMax = start_pos + strlen(text);
2282 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2285 if (search_pos != -1)
2287 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
2289 /* unfold maybe folded results */
2290 sci_ensure_line_is_visible(doc->editor->sci, line);
2292 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2293 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2295 if (! editor_line_in_view(doc->editor, line))
2296 { /* we need to force scrolling in case the cursor is outside of the current visible area
2297 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2298 * while searching */
2299 editor_scroll_to_line(doc->editor, -1, 0.3F);
2301 else
2302 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2303 return TRUE;
2305 else
2307 if (! inc)
2309 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2311 utils_beep();
2312 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
2313 return FALSE;
2318 /* General search function, used from the find dialog.
2319 * Returns -1 on failure or the start position of the matching text.
2320 * Will skip past any selection, ignoring it.
2322 * @param text Text to find.
2323 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2325 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2326 GeanyFindFlags flags, gboolean search_backwards, GeanyMatchInfo **match_,
2327 gboolean scroll, GtkWidget *parent)
2329 gint selection_end, selection_start, search_pos;
2331 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2332 if (! *text)
2333 return -1;
2335 /* Sci doesn't support searching backwards with a regex */
2336 if (flags & GEANY_FIND_REGEXP)
2337 search_backwards = FALSE;
2339 if (!original_text)
2340 original_text = text;
2342 selection_start = sci_get_selection_start(doc->editor->sci);
2343 selection_end = sci_get_selection_end(doc->editor->sci);
2344 if ((selection_end - selection_start) > 0)
2345 { /* there's a selection so go to the end */
2346 if (search_backwards)
2347 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2348 else
2349 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2352 sci_set_search_anchor(doc->editor->sci);
2353 if (search_backwards)
2354 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2355 else
2356 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2358 if (search_pos != -1)
2360 /* unfold maybe folded results */
2361 sci_ensure_line_is_visible(doc->editor->sci,
2362 sci_get_line_from_position(doc->editor->sci, search_pos));
2363 if (scroll)
2364 doc->editor->scroll_percent = 0.3F;
2366 else
2368 gint sci_len = sci_get_length(doc->editor->sci);
2370 /* if we just searched the whole text, give up searching. */
2371 if ((selection_end == 0 && ! search_backwards) ||
2372 (selection_end == sci_len && search_backwards))
2374 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2375 utils_beep();
2376 return -1;
2379 /* we searched only part of the document, so ask whether to wraparound. */
2380 if (search_prefs.always_wrap ||
2381 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2382 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2384 gint ret;
2386 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2387 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2388 if (ret == -1)
2389 { /* return to original cursor position if not found */
2390 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2392 return ret;
2395 return search_pos;
2399 /* Replaces the selection if it matches, otherwise just finds the next match.
2400 * Returns: start of replaced text, or -1 if no replacement was made
2402 * @param find_text Text to find.
2403 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2405 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2406 const gchar *replace_text, GeanyFindFlags flags, gboolean search_backwards)
2408 gint selection_end, selection_start, search_pos;
2409 GeanyMatchInfo *match = NULL;
2411 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2413 if (! *find_text)
2414 return -1;
2416 /* Sci doesn't support searching backwards with a regex */
2417 if (flags & GEANY_FIND_REGEXP)
2418 search_backwards = FALSE;
2420 if (!original_find_text)
2421 original_find_text = find_text;
2423 selection_start = sci_get_selection_start(doc->editor->sci);
2424 selection_end = sci_get_selection_end(doc->editor->sci);
2425 if (selection_end == selection_start)
2427 /* no selection so just find the next match */
2428 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2429 return -1;
2431 /* there's a selection so go to the start before finding to search through it
2432 * this ensures there is a match */
2433 if (search_backwards)
2434 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2435 else
2436 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2438 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2439 /* return if the original selected text did not match (at the start of the selection) */
2440 if (search_pos != selection_start)
2442 if (search_pos != -1)
2443 geany_match_info_free(match);
2444 return -1;
2447 if (search_pos != -1)
2449 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2450 /* select the replacement - find text will skip past the selected text */
2451 sci_set_selection_start(doc->editor->sci, search_pos);
2452 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2453 geany_match_info_free(match);
2455 else
2457 /* no match in the selection */
2458 utils_beep();
2460 return search_pos;
2464 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2465 const gchar *original_replace_text)
2467 gchar *filename;
2469 if (count == 0)
2471 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2472 return;
2475 filename = g_path_get_basename(DOC_FILENAME(doc));
2476 ui_set_statusbar(TRUE, ngettext(
2477 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2478 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2479 count), filename, count, original_find_text, original_replace_text);
2480 g_free(filename);
2484 /* Replace all text matches in a certain range within document.
2485 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2486 * or -1 if no text was found.
2487 * scroll_to_match is whether to scroll the last replacement in view (which also
2488 * clears the selection).
2489 * Returns: the number of replacements made. */
2490 static guint
2491 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2492 GeanyFindFlags flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2494 gint count = 0;
2495 struct Sci_TextToFind ttf;
2496 ScintillaObject *sci;
2498 if (new_range_end != NULL)
2499 *new_range_end = -1;
2501 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2503 if (! *find_text || doc->readonly)
2504 return 0;
2506 sci = doc->editor->sci;
2508 ttf.chrg.cpMin = start;
2509 ttf.chrg.cpMax = end;
2510 ttf.lpstrText = (gchar*)find_text;
2512 sci_start_undo_action(sci);
2513 count = search_replace_range(sci, &ttf, flags, replace_text);
2514 sci_end_undo_action(sci);
2516 if (count > 0)
2517 { /* scroll last match in view, will destroy the existing selection */
2518 if (scroll_to_match)
2519 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2521 if (new_range_end != NULL)
2522 *new_range_end = ttf.chrg.cpMax;
2524 return count;
2528 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2529 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2531 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2532 gint max_column = 0, count = 0;
2533 gboolean replaced = FALSE;
2535 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2537 if (! *find_text)
2538 return;
2540 selection_start = sci_get_selection_start(doc->editor->sci);
2541 selection_end = sci_get_selection_end(doc->editor->sci);
2542 /* do we have a selection? */
2543 if ((selection_end - selection_start) == 0)
2545 utils_beep();
2546 return;
2549 selection_mode = sci_get_selection_mode(doc->editor->sci);
2550 selected_lines = sci_get_lines_selected(doc->editor->sci);
2551 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2552 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2554 gint first_line, line;
2556 sci_start_undo_action(doc->editor->sci);
2558 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2559 /* Find the last line with chars selected (not EOL char) */
2560 last_line = sci_get_line_from_position(doc->editor->sci,
2561 selection_end - editor_get_eol_char_len(doc->editor));
2562 last_line = MAX(first_line, last_line);
2563 for (line = first_line; line < (first_line + selected_lines); line++)
2565 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2566 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2568 /* skip line if there is no selection */
2569 if (line_start != INVALID_POSITION)
2571 /* don't let document_replace_range() scroll to match to keep our selection */
2572 gint new_sel_end;
2574 count += document_replace_range(doc, find_text, replace_text, flags,
2575 line_start, line_end, FALSE, &new_sel_end);
2576 if (new_sel_end != -1)
2578 replaced = TRUE;
2579 /* this gets the greatest column within the selection after replacing */
2580 max_column = MAX(max_column,
2581 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2585 sci_end_undo_action(doc->editor->sci);
2587 else /* handle normal line selection */
2589 count += document_replace_range(doc, find_text, replace_text, flags,
2590 selection_start, selection_end, TRUE, &selection_end);
2591 if (selection_end != -1)
2592 replaced = TRUE;
2595 if (replaced)
2596 { /* update the selection for the new endpoint */
2598 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2600 /* now we can scroll to the selection and destroy it because we rebuild it later */
2601 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2603 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2604 * the highest column on the last line. The wrapped selection is completely different
2605 * from the original one, so skip the selection at all */
2606 /* TODO is there a better way to handle the wrapped selection? */
2607 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2608 { /* for keeping and adjusting the selection in multi line rectangle selection we
2609 * need the last line of the original selection and the greatest column number after
2610 * replacing and set the selection end to the last line at the greatest column */
2611 sci_set_selection_start(doc->editor->sci, selection_start);
2612 sci_set_selection_end(doc->editor->sci,
2613 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2614 sci_set_selection_mode(doc->editor->sci, selection_mode);
2617 else
2619 sci_set_selection_start(doc->editor->sci, selection_start);
2620 sci_set_selection_end(doc->editor->sci, selection_end);
2623 else /* no replacements */
2624 utils_beep();
2626 show_replace_summary(doc, count, original_find_text, original_replace_text);
2630 /* returns number of replacements made. */
2631 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2632 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2634 gint len, count;
2635 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2637 if (! *find_text)
2638 return FALSE;
2640 len = sci_get_length(doc->editor->sci);
2641 count = document_replace_range(
2642 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2644 show_replace_summary(doc, count, original_find_text, original_replace_text);
2645 return count;
2650 * Parses or re-parses the document's buffer and updates the type
2651 * keywords and symbol list.
2653 * @param doc The document.
2655 void document_update_tags(GeanyDocument *doc)
2657 guchar *buffer_ptr;
2658 gsize len;
2660 g_return_if_fail(DOC_VALID(doc));
2661 g_return_if_fail(app->tm_workspace != NULL);
2663 /* early out if it's a new file or doesn't support tags */
2664 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2666 /* We must call sidebar_update_tag_list() before returning,
2667 * to ensure that the symbol list is always updated properly (e.g.
2668 * when creating a new document with a partial filename set. */
2669 sidebar_update_tag_list(doc, FALSE);
2670 return;
2673 /* create a new TM file if there isn't one yet */
2674 if (! doc->tm_file)
2676 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2677 const gchar *name;
2679 /* lookup the name rather than using filetype name to support custom filetypes */
2680 name = tm_source_file_get_lang_name(doc->file_type->lang);
2681 doc->tm_file = tm_source_file_new(locale_filename, name);
2682 g_free(locale_filename);
2684 if (doc->tm_file)
2685 tm_workspace_add_source_file_noupdate(doc->tm_file);
2688 /* early out if there's no tm source file and we couldn't create one */
2689 if (doc->tm_file == NULL)
2691 /* We must call sidebar_update_tag_list() before returning,
2692 * to ensure that the symbol list is always updated properly (e.g.
2693 * when creating a new document with a partial filename set. */
2694 sidebar_update_tag_list(doc, FALSE);
2695 return;
2698 /* Parse Scintilla's buffer directly using TagManager
2699 * Note: this buffer *MUST NOT* be modified */
2700 len = sci_get_length(doc->editor->sci);
2701 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2702 tm_workspace_update_source_file_buffer(doc->tm_file, buffer_ptr, len);
2704 sidebar_update_tag_list(doc, TRUE);
2705 document_highlight_tags(doc);
2709 /* Re-highlights type keywords without re-parsing the whole document. */
2710 void document_highlight_tags(GeanyDocument *doc)
2712 GString *keywords_str;
2713 gchar *keywords;
2714 gint keyword_idx;
2716 /* some filetypes support type keywords (such as struct names), but not
2717 * necessarily all filetypes for a particular scintilla lexer. this
2718 * tells us whether the filetype supports keywords, and if so
2719 * which index to use for the scintilla keywords set. */
2720 switch (doc->file_type->id)
2722 case GEANY_FILETYPES_C:
2723 case GEANY_FILETYPES_CPP:
2724 case GEANY_FILETYPES_CS:
2725 case GEANY_FILETYPES_D:
2726 case GEANY_FILETYPES_JAVA:
2727 case GEANY_FILETYPES_OBJECTIVEC:
2728 case GEANY_FILETYPES_VALA:
2729 case GEANY_FILETYPES_RUST:
2730 case GEANY_FILETYPES_GO:
2733 /* index of the keyword set in the Scintilla lexer, for
2734 * example in LexCPP.cxx, see "cppWordLists" global array.
2735 * TODO: this magic number should be a member of the filetype */
2736 keyword_idx = 3;
2737 break;
2739 default:
2740 return; /* early out if type keywords are not supported */
2742 if (!app->tm_workspace->tags_array)
2743 return;
2745 /* get any type keywords and tell scintilla about them
2746 * this will cause the type keywords to be colourized in scintilla */
2747 keywords_str = symbols_find_typenames_as_string(doc->file_type->lang, FALSE);
2748 if (keywords_str)
2750 keywords = g_string_free(keywords_str, FALSE);
2751 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2752 g_free(keywords);
2753 queue_colourise(doc); /* force re-highlighting the entire document */
2758 static gboolean on_document_update_tag_list_idle(gpointer data)
2760 GeanyDocument *doc = data;
2762 if (! DOC_VALID(doc))
2763 return FALSE;
2765 if (! main_status.quitting)
2766 document_update_tags(doc);
2768 doc->priv->tag_list_update_source = 0;
2770 /* don't update the tags until another modification of the buffer */
2771 return FALSE;
2775 void document_update_tag_list_in_idle(GeanyDocument *doc)
2777 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2778 return;
2780 /* prevent "stacking up" callback handlers, we only need one to run soon */
2781 if (doc->priv->tag_list_update_source != 0)
2782 g_source_remove(doc->priv->tag_list_update_source);
2784 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2785 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2789 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2790 gboolean filetype_changed)
2792 g_return_if_fail(doc);
2793 if (type == NULL)
2794 type = filetypes[GEANY_FILETYPES_NONE];
2796 if (filetype_changed)
2798 doc->file_type = type;
2800 /* delete tm file object to force creation of a new one */
2801 if (doc->tm_file != NULL)
2803 tm_workspace_remove_source_file(doc->tm_file);
2804 tm_source_file_free(doc->tm_file);
2805 doc->tm_file = NULL;
2807 /* load tags files before highlighting (some lexers highlight global typenames) */
2808 if (type->id != GEANY_FILETYPES_NONE)
2809 symbols_global_tags_loaded(type->id);
2811 highlighting_set_styles(doc->editor->sci, type);
2812 editor_set_indentation_guides(doc->editor);
2813 build_menu_update(doc);
2814 queue_colourise(doc);
2815 if (type->priv->symbol_list_sort_mode == SYMBOLS_SORT_USE_PREVIOUS)
2816 doc->priv->symbol_list_sort_mode = interface_prefs.symbols_sort_mode;
2817 else
2818 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2821 document_update_tags(doc);
2825 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2826 * @param doc The document to use.
2827 * @param type The filetype. */
2828 GEANY_API_SYMBOL
2829 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2831 gboolean ft_changed;
2832 GeanyFiletype *old_ft;
2834 g_return_if_fail(doc);
2835 if (type == NULL)
2836 type = filetypes[GEANY_FILETYPES_NONE];
2838 old_ft = doc->file_type;
2839 geany_debug("%s : %s (%s)",
2840 (doc->file_name != NULL) ? doc->file_name : "unknown",
2841 type->name,
2842 (doc->encoding != NULL) ? doc->encoding : "unknown");
2844 ft_changed = (doc->file_type != type); /* filetype has changed */
2845 document_load_config(doc, type, ft_changed);
2847 if (ft_changed)
2849 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2851 /* assume that if previous filetype was none and the settings are the default ones, this
2852 * is the first time the filetype is carefully set, so we should apply indent settings */
2853 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2854 doc->editor->indent_type == iprefs->type &&
2855 doc->editor->indent_width == iprefs->width)
2857 document_apply_indent_settings(doc);
2858 ui_document_show_hide(doc);
2861 sidebar_openfiles_update(doc); /* to update the icon */
2862 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2867 void document_reload_config(GeanyDocument *doc)
2869 document_load_config(doc, doc->file_type, TRUE);
2874 * Sets the encoding of a document.
2875 * This function only set the encoding of the %document, it does not any conversions. The new
2876 * encoding is used when e.g. saving the file.
2878 * @param doc The document to use.
2879 * @param new_encoding The encoding to be set for the document.
2881 GEANY_API_SYMBOL
2882 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2884 if (doc == NULL || new_encoding == NULL ||
2885 utils_str_equal(new_encoding, doc->encoding))
2886 return;
2888 g_free(doc->encoding);
2889 doc->encoding = g_strdup(new_encoding);
2891 ui_update_statusbar(doc, -1);
2892 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2893 encodings_is_unicode_charset(doc->encoding));
2897 /* own Undo / Redo implementation to be able to undo / redo changes
2898 * to the encoding or the Unicode BOM (which are Scintilla independet).
2899 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2901 /* Clears an Undo or Redo buffer. */
2902 void document_undo_clear_stack(GTrashStack **stack)
2904 undo_action *a;
2906 while (g_trash_stack_height(stack) > 0)
2908 a = g_trash_stack_pop(stack);
2909 if (G_LIKELY(a != NULL))
2911 switch (a->type)
2913 case UNDO_ENCODING:
2914 case UNDO_RELOAD:
2915 g_free(a->data); break;
2916 default: break;
2918 g_free(a);
2921 *stack = NULL;
2924 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2925 void document_undo_clear(GeanyDocument *doc)
2927 document_undo_clear_stack(&doc->priv->undo_actions);
2928 document_undo_clear_stack(&doc->priv->redo_actions);
2930 if (! main_status.quitting && doc->editor != NULL)
2931 document_set_text_changed(doc, FALSE);
2935 /* Adds an undo action without clearing the redo stack. This function should
2936 * not be called directly, generally (use document_undo_add() instead), but is
2937 * used by document_redo() in order not to erase the redo stack while moving
2938 * an action from the redo stack to the undo stack. */
2939 void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data)
2941 undo_action *action;
2943 g_return_if_fail(doc != NULL);
2945 action = g_new0(undo_action, 1);
2946 action->type = type;
2947 action->data = data;
2949 g_trash_stack_push(&doc->priv->undo_actions, action);
2951 /* avoid unnecessary redraws */
2952 if (type != UNDO_SCINTILLA || !doc->changed)
2953 document_set_text_changed(doc, TRUE);
2955 ui_update_popup_reundo_items(doc);
2958 /* note: this is called on SCN_MODIFIED notifications */
2959 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2961 /* Clear the redo actions stack before adding the undo action. */
2962 document_undo_clear_stack(&doc->priv->redo_actions);
2964 document_undo_add_internal(doc, type, data);
2968 gboolean document_can_undo(GeanyDocument *doc)
2970 g_return_val_if_fail(doc != NULL, FALSE);
2972 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2973 return TRUE;
2974 else
2975 return FALSE;
2979 static void update_changed_state(GeanyDocument *doc)
2981 doc->changed =
2982 (sci_is_modified(doc->editor->sci) ||
2983 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2984 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2985 document_set_text_changed(doc, doc->changed);
2989 void document_undo(GeanyDocument *doc)
2991 undo_action *action;
2993 g_return_if_fail(doc != NULL);
2995 action = g_trash_stack_pop(&doc->priv->undo_actions);
2997 if (G_UNLIKELY(action == NULL))
2999 /* fallback, should not be necessary */
3000 geany_debug("%s: fallback used", G_STRFUNC);
3001 sci_undo(doc->editor->sci);
3003 else
3005 switch (action->type)
3007 case UNDO_SCINTILLA:
3009 document_redo_add(doc, UNDO_SCINTILLA, NULL);
3011 sci_undo(doc->editor->sci);
3012 break;
3014 case UNDO_BOM:
3016 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3018 doc->has_bom = GPOINTER_TO_INT(action->data);
3019 ui_update_statusbar(doc, -1);
3020 ui_document_show_hide(doc);
3021 break;
3023 case UNDO_ENCODING:
3025 /* use the "old" encoding */
3026 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3028 document_set_encoding(doc, (const gchar*)action->data);
3030 ignore_callback = TRUE;
3031 encodings_select_radio_item((const gchar*)action->data);
3032 ignore_callback = FALSE;
3034 g_free(action->data);
3035 break;
3037 case UNDO_RELOAD:
3039 UndoReloadData *data = (UndoReloadData*)action->data;
3040 gint eol_mode = data->eol_mode;
3041 guint i;
3043 /* We reuse 'data' for the redo action, so read the current EOL mode
3044 * into it before proceeding. */
3045 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3047 /* Undo the rest of the actions which are part of the reloading process. */
3048 for (i = 0; i < data->actions_count; i++)
3049 document_undo(doc);
3051 /* Restore the previous EOL mode. */
3052 sci_set_eol_mode(doc->editor->sci, eol_mode);
3053 /* This might affect the status bar and document menu, so update them. */
3054 ui_update_statusbar(doc, -1);
3055 ui_document_show_hide(doc);
3057 document_redo_add(doc, UNDO_RELOAD, data);
3058 break;
3060 default: break;
3063 g_free(action); /* free the action which was taken from the stack */
3065 update_changed_state(doc);
3066 ui_update_popup_reundo_items(doc);
3070 gboolean document_can_redo(GeanyDocument *doc)
3072 g_return_val_if_fail(doc != NULL, FALSE);
3074 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
3075 return TRUE;
3076 else
3077 return FALSE;
3081 void document_redo(GeanyDocument *doc)
3083 undo_action *action;
3085 g_return_if_fail(doc != NULL);
3087 action = g_trash_stack_pop(&doc->priv->redo_actions);
3089 if (G_UNLIKELY(action == NULL))
3091 /* fallback, should not be necessary */
3092 geany_debug("%s: fallback used", G_STRFUNC);
3093 sci_redo(doc->editor->sci);
3095 else
3097 switch (action->type)
3099 case UNDO_SCINTILLA:
3101 document_undo_add_internal(doc, UNDO_SCINTILLA, NULL);
3103 sci_redo(doc->editor->sci);
3104 break;
3106 case UNDO_BOM:
3108 document_undo_add_internal(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3110 doc->has_bom = GPOINTER_TO_INT(action->data);
3111 ui_update_statusbar(doc, -1);
3112 ui_document_show_hide(doc);
3113 break;
3115 case UNDO_ENCODING:
3117 document_undo_add_internal(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3119 document_set_encoding(doc, (const gchar*)action->data);
3121 ignore_callback = TRUE;
3122 encodings_select_radio_item((const gchar*)action->data);
3123 ignore_callback = FALSE;
3125 g_free(action->data);
3126 break;
3128 case UNDO_RELOAD:
3130 UndoReloadData *data = (UndoReloadData*)action->data;
3131 gint eol_mode = data->eol_mode;
3132 guint i;
3134 /* We reuse 'data' for the undo action, so read the current EOL mode
3135 * into it before proceeding. */
3136 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3138 /* Redo the rest of the actions which are part of the reloading process. */
3139 for (i = 0; i < data->actions_count; i++)
3140 document_redo(doc);
3142 /* Restore the previous EOL mode. */
3143 sci_set_eol_mode(doc->editor->sci, eol_mode);
3144 /* This might affect the status bar and document menu, so update them. */
3145 ui_update_statusbar(doc, -1);
3146 ui_document_show_hide(doc);
3148 document_undo_add_internal(doc, UNDO_RELOAD, data);
3149 break;
3151 default: break;
3154 g_free(action); /* free the action which was taken from the stack */
3156 update_changed_state(doc);
3157 ui_update_popup_reundo_items(doc);
3161 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
3163 undo_action *action;
3165 g_return_if_fail(doc != NULL);
3167 action = g_new0(undo_action, 1);
3168 action->type = type;
3169 action->data = data;
3171 g_trash_stack_push(&doc->priv->redo_actions, action);
3173 if (type != UNDO_SCINTILLA || !doc->changed)
3174 document_set_text_changed(doc, TRUE);
3176 ui_update_popup_reundo_items(doc);
3180 enum
3182 STATUS_CHANGED,
3183 STATUS_DISK_CHANGED,
3184 STATUS_READONLY
3187 static struct
3189 const gchar *name;
3190 GdkColor color;
3191 gboolean loaded;
3192 } document_status_styles[] = {
3193 { "geany-document-status-changed", {0}, FALSE },
3194 { "geany-document-status-disk-changed", {0}, FALSE },
3195 { "geany-document-status-readonly", {0}, FALSE }
3199 static gint document_get_status_id(GeanyDocument *doc)
3201 if (doc->changed)
3202 return STATUS_CHANGED;
3203 #ifdef USE_GIO_FILEMON
3204 else if (doc->priv->file_disk_status == FILE_CHANGED)
3205 #else
3206 else if (doc->priv->protected)
3207 #endif
3208 return STATUS_DISK_CHANGED;
3209 else if (doc->readonly)
3210 return STATUS_READONLY;
3212 return -1;
3216 /* returns an identifier that is to be set as a widget name or class to get it styled
3217 * depending on the document status (changed, readonly, etc.)
3218 * a NULL return value means default (unchanged) style */
3219 const gchar *document_get_status_widget_class(GeanyDocument *doc)
3221 gint status;
3223 g_return_val_if_fail(doc != NULL, NULL);
3225 status = document_get_status_id(doc);
3226 if (status < 0)
3227 return NULL;
3228 else
3229 return document_status_styles[status].name;
3234 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
3235 * Returned colors are red if the document has changes, green if the document is read-only
3236 * or simply @c NULL if the document is unmodified but writable.
3238 * @param doc The document to use.
3240 * @return @nullable The color for the document or @c NULL if the default color should be used.
3241 * The color object is owned by Geany and should not be modified or freed.
3243 * @since 0.16
3245 GEANY_API_SYMBOL
3246 const GdkColor *document_get_status_color(GeanyDocument *doc)
3248 gint status;
3250 g_return_val_if_fail(doc != NULL, NULL);
3252 status = document_get_status_id(doc);
3253 if (status < 0)
3254 return NULL;
3255 if (! document_status_styles[status].loaded)
3257 #if GTK_CHECK_VERSION(3, 0, 0)
3258 GdkRGBA color;
3259 GtkWidgetPath *path = gtk_widget_path_new();
3260 GtkStyleContext *ctx = gtk_style_context_new();
3261 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
3262 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
3263 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
3264 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
3265 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
3266 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
3267 gtk_style_context_set_path(ctx, path);
3268 gtk_style_context_get_color(ctx, gtk_style_context_get_state(ctx), &color);
3269 document_status_styles[status].color.red = 0xffff * color.red;
3270 document_status_styles[status].color.green = 0xffff * color.green;
3271 document_status_styles[status].color.blue = 0xffff * color.blue;
3272 document_status_styles[status].loaded = TRUE;
3273 gtk_widget_path_unref(path);
3274 g_object_unref(ctx);
3275 #else
3276 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
3277 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
3278 document_status_styles[status].name, NULL);
3279 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
3281 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
3282 document_status_styles[status].loaded = TRUE;
3283 g_free(path);
3284 #endif
3286 return &document_status_styles[status].color;
3290 /** Accessor function for @ref documents_array items.
3291 * @warning Always check the returned document is valid (@c doc->is_valid).
3292 * @param idx @c documents_array index.
3293 * @return @transfer{none} @nullable The document, or @c NULL if @a idx is out of range.
3295 * @since 0.16
3297 GEANY_API_SYMBOL
3298 GeanyDocument *document_index(gint idx)
3300 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
3304 GeanyDocument *document_clone(GeanyDocument *old_doc)
3306 gchar *text;
3307 GeanyDocument *doc;
3308 ScintillaObject *old_sci;
3310 g_return_val_if_fail(old_doc, NULL);
3311 old_sci = old_doc->editor->sci;
3312 if (sci_has_selection(old_sci))
3313 text = sci_get_selection_contents(old_sci);
3314 else
3315 text = sci_get_contents(old_sci, -1);
3317 doc = document_new_file(NULL, old_doc->file_type, text);
3318 g_free(text);
3319 document_set_text_changed(doc, TRUE);
3321 /* copy file properties */
3322 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
3323 doc->editor->line_breaking = old_doc->editor->line_breaking;
3324 doc->editor->auto_indent = old_doc->editor->auto_indent;
3325 editor_set_indent(doc->editor, old_doc->editor->indent_type,
3326 old_doc->editor->indent_width);
3327 doc->readonly = old_doc->readonly;
3328 doc->has_bom = old_doc->has_bom;
3329 doc->priv->protected = 0;
3330 document_set_encoding(doc, old_doc->encoding);
3331 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
3332 sci_set_readonly(doc->editor->sci, doc->readonly);
3334 /* update ui */
3335 ui_document_show_hide(doc);
3336 return doc;
3340 /* @note If successful, this should always be followed up with a call to
3341 * document_close_all().
3342 * @return TRUE if all files were saved or had their changes discarded. */
3343 gboolean document_account_for_unsaved(void)
3345 guint i, p, page_count;
3347 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3348 /* iterate over documents in tabs order */
3349 for (p = 0; p < page_count; p++)
3351 GeanyDocument *doc = document_get_from_page(p);
3353 if (DOC_VALID(doc) && doc->changed)
3355 if (! dialogs_show_unsaved_file(doc))
3356 return FALSE;
3359 /* all documents should now be accounted for, so ignore any changes */
3360 foreach_document (i)
3362 documents[i]->changed = FALSE;
3364 return TRUE;
3368 static void force_close_all(void)
3370 guint i, len = documents_array->len;
3372 /* check all documents have been accounted for */
3373 for (i = 0; i < len; i++)
3375 if (documents[i]->is_valid)
3377 g_return_if_fail(!documents[i]->changed);
3380 main_status.closing_all = TRUE;
3382 foreach_document(i)
3384 document_close(documents[i]);
3387 main_status.closing_all = FALSE;
3391 gboolean document_close_all(void)
3393 if (! document_account_for_unsaved())
3394 return FALSE;
3396 force_close_all();
3398 return TRUE;
3402 /* *
3403 * Shows a message related to a document.
3405 * Use this whenever the user needs to see a document-related message,
3406 * for example when the file was externally modified or deleted.
3408 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3409 * @a response_1 response will be the default for the @c GtkInfoBar or
3410 * @c GtkDialog.
3412 * @param doc @c GeanyDocument.
3413 * @param msgtype The type of message.
3414 * @param response_cb A callback function called when there's a response.
3415 * @param btn_1 The first action area button.
3416 * @param response_1 The response for @a btn_1.
3417 * @param btn_2 The second action area button.
3418 * @param response_2 The response for @a btn_2.
3419 * @param btn_3 The third action area button.
3420 * @param response_3 The response for @a btn_3.
3421 * @param extra_text Text to show below the main message.
3422 * @param format The text format for the main message.
3423 * @param ... Used with @a format as in @c printf.
3425 * @since 1.25
3426 * */
3427 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3428 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3429 const gchar *btn_1, GtkResponseType response_1,
3430 const gchar *btn_2, GtkResponseType response_2,
3431 const gchar *btn_3, GtkResponseType response_3,
3432 const gchar *extra_text, const gchar *format, ...)
3434 va_list args;
3435 gchar *text, *markup;
3436 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3437 GtkWidget *info_widget, *parent;
3438 parent = document_get_notebook_child(doc);
3440 va_start(args, format);
3441 text = g_strdup_vprintf(format, args);
3442 va_end(args);
3444 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3445 g_free(text);
3447 info_widget = gtk_info_bar_new();
3448 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3449 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3451 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3453 if (btn_1)
3454 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3455 if (btn_2)
3456 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3457 if (btn_3)
3458 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3460 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3462 label = geany_wrap_label_new(NULL);
3463 gtk_label_set_markup(GTK_LABEL(label), markup);
3464 g_free(markup);
3466 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3468 hbox = gtk_hbox_new(FALSE, 12);
3469 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3471 switch (msgtype)
3473 case GTK_MESSAGE_INFO:
3474 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3475 break;
3476 case GTK_MESSAGE_WARNING:
3477 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3478 break;
3479 case GTK_MESSAGE_QUESTION:
3480 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3481 break;
3482 case GTK_MESSAGE_ERROR:
3483 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3484 break;
3485 default:
3486 icon = NULL;
3487 break;
3490 if (icon)
3491 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3493 if (extra_text)
3495 vbox = gtk_vbox_new(FALSE, 6);
3496 extra_label = geany_wrap_label_new(extra_text);
3497 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3498 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3499 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3501 else
3502 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3504 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3506 gtk_widget_show_all(info_widget);
3508 return info_widget;
3512 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3514 gboolean close = FALSE;
3516 // disable info bar so actions complete normally
3517 unprotect_document(doc);
3518 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3520 if (response_id == RESPONSE_DOCUMENT_RELOAD)
3522 close = doc->changed ?
3523 document_reload_prompt(doc, doc->encoding) :
3524 document_reload_force(doc, doc->encoding);
3526 else if (response_id == RESPONSE_DOCUMENT_SAVE)
3528 close = document_save_file(doc, TRUE); // force overwrite
3530 else if (response_id == GTK_RESPONSE_CANCEL)
3532 document_set_text_changed(doc, TRUE);
3533 close = TRUE;
3535 if (!close)
3537 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3538 protect_document(doc);
3539 return;
3541 gtk_widget_destroy(bar);
3545 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3547 GtkInfoBar *bar = GTK_INFO_BAR(data);
3549 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3551 switch (event->keyval)
3553 case GDK_Tab:
3554 case GDK_ISO_Left_Tab:
3556 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3557 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3558 gtk_widget_child_focus(action_area, dir);
3559 return TRUE;
3561 case GDK_Escape:
3563 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3564 return TRUE;
3566 default:
3567 return FALSE;
3572 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3573 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3575 /* automatically focus editor again on bar close */
3576 g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3577 G_CONNECT_SWAPPED);
3578 g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3582 static void monitor_reload_file(GeanyDocument *doc)
3584 gchar *base_name = g_path_get_basename(doc->file_name);
3586 /* show this message only once */
3587 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3589 GtkWidget *bar;
3591 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3592 _("_Reload"), RESPONSE_DOCUMENT_RELOAD,
3593 _("_Overwrite"), RESPONSE_DOCUMENT_SAVE,
3594 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3595 _("Do you want to reload it?"),
3596 _("The file '%s' on the disk is more recent than the current buffer."),
3597 base_name);
3599 protect_document(doc);
3600 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3601 enable_key_intercept(doc, bar);
3603 g_free(base_name);
3607 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3608 gint response_id,
3609 GeanyDocument *doc)
3611 gboolean close = TRUE;
3613 unprotect_document(doc);
3615 if (response_id == RESPONSE_DOCUMENT_SAVE)
3616 close = dialogs_show_save_as();
3618 if (close)
3620 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3621 gtk_widget_destroy(bar);
3623 else
3625 /* protect back the document if save didn't occur */
3626 protect_document(doc);
3631 static void monitor_resave_missing_file(GeanyDocument *doc)
3633 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3635 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3637 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3638 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3640 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3641 on_monitor_resave_missing_file_response,
3642 GTK_STOCK_SAVE, RESPONSE_DOCUMENT_SAVE,
3643 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3644 NULL, GTK_RESPONSE_NONE,
3645 _("Try to resave the file?"),
3646 _("File \"%s\" was not found on disk!"),
3647 doc->file_name);
3649 protect_document(doc);
3650 document_set_text_changed(doc, TRUE);
3651 /* don't prompt more than once */
3652 SETPTR(doc->real_path, NULL);
3653 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3654 enable_key_intercept(doc, bar);
3659 /* Set force to force a disk check, otherwise it is ignored if there was a check
3660 * in the last file_prefs.disk_check_timeout seconds.
3661 * @return @c TRUE if the file has changed. */
3662 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3664 gboolean ret = FALSE;
3665 gboolean use_gio_filemon;
3666 time_t cur_time = 0;
3667 time_t mtime;
3668 gchar *locale_filename;
3669 FileDiskStatus old_status;
3671 g_return_val_if_fail(doc != NULL, FALSE);
3673 /* ignore remote files and documents that have never been saved to disk */
3674 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3675 || doc->real_path == NULL || doc->priv->is_remote)
3676 return FALSE;
3678 use_gio_filemon = (doc->priv->monitor != NULL);
3680 if (use_gio_filemon)
3682 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3683 return FALSE;
3685 else
3687 cur_time = time(NULL);
3688 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3689 return FALSE;
3691 doc->priv->last_check = cur_time;
3694 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3695 if (!get_mtime(locale_filename, &mtime))
3697 monitor_resave_missing_file(doc);
3698 /* doc may be closed now */
3699 ret = TRUE;
3701 else if (doc->priv->mtime < mtime)
3703 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3704 doc->priv->mtime = mtime;
3705 monitor_reload_file(doc);
3706 /* doc may be closed now */
3707 ret = TRUE;
3709 g_free(locale_filename);
3711 if (DOC_VALID(doc))
3712 { /* doc can get invalid when a document was closed */
3713 old_status = doc->priv->file_disk_status;
3714 doc->priv->file_disk_status = FILE_OK;
3715 if (old_status != doc->priv->file_disk_status)
3716 ui_update_tab_status(doc);
3718 return ret;
3722 /** Compares documents by their display names.
3723 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3724 * @note 'Display name' means the base name of the document's filename.
3726 * @param a @c GeanyDocument**.
3727 * @param b @c GeanyDocument**.
3728 * @warning The arguments take the address of each document pointer.
3729 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3731 * @since 0.21
3733 GEANY_API_SYMBOL
3734 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3736 GeanyDocument *doc_a = *((GeanyDocument**) a);
3737 GeanyDocument *doc_b = *((GeanyDocument**) b);
3738 gchar *base_name_a, *base_name_b;
3739 gint result;
3741 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3742 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3744 result = strcmp(base_name_a, base_name_b);
3746 g_free(base_name_a);
3747 g_free(base_name_b);
3749 return result;
3753 /** Compares documents by their tab order.
3754 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3756 * @param a @c GeanyDocument**.
3757 * @param b @c GeanyDocument**.
3758 * @warning The arguments take the address of each document pointer.
3759 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3761 * @since 0.21 (GEANY_API_VERSION 209)
3763 GEANY_API_SYMBOL
3764 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3766 GeanyDocument *doc_a = *((GeanyDocument**) a);
3767 GeanyDocument *doc_b = *((GeanyDocument**) b);
3768 gint notebook_position_doc_a;
3769 gint notebook_position_doc_b;
3771 notebook_position_doc_a = document_get_notebook_page(doc_a);
3772 notebook_position_doc_b = document_get_notebook_page(doc_b);
3774 if (notebook_position_doc_a < notebook_position_doc_b)
3775 return -1;
3776 if (notebook_position_doc_a > notebook_position_doc_b)
3777 return 1;
3778 /* equality */
3779 return 0;
3783 /** Compares documents by their tab order, in reverse order.
3784 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3786 * @param a @c GeanyDocument**.
3787 * @param b @c GeanyDocument**.
3788 * @warning The arguments take the address of each document pointer.
3789 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3791 * @since 0.21 (GEANY_API_VERSION 209)
3793 GEANY_API_SYMBOL
3794 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3796 return -1 * document_compare_by_tab_order(a, b);
3800 void document_grab_focus(GeanyDocument *doc)
3802 g_return_if_fail(doc != NULL);
3804 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));