Merge pull request #575 from techee/colourise
[geany-mirror.git] / src / document.c
blob333babfddd5d5c98d5b6c6853a3f4d6454a7951e
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 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 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 @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 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 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, gboolean full_colourise)
515 /* make sure we don't override previously set full_colourise=TRUE by FALSE */
516 if (!doc->priv->colourise_needed || !doc->priv->full_colourise)
517 doc->priv->full_colourise = full_colourise;
519 /* Colourise the editor before it is next drawn */
520 doc->priv->colourise_needed = TRUE;
522 /* If the editor doesn't need drawing (e.g. after saving the current
523 * document), we need to force a redraw, so the expose event is triggered.
524 * This ensures we don't start colourising before all documents are opened/saved,
525 * only once the editor is drawn. */
526 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
530 #ifdef USE_GIO_FILEMON
531 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
532 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
533 GeanyDocument *doc)
535 g_return_if_fail(doc != NULL);
537 if (file_prefs.disk_check_timeout == 0)
538 return;
540 geany_debug("%s: event: %d previous file status: %d",
541 G_STRFUNC, event, doc->priv->file_disk_status);
542 switch (event)
544 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
546 if (doc->priv->file_disk_status == FILE_IGNORE)
547 doc->priv->file_disk_status = FILE_OK;
548 else
549 doc->priv->file_disk_status = FILE_CHANGED;
550 g_message("%s: FILE_CHANGED", G_STRFUNC);
551 break;
553 case G_FILE_MONITOR_EVENT_DELETED:
555 doc->priv->file_disk_status = FILE_CHANGED;
556 g_message("%s: FILE_MISSING", G_STRFUNC);
557 break;
559 default:
560 break;
562 if (doc->priv->file_disk_status != FILE_OK)
564 ui_update_tab_status(doc);
567 #endif
570 static void document_stop_file_monitoring(GeanyDocument *doc)
572 g_return_if_fail(doc != NULL);
574 if (doc->priv->monitor != NULL)
576 g_object_unref(doc->priv->monitor);
577 doc->priv->monitor = NULL;
582 static void monitor_file_setup(GeanyDocument *doc)
584 g_return_if_fail(doc != NULL);
585 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
586 * doesn't work at all for remote files and legacy polling is too slow. */
587 if (! doc->priv->is_remote)
589 #ifdef USE_GIO_FILEMON
590 gchar *locale_filename;
592 /* stop any previous monitoring */
593 document_stop_file_monitoring(doc);
595 locale_filename = utils_get_locale_from_utf8(doc->file_name);
596 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
598 /* get a file monitor and connect to the 'changed' signal */
599 GFile *file = g_file_new_for_path(locale_filename);
600 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
601 g_signal_connect(doc->priv->monitor, "changed",
602 G_CALLBACK(monitor_file_changed_cb), doc);
604 /* we set the rate limit according to the GUI pref but it's most probably not used */
605 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
607 g_object_unref(file);
609 g_free(locale_filename);
610 #endif
612 doc->priv->file_disk_status = FILE_OK;
616 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
618 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
619 if (DOC_VALID(doc))
621 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
622 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
624 if (source_widget == NULL)
625 source_widget = doc->priv->tag_tree;
627 if (focusw == source_widget)
628 gtk_widget_grab_focus(sci);
633 static gboolean on_idle_focus(gpointer doc)
635 document_try_focus(doc, NULL);
636 return FALSE;
640 /* Creates a new document and editor, adding a tab in the notebook.
641 * @return The created document */
642 static GeanyDocument *document_create(const gchar *utf8_filename)
644 GeanyDocument *doc;
645 gint new_idx;
646 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
648 if (cur_pages == 1)
650 doc = document_get_current();
651 /* remove the empty document first */
652 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
653 /* prevent immediately opening another new doc with
654 * new_document_after_close pref */
655 remove_page(0);
658 new_idx = document_get_new_idx();
659 if (new_idx == -1) /* expand the array, no free places */
661 doc = g_new0(GeanyDocument, 1);
663 new_idx = documents_array->len;
664 g_ptr_array_add(documents_array, doc);
667 doc = documents[new_idx];
669 /* initialize default document settings */
670 doc->priv = g_new0(GeanyDocumentPrivate, 1);
671 doc->id = ++doc_id_counter;
672 doc->index = new_idx;
673 doc->file_name = g_strdup(utf8_filename);
674 doc->editor = editor_create(doc);
675 #ifndef USE_GIO_FILEMON
676 doc->priv->last_check = time(NULL);
677 #endif
679 sidebar_openfiles_add(doc); /* sets doc->iter */
681 notebook_new_tab(doc);
683 /* select document in sidebar */
685 GtkTreeSelection *sel;
687 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
688 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
691 ui_document_buttons_update();
693 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
694 return doc;
699 * Closes the given document.
701 * @param doc The document to remove.
703 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
705 * @since 0.15
707 GEANY_API_SYMBOL
708 gboolean document_close(GeanyDocument *doc)
710 g_return_val_if_fail(doc, FALSE);
712 return document_remove_page(document_get_notebook_page(doc));
716 /* Call document_remove_page() instead, this is only needed for document_create()
717 * to prevent re-opening a new document when the last document is closed (if enabled). */
718 static gboolean remove_page(guint page_num)
720 GeanyDocument *doc = document_get_from_page(page_num);
722 g_return_val_if_fail(doc != NULL, FALSE);
724 if (doc->changed && ! dialogs_show_unsaved_file(doc))
725 return FALSE;
727 /* tell any plugins that the document is about to be closed */
728 g_signal_emit_by_name(geany_object, "document-close", doc);
730 /* Checking real_path makes it likely the file exists on disk */
731 if (! main_status.closing_all && doc->real_path != NULL)
732 ui_add_recent_document(doc);
734 doc->is_valid = FALSE;
735 doc->id = 0;
737 if (main_status.quitting)
739 /* we need to destroy the ScintillaWidget so our handlers on it are
740 * disconnected before we free any data they may use (like the editor).
741 * when not quitting, this is handled by removing the notebook page. */
742 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
744 else
746 notebook_remove_page(page_num);
747 sidebar_remove_document(doc);
748 navqueue_remove_file(doc->file_name);
749 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
751 g_free(doc->encoding);
752 g_free(doc->priv->saved_encoding.encoding);
753 g_free(doc->file_name);
754 g_free(doc->real_path);
755 if (doc->tm_file)
757 tm_workspace_remove_source_file(doc->tm_file);
758 tm_source_file_free(doc->tm_file);
761 if (doc->priv->tag_tree)
762 gtk_widget_destroy(doc->priv->tag_tree);
764 editor_destroy(doc->editor);
765 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
767 document_stop_file_monitoring(doc);
769 document_undo_clear(doc);
771 g_free(doc->priv);
773 /* reset document settings to defaults for re-use */
774 memset(doc, 0, sizeof(GeanyDocument));
776 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
778 sidebar_update_tag_list(NULL, FALSE);
779 ui_set_window_title(NULL);
780 ui_save_buttons_toggle(FALSE);
781 ui_update_popup_reundo_items(NULL);
782 ui_document_buttons_update();
783 build_menu_update(NULL);
785 return TRUE;
790 * Removes the given notebook tab at @a page_num and clears all related information
791 * in the document list.
793 * @param page_num The notebook page number to remove.
795 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
797 GEANY_API_SYMBOL
798 gboolean document_remove_page(guint page_num)
800 gboolean done = remove_page(page_num);
802 if (done && ui_prefs.new_document_after_close)
803 document_new_file_if_non_open();
805 return done;
809 /* used to keep a record of the unchanged document state encoding */
810 static void store_saved_encoding(GeanyDocument *doc)
812 g_free(doc->priv->saved_encoding.encoding);
813 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
814 doc->priv->saved_encoding.has_bom = doc->has_bom;
818 /* Opens a new empty document only if there are no other documents open */
819 GeanyDocument *document_new_file_if_non_open(void)
821 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
822 return document_new_file(NULL, NULL, NULL);
824 return NULL;
829 * Creates a new document.
830 * Line endings in @a text will be converted to the default setting.
831 * Afterwards, the @c "document-new" signal is emitted for plugins.
833 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
834 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
835 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
837 * @return The new document.
839 GEANY_API_SYMBOL
840 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
842 GeanyDocument *doc;
844 if (utf8_filename && g_path_is_absolute(utf8_filename))
846 gchar *tmp;
847 tmp = utils_strdupa(utf8_filename); /* work around const */
848 utils_tidy_path(tmp);
849 utf8_filename = tmp;
851 doc = document_create(utf8_filename);
853 g_assert(doc != NULL);
855 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
856 if (text)
858 GString *template = g_string_new(text);
859 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
861 sci_set_text(doc->editor->sci, template->str);
862 g_string_free(template, TRUE);
864 else
865 sci_clear_all(doc->editor->sci);
867 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
869 sci_set_undo_collection(doc->editor->sci, TRUE);
870 sci_empty_undo_buffer(doc->editor->sci);
872 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
873 /* store the opened encoding for undo/redo */
874 store_saved_encoding(doc);
876 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
877 ft = filetypes_detect_from_document(doc);
879 document_set_filetype(doc, ft); /* also re-parses tags */
881 /* now the document is fully ready, display it (see notebook_new_tab()) */
882 gtk_widget_show(document_get_notebook_child(doc));
884 ui_set_window_title(doc);
885 build_menu_update(doc);
886 document_set_text_changed(doc, FALSE);
887 ui_document_show_hide(doc); /* update the document menu */
889 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
890 /* bring it in front, jump to the start and grab the focus */
891 editor_goto_pos(doc->editor, 0, FALSE);
892 document_try_focus(doc, NULL);
894 #ifdef USE_GIO_FILEMON
895 monitor_file_setup(doc);
896 #else
897 doc->priv->mtime = 0;
898 #endif
900 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
901 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
903 g_signal_emit_by_name(geany_object, "document-new", doc);
905 msgwin_status_add(_("New file \"%s\" opened."),
906 DOC_FILENAME(doc));
908 return doc;
913 * Opens a document specified by @a locale_filename.
914 * Afterwards, the @c "document-open" signal is emitted for plugins.
916 * @param locale_filename The filename of the document to load, in locale encoding.
917 * @param readonly Whether to open the document in read-only mode.
918 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
919 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
921 * @return The document opened or @c NULL.
923 GEANY_API_SYMBOL
924 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
925 GeanyFiletype *ft, const gchar *forced_enc)
927 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
931 typedef struct
933 gchar *data; /* null-terminated file data */
934 gsize len; /* string length of data */
935 gchar *enc;
936 gboolean bom;
937 time_t mtime; /* modification time, read by stat::st_mtime */
938 gboolean readonly;
939 } FileData;
942 static gboolean get_mtime(const gchar *locale_filename, time_t *time)
944 GError *error = NULL;
945 const gchar *err_msg = NULL;
947 if (USE_GIO_FILE_OPERATIONS)
949 GFile *file = g_file_new_for_path(locale_filename);
950 GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, NULL, &error);
952 if (info)
954 GTimeVal timeval;
956 g_file_info_get_modification_time(info, &timeval);
957 g_object_unref(info);
958 *time = timeval.tv_sec;
960 else if (error)
961 err_msg = error->message;
963 g_object_unref(file);
965 else
967 GStatBuf st;
969 if (g_stat(locale_filename, &st) == 0)
970 *time = st.st_mtime;
971 else
972 err_msg = g_strerror(errno);
975 if (err_msg)
977 gchar *utf8_filename = utils_get_utf8_from_locale(locale_filename);
979 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
980 utf8_filename, err_msg);
981 g_free(utf8_filename);
984 if (error)
985 g_error_free(error);
987 return err_msg == NULL;
991 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
992 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
993 FileData *filedata, const gchar *forced_enc)
995 GError *err = NULL;
997 filedata->data = NULL;
998 filedata->len = 0;
999 filedata->enc = NULL;
1000 filedata->bom = FALSE;
1001 filedata->readonly = FALSE;
1003 if (!get_mtime(locale_filename, &filedata->mtime))
1004 return FALSE;
1006 if (USE_GIO_FILE_OPERATIONS)
1008 GFile *file = g_file_new_for_path(locale_filename);
1010 g_file_load_contents(file, NULL, &filedata->data, &filedata->len, NULL, &err);
1011 g_object_unref(file);
1013 else
1014 g_file_get_contents(locale_filename, &filedata->data, &filedata->len, &err);
1016 if (err)
1018 ui_set_statusbar(TRUE, "%s", err->message);
1019 g_error_free(err);
1020 return FALSE;
1023 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
1024 &filedata->enc, &filedata->bom, &filedata->readonly))
1026 if (forced_enc)
1028 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
1029 display_filename, forced_enc);
1031 else
1033 ui_set_statusbar(TRUE,
1034 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1035 display_filename);
1037 g_free(filedata->data);
1038 return FALSE;
1041 if (filedata->readonly)
1043 const gchar *warn_msg = _(
1044 "The file \"%s\" could not be opened properly and has been truncated. " \
1045 "This can occur if the file contains a NULL byte. " \
1046 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1048 if (main_status.main_window_realized)
1049 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
1051 ui_set_statusbar(TRUE, warn_msg, display_filename);
1054 return TRUE;
1058 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1059 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1060 * if cl_options.goto_column is set.
1062 * returns the new position which may have changed */
1063 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1065 if (cl_options.goto_line >= 0)
1066 { /* goto line which was specified on command line and then undefine the line */
1067 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1068 editor->scroll_percent = 0.5F;
1069 cl_options.goto_line = -1;
1071 else if (pos > 0)
1073 sci_set_current_position(editor->sci, pos, FALSE);
1074 editor->scroll_percent = 0.5F;
1077 if (cl_options.goto_column >= 0)
1078 { /* goto column which was specified on command line and then undefine the column */
1080 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1081 sci_set_current_position(editor->sci, new_pos, FALSE);
1082 editor->scroll_percent = 0.5F;
1083 cl_options.goto_column = -1;
1084 return new_pos;
1086 return sci_get_current_position(editor->sci);
1090 /* Count lines that start with some hard tabs then a soft tab. */
1091 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1093 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1094 ScintillaObject *sci = editor->sci;
1095 gsize count = 0;
1096 struct Sci_TextToFind ttf;
1097 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
1098 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1100 g_free(soft_tab);
1102 ttf.chrg.cpMin = 0;
1103 ttf.chrg.cpMax = sci_get_length(sci);
1104 ttf.lpstrText = regex;
1105 while (1)
1107 gint pos;
1109 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1110 if (pos == -1)
1111 break; /* no more matches */
1112 count++;
1113 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1115 g_free(regex);
1116 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1117 return count > sci_get_line_count(sci) * 0.02;
1121 /* Detect the indent type based on counting the leading indent characters for each line.
1122 * Returns whether detection succeeded, and the detected type in *type_ upon success */
1123 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
1125 GeanyEditor *editor = doc->editor;
1126 ScintillaObject *sci = editor->sci;
1127 gint line, line_count;
1128 gsize tabs = 0, spaces = 0;
1130 if (detect_tabs_and_spaces(editor))
1132 *type_ = GEANY_INDENT_TYPE_BOTH;
1133 return TRUE;
1136 line_count = sci_get_line_count(sci);
1137 for (line = 0; line < line_count; line++)
1139 gint pos = sci_get_position_from_line(sci, line);
1140 gchar c;
1142 /* most code will have indent total <= 24, otherwise it's more likely to be
1143 * alignment than indentation */
1144 if (sci_get_line_indentation(sci, line) > 24)
1145 continue;
1147 c = sci_get_char_at(sci, pos);
1148 if (c == '\t')
1149 tabs++;
1150 /* check for at least 2 spaces */
1151 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1152 spaces++;
1154 if (spaces == 0 && tabs == 0)
1155 return FALSE;
1157 /* the factors may need to be tweaked */
1158 if (spaces > tabs * 4)
1159 *type_ = GEANY_INDENT_TYPE_SPACES;
1160 else if (tabs > spaces * 4)
1161 *type_ = GEANY_INDENT_TYPE_TABS;
1162 else
1163 *type_ = GEANY_INDENT_TYPE_BOTH;
1165 return TRUE;
1169 /* Detect the indent width based on counting the leading indent characters for each line.
1170 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1171 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1173 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1174 ScintillaObject *sci = editor->sci;
1175 gint line, line_count;
1176 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1177 gint count, width, i;
1179 /* can't easily detect the supposed width of a tab, guess the default is OK */
1180 if (type == GEANY_INDENT_TYPE_TABS)
1181 return FALSE;
1183 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1184 sci_set_tab_width(sci, 8);
1186 line_count = sci_get_line_count(sci);
1187 for (line = 0; line < line_count; line++)
1189 gint pos = sci_get_line_indent_position(sci, line);
1191 /* We probably don't have style info yet, because we're generally called just after
1192 * the document got created, so we can't use highlighting_is_code_style().
1193 * That's not good, but the assumption below that concerning lines start with an
1194 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1195 * without removing too much legitimate lines. */
1196 if (sci_get_char_at(sci, pos) == '*')
1197 continue;
1199 width = sci_get_line_indentation(sci, line);
1200 /* most code will have indent total <= 24, otherwise it's more likely to be
1201 * alignment than indentation */
1202 if (width > 24)
1203 continue;
1204 /* < 2 is no indentation */
1205 if (width < 2)
1206 continue;
1208 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1210 if ((width % (i + 2)) == 0)
1211 widths[i]++;
1214 count = 0;
1215 width = iprefs->width;
1216 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1218 /* give large indents higher weight not to be fooled by spurious indents */
1219 if (widths[i] >= count * 1.5)
1221 width = i + 2;
1222 count = widths[i];
1226 if (count == 0)
1227 return FALSE;
1229 *width_ = width;
1230 return TRUE;
1234 /* same as detect_indent_width() but uses editor's indent type */
1235 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1237 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1241 void document_apply_indent_settings(GeanyDocument *doc)
1243 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1244 GeanyIndentType type = iprefs->type;
1245 gint width = iprefs->width;
1247 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1249 if (type != iprefs->type)
1251 const gchar *name = NULL;
1253 switch (type)
1255 case GEANY_INDENT_TYPE_SPACES:
1256 name = _("Spaces");
1257 break;
1258 case GEANY_INDENT_TYPE_TABS:
1259 name = _("Tabs");
1260 break;
1261 case GEANY_INDENT_TYPE_BOTH:
1262 name = _("Tabs and Spaces");
1263 break;
1265 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1266 * and Spaces), the second one is the filename */
1267 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1268 DOC_FILENAME(doc));
1271 else if (doc->file_type->indent_type > -1)
1272 type = doc->file_type->indent_type;
1274 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1276 if (width != iprefs->width)
1278 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1279 DOC_FILENAME(doc));
1282 else if (doc->file_type->indent_width > -1)
1283 width = doc->file_type->indent_width;
1285 editor_set_indent(doc->editor, type, width);
1289 void document_show_tab(GeanyDocument *doc)
1291 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1292 document_get_notebook_page(doc));
1296 /* To open a new file, set doc to NULL; filename should be locale encoded.
1297 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1298 * pos is the cursor position, which can be overridden by --line and --column.
1299 * forced_enc can be NULL to detect the file encoding.
1300 * Returns: doc of the opened file or NULL if an error occurred. */
1301 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1302 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1304 gint editor_mode;
1305 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1306 gchar *utf8_filename = NULL;
1307 gchar *display_filename = NULL;
1308 gchar *locale_filename = NULL;
1309 GeanyFiletype *use_ft;
1310 FileData filedata;
1311 UndoReloadData *undo_reload_data;
1312 gboolean add_undo_reload_action;
1314 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1316 if (reload)
1318 utf8_filename = g_strdup(doc->file_name);
1319 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1321 else
1323 /* filename must not be NULL when opening a file */
1324 g_return_val_if_fail(filename, NULL);
1326 #ifdef G_OS_WIN32
1327 /* if filename is a shortcut, try to resolve it */
1328 locale_filename = win32_get_shortcut_target(filename);
1329 #else
1330 locale_filename = g_strdup(filename);
1331 #endif
1332 /* remove relative junk */
1333 utils_tidy_path(locale_filename);
1335 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1336 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1338 /* if file is already open, switch to it and go */
1339 doc = document_find_by_filename(utf8_filename);
1340 if (doc != NULL)
1342 ui_add_recent_document(doc); /* either add or reorder recent item */
1343 /* show the doc before reload dialog */
1344 document_show_tab(doc);
1345 document_check_disk_status(doc, TRUE); /* force a file changed check */
1348 if (reload || doc == NULL)
1349 { /* doc possibly changed */
1350 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1352 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1354 g_free(display_filename);
1355 g_free(utf8_filename);
1356 g_free(locale_filename);
1357 return NULL;
1360 if (! reload)
1362 doc = document_create(utf8_filename);
1363 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1365 /* file exists on disk, set real_path */
1366 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1368 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1369 monitor_file_setup(doc);
1372 if (! reload || ! file_prefs.keep_edit_history_on_reload)
1374 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1375 sci_empty_undo_buffer(doc->editor->sci);
1376 undo_reload_data = NULL;
1378 else
1380 undo_reload_data = (UndoReloadData*) g_malloc(sizeof(UndoReloadData));
1382 /* We will be adding a UNDO_RELOAD action to the undo stack that undoes
1383 * this reload. To do that, we keep collecting undo actions during
1384 * reloading, and at the end add an UNDO_RELOAD action that performs
1385 * all these actions in bulk. To keep track of how many undo actions
1386 * were added during this time, we compare the current undo-stack height
1387 * with its height at the end of the process. Note that g_trash_stack_height()
1388 * is O(N), which is a little ugly, but this seems like the most maintainable
1389 * option. */
1390 undo_reload_data->actions_count = g_trash_stack_height(&doc->priv->undo_actions);
1392 /* We use add_undo_reload_action to track any changes to the document that
1393 * require adding an undo action to revert the reload, but that do not
1394 * generate an undo action themselves. */
1395 add_undo_reload_action = FALSE;
1398 /* add the text to the ScintillaObject */
1399 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1400 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1401 queue_colourise(doc, TRUE); /* Ensure the document gets colourised. */
1403 /* detect & set line endings */
1404 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1405 if (undo_reload_data)
1407 undo_reload_data->eol_mode = editor_get_eol_char_mode(doc->editor);
1408 /* Force adding an undo-reload action if the EOL mode changed. */
1409 if (editor_mode != undo_reload_data->eol_mode)
1410 add_undo_reload_action = TRUE;
1412 sci_set_eol_mode(doc->editor->sci, editor_mode);
1413 g_free(filedata.data);
1415 sci_set_undo_collection(doc->editor->sci, TRUE);
1417 /* If reloading and the current and new encodings or BOM states differ,
1418 * add appropriate undo actions. */
1419 if (undo_reload_data)
1421 if (! utils_str_equal(doc->encoding, filedata.enc))
1422 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
1423 if (doc->has_bom != filedata.bom)
1424 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
1427 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1428 g_free(doc->encoding); /* if reloading, free old encoding */
1429 doc->encoding = filedata.enc;
1430 doc->has_bom = filedata.bom;
1431 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1433 doc->readonly = readonly || filedata.readonly;
1434 sci_set_readonly(doc->editor->sci, doc->readonly);
1435 doc->priv->protected = 0;
1437 /* update line number margin width */
1438 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1439 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1441 if (! reload)
1444 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1445 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1446 doc->editor);
1448 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1450 else
1451 { /* reloading */
1452 if (undo_reload_data)
1454 /* Calculate the number of undo actions that are part of the reloading
1455 * process, and add the UNDO_RELOAD action. */
1456 undo_reload_data->actions_count =
1457 g_trash_stack_height(&doc->priv->undo_actions) - undo_reload_data->actions_count;
1459 /* We only add an undo-reload action if the document has actually changed.
1460 * At the time of writing, this condition is moot because sci_set_text
1461 * generates an undo action even when the text hasn't really changed, so
1462 * actions_count is always greater than zero. In the future this might change.
1463 * It's arguable whether we should add an undo-reload action unconditionally,
1464 * especially since it's possible (if unlikely) that there had only
1465 * been "invisible" changes to the document, such as changes in encoding and
1466 * EOL mode, but for the time being that's how we roll. */
1467 if (undo_reload_data->actions_count > 0 || add_undo_reload_action)
1468 document_undo_add(doc, UNDO_RELOAD, undo_reload_data);
1469 else
1470 g_free(undo_reload_data);
1472 /* We didn't save the document per-se, but its contents are now
1473 * synchronized with the file on disk, hence set a save point here.
1474 * We need to do this in this case only, because we don't clear
1475 * Scintilla's undo stack. */
1476 sci_set_savepoint(doc->editor->sci);
1478 else
1479 document_undo_clear(doc);
1481 use_ft = ft;
1483 /* update taglist, typedef keywords and build menu if necessary */
1484 document_set_filetype(doc, use_ft);
1486 /* set indentation settings after setting the filetype */
1487 if (reload)
1488 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1489 else
1490 document_apply_indent_settings(doc);
1492 document_set_text_changed(doc, FALSE); /* also updates tab state */
1493 ui_document_show_hide(doc); /* update the document menu */
1495 /* finally add current file to recent files menu, but not the files from the last session */
1496 if (! main_status.opening_session_files)
1497 ui_add_recent_document(doc);
1499 if (reload)
1501 g_signal_emit_by_name(geany_object, "document-reload", doc);
1502 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1504 else
1506 g_signal_emit_by_name(geany_object, "document-open", doc);
1507 /* For translators: this is the status window message for opening a file. %d is the number
1508 * of the newly opened file, %s indicates whether the file is opened read-only
1509 * (it is replaced with the string ", read-only"). */
1510 msgwin_status_add(_("File %s opened(%d%s)."),
1511 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1512 (readonly) ? _(", read-only") : "");
1515 /* now the document is fully ready, display it (see notebook_new_tab()) */
1516 gtk_widget_show(document_get_notebook_child(doc));
1519 g_free(display_filename);
1520 g_free(utf8_filename);
1521 g_free(locale_filename);
1523 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1524 pos = set_cursor_position(doc->editor, pos);
1525 /* now bring the file in front */
1526 editor_goto_pos(doc->editor, pos, FALSE);
1528 /* finally, let the editor widget grab the focus so you can start coding
1529 * right away */
1530 g_idle_add(on_idle_focus, doc);
1531 return doc;
1535 /* Takes a new line separated list of filename URIs and opens each file.
1536 * length is the length of the string */
1537 void document_open_file_list(const gchar *data, gsize length)
1539 guint i;
1540 gchar *filename;
1541 gchar **list;
1543 g_return_if_fail(data != NULL);
1545 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1547 /* stop at the end or first empty item, because last item is empty but not null */
1548 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1550 filename = utils_get_path_from_uri(list[i]);
1551 if (filename == NULL)
1552 continue;
1553 document_open_file(filename, FALSE, NULL, NULL);
1554 g_free(filename);
1557 g_strfreev(list);
1562 * Opens each file in the list @a filenames.
1563 * Internally, document_open_file() is called for every list item.
1565 * @param filenames A list of filenames to load, in locale encoding.
1566 * @param readonly Whether to open the document in read-only mode.
1567 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1568 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1570 GEANY_API_SYMBOL
1571 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1572 const gchar *forced_enc)
1574 const GSList *item;
1576 for (item = filenames; item != NULL; item = g_slist_next(item))
1578 document_open_file(item->data, readonly, ft, forced_enc);
1583 static void on_keep_edit_history_on_reload_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
1585 if (response_id == GTK_RESPONSE_NO)
1587 file_prefs.keep_edit_history_on_reload = FALSE;
1588 document_reload_force(doc, doc->encoding);
1590 else if (response_id == GTK_RESPONSE_CANCEL)
1592 /* this condition cannot be reached via info bar buttons, but by our code
1593 * to replace this bar with a higher priority one */
1594 file_prefs.show_keep_edit_history_on_reload_msg = TRUE;
1596 doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = NULL;
1597 gtk_widget_destroy(bar);
1602 * Reloads the document with the specified file encoding.
1603 * @a forced_enc or @c NULL to auto-detect the file encoding.
1605 * @param doc The document to reload.
1606 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1608 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1610 GEANY_API_SYMBOL
1611 gboolean document_reload_force(GeanyDocument *doc, const gchar *forced_enc)
1613 gint pos = 0;
1614 GeanyDocument *new_doc;
1615 GtkWidget *bar;
1617 g_return_val_if_fail(doc != NULL, FALSE);
1619 /* Use cancel because the response handler would call this recursively */
1620 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1621 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1623 /* try to set the cursor to the position before reloading */
1624 pos = sci_get_current_position(doc->editor->sci);
1625 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1627 if (file_prefs.keep_edit_history_on_reload && file_prefs.show_keep_edit_history_on_reload_msg)
1629 bar = document_show_message(doc, GTK_MESSAGE_INFO,
1630 on_keep_edit_history_on_reload_response,
1631 GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
1632 _("Discard history"), GTK_RESPONSE_NO,
1633 NULL, 0, _("The buffer's previous state is stored in the history and "
1634 "undoing restores it. You can disable this by discarding the history upon "
1635 "reload. This message will not be displayed again but "
1636 "Your choice can be changed in the various preferences."),
1637 _("The file has been reloaded."));
1638 doc->priv->info_bars[MSG_TYPE_POST_RELOAD] = bar;
1639 file_prefs.show_keep_edit_history_on_reload_msg = FALSE;
1642 return (new_doc != NULL);
1646 /* also used for reloading when forced_enc is NULL */
1647 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1649 gchar *base_name;
1650 gboolean prompt, result = FALSE;
1652 g_return_val_if_fail(doc != NULL, FALSE);
1654 /* No need to reload "untitled" (non-file-backed) documents */
1655 if (doc->file_name == NULL)
1656 return FALSE;
1658 if (forced_enc == NULL)
1659 forced_enc = doc->encoding;
1661 base_name = g_path_get_basename(doc->file_name);
1662 /* don't prompt if edit history is maintained, or if file hasn't been edited at all */
1663 prompt = !file_prefs.keep_edit_history_on_reload &&
1664 (doc->changed || (document_can_undo(doc) || document_can_redo(doc)));
1666 if (!prompt || dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1667 doc->changed ? _("Any unsaved changes will be lost.") :
1668 _("Undo history will be lost."),
1669 _("Are you sure you want to reload '%s'?"), base_name))
1671 result = document_reload_force(doc, forced_enc);
1672 if (forced_enc != NULL)
1673 ui_update_statusbar(doc, -1);
1675 g_free(base_name);
1676 return result;
1680 static void document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1682 #ifndef USE_GIO_FILEMON
1683 g_return_if_fail(doc != NULL);
1685 get_mtime(locale_filename, &doc->priv->mtime); /* get the modification time from file and keep it */
1686 #endif
1690 /* Sets line and column to the given position byte_pos in the document.
1691 * byte_pos is the position counted in bytes, not characters */
1692 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1694 gint i;
1695 gint line_start;
1697 /* for some reason we can use byte count instead of character count here */
1698 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1699 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1700 /* get the column in the line */
1701 *column = byte_pos - line_start;
1703 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1704 * skip one byte(i++) and decrease the column number which is based on byte count */
1705 for (i = line_start; i < (line_start + *column); i++)
1707 if (sci_get_char_at(doc->editor->sci, i) < 0)
1709 (*column)--;
1710 i++;
1716 static void replace_header_filename(GeanyDocument *doc)
1718 gchar *filebase;
1719 gchar *filename;
1720 struct Sci_TextToFind ttf;
1722 g_return_if_fail(doc != NULL);
1723 g_return_if_fail(doc->file_type != NULL);
1725 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1726 if (doc->file_type->extension)
1727 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1728 else
1729 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1731 filename = g_path_get_basename(doc->file_name);
1733 /* only search the first 3 lines */
1734 ttf.chrg.cpMin = 0;
1735 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1736 ttf.lpstrText = filebase;
1738 if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1740 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1741 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1742 sci_replace_target(doc->editor->sci, filename, FALSE);
1744 g_free(filebase);
1745 g_free(filename);
1750 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1751 * you still have to call @ref document_save_file_as() to change the @a doc object.
1752 * It also stops monitoring for file changes to prevent receiving too many file change events
1753 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1755 * @param doc The current document which should be renamed.
1756 * @param new_filename The new filename in UTF-8 encoding.
1758 * @since 0.16
1760 GEANY_API_SYMBOL
1761 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1763 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1764 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1765 gint result;
1767 /* stop file monitoring to avoid getting events for deleting/creating files,
1768 * it's re-setup in document_save_file_as() */
1769 document_stop_file_monitoring(doc);
1771 result = g_rename(old_locale_filename, new_locale_filename);
1772 if (result != 0)
1774 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1775 _("Error renaming file."), g_strerror(errno));
1777 g_free(old_locale_filename);
1778 g_free(new_locale_filename);
1782 static void protect_document(GeanyDocument *doc)
1784 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1785 if (!doc->priv->protected++)
1786 sci_set_readonly(doc->editor->sci, TRUE);
1788 ui_update_tab_status(doc);
1792 static void unprotect_document(GeanyDocument *doc)
1794 g_return_if_fail(doc->priv->protected > 0);
1796 if (!--doc->priv->protected && doc->readonly == FALSE)
1797 sci_set_readonly(doc->editor->sci, FALSE);
1799 ui_update_tab_status(doc);
1803 /* Return TRUE if the document doesn't have a full filename set.
1804 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1805 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1806 * new files. */
1807 gboolean document_need_save_as(GeanyDocument *doc)
1809 g_return_val_if_fail(doc != NULL, FALSE);
1811 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1816 * Saves the document, detecting the filetype.
1818 * @param doc The document for the file to save.
1819 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1820 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1822 * @see document_save_file().
1824 * @since 0.16
1826 GEANY_API_SYMBOL
1827 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1829 gboolean ret;
1830 gboolean new_file;
1832 g_return_val_if_fail(doc != NULL, FALSE);
1834 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1835 if (utf8_fname != NULL)
1836 SETPTR(doc->file_name, g_strdup(utf8_fname));
1838 /* reset real path, it's retrieved again in document_save() */
1839 SETPTR(doc->real_path, NULL);
1841 /* detect filetype */
1842 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1844 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1846 document_set_filetype(doc, ft);
1847 if (document_get_current() == doc)
1849 ignore_callback = TRUE;
1850 filetypes_select_radio_item(doc->file_type);
1851 ignore_callback = FALSE;
1855 if (new_file)
1857 // assume user wants to throw away read-only setting
1858 sci_set_readonly(doc->editor->sci, FALSE);
1859 doc->readonly = FALSE;
1860 if (doc->priv->protected > 0)
1861 unprotect_document(doc);
1864 replace_header_filename(doc);
1866 ret = document_save_file(doc, TRUE);
1868 /* file monitoring support, add file monitoring after the file has been saved
1869 * to ignore any earlier events */
1870 monitor_file_setup(doc);
1871 doc->priv->file_disk_status = FILE_IGNORE;
1873 if (ret)
1874 ui_add_recent_document(doc);
1875 return ret;
1879 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1881 GError *conv_error = NULL;
1882 gchar* conv_file_contents = NULL;
1883 gsize bytes_read;
1884 gsize conv_len;
1886 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1887 g_return_val_if_fail(len != NULL, FALSE);
1889 /* try to convert it from UTF-8 to original encoding */
1890 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1891 &bytes_read, &conv_len, &conv_error);
1893 if (conv_error != NULL)
1895 gchar *text = g_strdup_printf(
1896 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1897 doc->encoding);
1898 gchar *error_text;
1900 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1902 gint line, column;
1903 gint context_len;
1904 gunichar unic;
1905 /* don't read over the doc length */
1906 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1907 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1908 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1910 /* take only one valid Unicode character from the context and discard the leftover */
1911 unic = g_utf8_get_char_validated(context, -1);
1912 context_len = g_unichar_to_utf8(unic, context);
1913 context[context_len] = '\0';
1914 get_line_column_from_pos(doc, bytes_read, &line, &column);
1916 error_text = g_strdup_printf(
1917 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1918 conv_error->message, context, line + 1, column);
1920 else
1921 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1923 geany_debug("encoding error: %s", conv_error->message);
1924 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1925 g_error_free(conv_error);
1926 g_free(text);
1927 g_free(error_text);
1928 return FALSE;
1930 else
1932 g_free(*data);
1933 *data = conv_file_contents;
1934 *len = conv_len;
1936 return TRUE;
1940 static gchar *write_data_to_disk(const gchar *locale_filename,
1941 const gchar *data, gsize len)
1943 GError *error = NULL;
1945 if (file_prefs.use_safe_file_saving)
1947 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1948 * This is the only option that handles disk space exhaustion. */
1949 if (g_file_set_contents(locale_filename, data, len, &error))
1950 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1952 else if (USE_GIO_FILE_OPERATIONS)
1954 GFile *fp;
1956 /* Use GIO API to save file (GVFS-safe)
1957 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1958 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1959 fp = g_file_new_for_path(locale_filename);
1960 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1961 G_FILE_CREATE_NONE, NULL, NULL, &error);
1962 g_object_unref(fp);
1964 else
1966 FILE *fp;
1967 int save_errno;
1968 gchar *display_name = g_filename_display_name(locale_filename);
1970 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1971 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1972 errno = 0;
1973 fp = g_fopen(locale_filename, "wb");
1974 if (fp == NULL)
1976 save_errno = errno;
1978 g_set_error(&error,
1979 G_FILE_ERROR,
1980 g_file_error_from_errno(save_errno),
1981 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1982 display_name,
1983 g_strerror(save_errno));
1985 else
1987 gsize bytes_written;
1989 errno = 0;
1990 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1992 if (len != bytes_written)
1994 save_errno = errno;
1996 g_set_error(&error,
1997 G_FILE_ERROR,
1998 g_file_error_from_errno(save_errno),
1999 _("Failed to write file '%s': fwrite() failed: %s"),
2000 display_name,
2001 g_strerror(save_errno));
2004 errno = 0;
2005 /* preserve the fwrite() error if any */
2006 if (fclose(fp) != 0 && error == NULL)
2008 save_errno = errno;
2010 g_set_error(&error,
2011 G_FILE_ERROR,
2012 g_file_error_from_errno(save_errno),
2013 _("Failed to close file '%s': fclose() failed: %s"),
2014 display_name,
2015 g_strerror(save_errno));
2019 g_free(display_name);
2021 if (error != NULL)
2023 gchar *msg = g_strdup(error->message);
2024 g_error_free(error);
2025 /* geany will warn about file truncation for unsafe saving below */
2026 return msg;
2028 return NULL;
2032 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
2033 const gchar *data, gsize len)
2035 gchar *err;
2037 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
2038 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
2040 err = write_data_to_disk(locale_filename, data, len);
2041 if (err)
2042 return err;
2044 /* now the file is on disk, set real_path */
2045 if (doc->real_path == NULL)
2047 doc->real_path = tm_get_real_path(locale_filename);
2048 doc->priv->is_remote = utils_is_remote_path(locale_filename);
2049 monitor_file_setup(doc);
2051 return NULL;
2055 static gboolean save_file_handle_infobars(GeanyDocument *doc, gboolean force)
2057 GtkWidget *bar = NULL;
2059 document_show_tab(doc);
2061 if (doc->priv->info_bars[MSG_TYPE_RELOAD])
2063 if (!dialogs_show_question_full(NULL, _("_Overwrite"), GTK_STOCK_CANCEL,
2064 _("Overwrite?"),
2065 _("The file '%s' on the disk is more recent than the current buffer."),
2066 doc->file_name))
2067 return FALSE;
2068 bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
2070 else if (doc->priv->info_bars[MSG_TYPE_RESAVE])
2072 if (!dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
2073 _("Try to resave the file?"),
2074 _("File \"%s\" was not found on disk!"),
2075 doc->file_name))
2076 return FALSE;
2077 bar = doc->priv->info_bars[MSG_TYPE_RESAVE];
2079 else
2081 g_assert_not_reached();
2082 return FALSE;
2084 gtk_info_bar_response(GTK_INFO_BAR(bar), RESPONSE_DOCUMENT_SAVE);
2085 return TRUE;
2090 * Saves the document.
2091 * Also shows the Save As dialog if necessary.
2092 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
2094 * Saving may include replacing tabs with spaces,
2095 * stripping trailing spaces and adding a final new line at the end of the file, depending
2096 * on user preferences. Then the @c "document-before-save" signal is emitted,
2097 * allowing plugins to modify the document before it is saved, and data is
2098 * actually written to disk.
2100 * On successful saving:
2101 * - GeanyDocument::real_path is set.
2102 * - The filetype is set again or auto-detected if it wasn't set yet.
2103 * - The @c "document-save" signal is emitted for plugins.
2105 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
2106 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
2107 * added in Geany 1.22.
2109 * @param doc The document to save.
2110 * @param force Whether to save the file even if it is not modified.
2112 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
2114 GEANY_API_SYMBOL
2115 gboolean document_save_file(GeanyDocument *doc, gboolean force)
2117 gchar *errmsg;
2118 gchar *data;
2119 gsize len;
2120 gchar *locale_filename;
2121 const GeanyFilePrefs *fp;
2123 g_return_val_if_fail(doc != NULL, FALSE);
2125 if (document_need_save_as(doc))
2127 /* ensure doc is the current tab before showing the dialog */
2128 document_show_tab(doc);
2129 return dialogs_show_save_as();
2132 if (!force && !doc->changed)
2133 return FALSE;
2134 if (doc->readonly)
2136 ui_set_statusbar(TRUE,
2137 _("Cannot save read-only document '%s'!"), DOC_FILENAME(doc));
2138 return FALSE;
2140 document_check_disk_status(doc, TRUE);
2141 if (doc->priv->protected)
2142 return save_file_handle_infobars(doc, force);
2144 fp = project_get_file_prefs();
2145 /* replaces tabs with spaces but only if the current file is not a Makefile */
2146 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
2147 editor_replace_tabs(doc->editor, TRUE);
2148 /* strip trailing spaces */
2149 if (fp->strip_trailing_spaces)
2150 editor_strip_trailing_spaces(doc->editor, TRUE);
2151 /* ensure the file has a newline at the end */
2152 if (fp->final_new_line)
2153 editor_ensure_final_newline(doc->editor);
2154 /* ensure newlines are consistent */
2155 if (fp->ensure_convert_new_lines)
2156 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
2158 /* notify plugins which may wish to modify the document before it's saved */
2159 g_signal_emit_by_name(geany_object, "document-before-save", doc);
2161 len = sci_get_length(doc->editor->sci) + 1;
2162 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
2163 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
2164 * encoding, it will be converted to doc->encoding below and this conversion
2165 * also changes the BOM */
2166 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
2167 data[0] = (gchar) 0xef;
2168 data[1] = (gchar) 0xbb;
2169 data[2] = (gchar) 0xbf;
2170 sci_get_text(doc->editor->sci, len, data + 3);
2171 len += 3;
2173 else
2175 data = (gchar*) g_malloc(len);
2176 sci_get_text(doc->editor->sci, len, data);
2179 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
2180 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
2181 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
2183 if (! save_convert_to_encoding(doc, &data, &len))
2185 g_free(data);
2186 return FALSE;
2189 else
2191 len = strlen(data);
2194 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2196 /* ignore file changed notification when the file is written */
2197 doc->priv->file_disk_status = FILE_IGNORE;
2199 /* actually write the content of data to the file on disk */
2200 errmsg = save_doc(doc, locale_filename, data, len);
2201 g_free(data);
2203 if (errmsg != NULL)
2205 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
2207 if (!file_prefs.use_safe_file_saving)
2209 SETPTR(errmsg,
2210 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
2212 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
2213 doc->priv->file_disk_status = FILE_OK;
2214 utils_beep();
2215 g_free(locale_filename);
2216 g_free(errmsg);
2217 return FALSE;
2220 /* store the opened encoding for undo/redo */
2221 store_saved_encoding(doc);
2223 /* ignore the following things if we are quitting */
2224 if (! main_status.quitting)
2226 sci_set_savepoint(doc->editor->sci);
2228 if (file_prefs.disk_check_timeout > 0)
2229 document_update_timestamp(doc, locale_filename);
2231 /* update filetype-related things */
2232 document_set_filetype(doc, doc->file_type);
2234 document_update_tab_label(doc);
2236 msgwin_status_add(_("File %s saved."), doc->file_name);
2237 ui_update_statusbar(doc, -1);
2238 #ifdef HAVE_VTE
2239 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
2240 #endif
2242 g_free(locale_filename);
2244 g_signal_emit_by_name(geany_object, "document-save", doc);
2246 return TRUE;
2250 /* special search function, used from the find entry in the toolbar
2251 * return TRUE if text was found otherwise FALSE
2252 * return also TRUE if text is empty */
2253 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gboolean inc,
2254 gboolean backwards)
2256 gint start_pos, search_pos;
2257 struct Sci_TextToFind ttf;
2259 g_return_val_if_fail(text != NULL, FALSE);
2260 g_return_val_if_fail(doc != NULL, FALSE);
2261 if (! *text)
2262 return TRUE;
2264 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
2265 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
2267 /* search cursor to end or start */
2268 ttf.chrg.cpMin = start_pos;
2269 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
2270 ttf.lpstrText = (gchar *)text;
2271 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2273 /* if no match, search start (or end) to cursor */
2274 if (search_pos == -1)
2276 if (backwards)
2278 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
2279 ttf.chrg.cpMax = start_pos;
2281 else
2283 ttf.chrg.cpMin = 0;
2284 ttf.chrg.cpMax = start_pos + strlen(text);
2286 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2289 if (search_pos != -1)
2291 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
2293 /* unfold maybe folded results */
2294 sci_ensure_line_is_visible(doc->editor->sci, line);
2296 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2297 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2299 if (! editor_line_in_view(doc->editor, line))
2300 { /* we need to force scrolling in case the cursor is outside of the current visible area
2301 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2302 * while searching */
2303 editor_scroll_to_line(doc->editor, -1, 0.3F);
2305 else
2306 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2307 return TRUE;
2309 else
2311 if (! inc)
2313 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2315 utils_beep();
2316 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
2317 return FALSE;
2322 /* General search function, used from the find dialog.
2323 * Returns -1 on failure or the start position of the matching text.
2324 * Will skip past any selection, ignoring it.
2326 * @param text Text to find.
2327 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2329 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2330 GeanyFindFlags flags, gboolean search_backwards, GeanyMatchInfo **match_,
2331 gboolean scroll, GtkWidget *parent)
2333 gint selection_end, selection_start, search_pos;
2335 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2336 if (! *text)
2337 return -1;
2339 /* Sci doesn't support searching backwards with a regex */
2340 if (flags & GEANY_FIND_REGEXP)
2341 search_backwards = FALSE;
2343 if (!original_text)
2344 original_text = text;
2346 selection_start = sci_get_selection_start(doc->editor->sci);
2347 selection_end = sci_get_selection_end(doc->editor->sci);
2348 if ((selection_end - selection_start) > 0)
2349 { /* there's a selection so go to the end */
2350 if (search_backwards)
2351 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2352 else
2353 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2356 sci_set_search_anchor(doc->editor->sci);
2357 if (search_backwards)
2358 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2359 else
2360 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2362 if (search_pos != -1)
2364 /* unfold maybe folded results */
2365 sci_ensure_line_is_visible(doc->editor->sci,
2366 sci_get_line_from_position(doc->editor->sci, search_pos));
2367 if (scroll)
2368 doc->editor->scroll_percent = 0.3F;
2370 else
2372 gint sci_len = sci_get_length(doc->editor->sci);
2374 /* if we just searched the whole text, give up searching. */
2375 if ((selection_end == 0 && ! search_backwards) ||
2376 (selection_end == sci_len && search_backwards))
2378 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2379 utils_beep();
2380 return -1;
2383 /* we searched only part of the document, so ask whether to wraparound. */
2384 if (search_prefs.always_wrap ||
2385 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2386 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2388 gint ret;
2390 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2391 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2392 if (ret == -1)
2393 { /* return to original cursor position if not found */
2394 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2396 return ret;
2399 return search_pos;
2403 /* Replaces the selection if it matches, otherwise just finds the next match.
2404 * Returns: start of replaced text, or -1 if no replacement was made
2406 * @param find_text Text to find.
2407 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2409 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2410 const gchar *replace_text, GeanyFindFlags flags, gboolean search_backwards)
2412 gint selection_end, selection_start, search_pos;
2413 GeanyMatchInfo *match = NULL;
2415 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2417 if (! *find_text)
2418 return -1;
2420 /* Sci doesn't support searching backwards with a regex */
2421 if (flags & GEANY_FIND_REGEXP)
2422 search_backwards = FALSE;
2424 if (!original_find_text)
2425 original_find_text = find_text;
2427 selection_start = sci_get_selection_start(doc->editor->sci);
2428 selection_end = sci_get_selection_end(doc->editor->sci);
2429 if (selection_end == selection_start)
2431 /* no selection so just find the next match */
2432 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2433 return -1;
2435 /* there's a selection so go to the start before finding to search through it
2436 * this ensures there is a match */
2437 if (search_backwards)
2438 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2439 else
2440 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2442 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2443 /* return if the original selected text did not match (at the start of the selection) */
2444 if (search_pos != selection_start)
2446 if (search_pos != -1)
2447 geany_match_info_free(match);
2448 return -1;
2451 if (search_pos != -1)
2453 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2454 /* select the replacement - find text will skip past the selected text */
2455 sci_set_selection_start(doc->editor->sci, search_pos);
2456 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2457 geany_match_info_free(match);
2459 else
2461 /* no match in the selection */
2462 utils_beep();
2464 return search_pos;
2468 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2469 const gchar *original_replace_text)
2471 gchar *filename;
2473 if (count == 0)
2475 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2476 return;
2479 filename = g_path_get_basename(DOC_FILENAME(doc));
2480 ui_set_statusbar(TRUE, ngettext(
2481 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2482 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2483 count), filename, count, original_find_text, original_replace_text);
2484 g_free(filename);
2488 /* Replace all text matches in a certain range within document.
2489 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2490 * or -1 if no text was found.
2491 * scroll_to_match is whether to scroll the last replacement in view (which also
2492 * clears the selection).
2493 * Returns: the number of replacements made. */
2494 static guint
2495 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2496 GeanyFindFlags flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2498 gint count = 0;
2499 struct Sci_TextToFind ttf;
2500 ScintillaObject *sci;
2502 if (new_range_end != NULL)
2503 *new_range_end = -1;
2505 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2507 if (! *find_text || doc->readonly)
2508 return 0;
2510 sci = doc->editor->sci;
2512 ttf.chrg.cpMin = start;
2513 ttf.chrg.cpMax = end;
2514 ttf.lpstrText = (gchar*)find_text;
2516 sci_start_undo_action(sci);
2517 count = search_replace_range(sci, &ttf, flags, replace_text);
2518 sci_end_undo_action(sci);
2520 if (count > 0)
2521 { /* scroll last match in view, will destroy the existing selection */
2522 if (scroll_to_match)
2523 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2525 if (new_range_end != NULL)
2526 *new_range_end = ttf.chrg.cpMax;
2528 return count;
2532 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2533 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2535 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2536 gint max_column = 0, count = 0;
2537 gboolean replaced = FALSE;
2539 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2541 if (! *find_text)
2542 return;
2544 selection_start = sci_get_selection_start(doc->editor->sci);
2545 selection_end = sci_get_selection_end(doc->editor->sci);
2546 /* do we have a selection? */
2547 if ((selection_end - selection_start) == 0)
2549 utils_beep();
2550 return;
2553 selection_mode = sci_get_selection_mode(doc->editor->sci);
2554 selected_lines = sci_get_lines_selected(doc->editor->sci);
2555 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2556 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2558 gint first_line, line;
2560 sci_start_undo_action(doc->editor->sci);
2562 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2563 /* Find the last line with chars selected (not EOL char) */
2564 last_line = sci_get_line_from_position(doc->editor->sci,
2565 selection_end - editor_get_eol_char_len(doc->editor));
2566 last_line = MAX(first_line, last_line);
2567 for (line = first_line; line < (first_line + selected_lines); line++)
2569 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2570 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2572 /* skip line if there is no selection */
2573 if (line_start != INVALID_POSITION)
2575 /* don't let document_replace_range() scroll to match to keep our selection */
2576 gint new_sel_end;
2578 count += document_replace_range(doc, find_text, replace_text, flags,
2579 line_start, line_end, FALSE, &new_sel_end);
2580 if (new_sel_end != -1)
2582 replaced = TRUE;
2583 /* this gets the greatest column within the selection after replacing */
2584 max_column = MAX(max_column,
2585 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2589 sci_end_undo_action(doc->editor->sci);
2591 else /* handle normal line selection */
2593 count += document_replace_range(doc, find_text, replace_text, flags,
2594 selection_start, selection_end, TRUE, &selection_end);
2595 if (selection_end != -1)
2596 replaced = TRUE;
2599 if (replaced)
2600 { /* update the selection for the new endpoint */
2602 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2604 /* now we can scroll to the selection and destroy it because we rebuild it later */
2605 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2607 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2608 * the highest column on the last line. The wrapped selection is completely different
2609 * from the original one, so skip the selection at all */
2610 /* TODO is there a better way to handle the wrapped selection? */
2611 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2612 { /* for keeping and adjusting the selection in multi line rectangle selection we
2613 * need the last line of the original selection and the greatest column number after
2614 * replacing and set the selection end to the last line at the greatest column */
2615 sci_set_selection_start(doc->editor->sci, selection_start);
2616 sci_set_selection_end(doc->editor->sci,
2617 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2618 sci_set_selection_mode(doc->editor->sci, selection_mode);
2621 else
2623 sci_set_selection_start(doc->editor->sci, selection_start);
2624 sci_set_selection_end(doc->editor->sci, selection_end);
2627 else /* no replacements */
2628 utils_beep();
2630 show_replace_summary(doc, count, original_find_text, original_replace_text);
2634 /* returns number of replacements made. */
2635 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2636 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2638 gint len, count;
2639 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2641 if (! *find_text)
2642 return FALSE;
2644 len = sci_get_length(doc->editor->sci);
2645 count = document_replace_range(
2646 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2648 show_replace_summary(doc, count, original_find_text, original_replace_text);
2649 return count;
2654 * Parses or re-parses the document's buffer and updates the type
2655 * keywords and symbol list.
2657 * @param doc The document.
2659 void document_update_tags(GeanyDocument *doc)
2661 guchar *buffer_ptr;
2662 gsize len;
2664 g_return_if_fail(DOC_VALID(doc));
2665 g_return_if_fail(app->tm_workspace != NULL);
2667 /* early out if it's a new file or doesn't support tags */
2668 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2670 /* We must call sidebar_update_tag_list() before returning,
2671 * to ensure that the symbol list is always updated properly (e.g.
2672 * when creating a new document with a partial filename set. */
2673 sidebar_update_tag_list(doc, FALSE);
2674 return;
2677 /* create a new TM file if there isn't one yet */
2678 if (! doc->tm_file)
2680 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2681 const gchar *name;
2683 /* lookup the name rather than using filetype name to support custom filetypes */
2684 name = tm_source_file_get_lang_name(doc->file_type->lang);
2685 doc->tm_file = tm_source_file_new(locale_filename, name);
2686 g_free(locale_filename);
2688 if (doc->tm_file)
2689 tm_workspace_add_source_file_noupdate(doc->tm_file);
2692 /* early out if there's no tm source file and we couldn't create one */
2693 if (doc->tm_file == NULL)
2695 /* We must call sidebar_update_tag_list() before returning,
2696 * to ensure that the symbol list is always updated properly (e.g.
2697 * when creating a new document with a partial filename set. */
2698 sidebar_update_tag_list(doc, FALSE);
2699 return;
2702 /* Parse Scintilla's buffer directly using TagManager
2703 * Note: this buffer *MUST NOT* be modified */
2704 len = sci_get_length(doc->editor->sci);
2705 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2706 tm_workspace_update_source_file_buffer(doc->tm_file, buffer_ptr, len);
2708 sidebar_update_tag_list(doc, TRUE);
2709 document_highlight_tags(doc);
2713 /* Re-highlights type keywords without re-parsing the whole document. */
2714 void document_highlight_tags(GeanyDocument *doc)
2716 GString *keywords_str;
2717 gchar *keywords;
2718 gint keyword_idx;
2720 /* some filetypes support type keywords (such as struct names), but not
2721 * necessarily all filetypes for a particular scintilla lexer. this
2722 * tells us whether the filetype supports keywords, and if so
2723 * which index to use for the scintilla keywords set. */
2724 switch (doc->file_type->id)
2726 case GEANY_FILETYPES_C:
2727 case GEANY_FILETYPES_CPP:
2728 case GEANY_FILETYPES_CS:
2729 case GEANY_FILETYPES_D:
2730 case GEANY_FILETYPES_JAVA:
2731 case GEANY_FILETYPES_OBJECTIVEC:
2732 case GEANY_FILETYPES_VALA:
2733 case GEANY_FILETYPES_RUST:
2734 case GEANY_FILETYPES_GO:
2737 /* index of the keyword set in the Scintilla lexer, for
2738 * example in LexCPP.cxx, see "cppWordLists" global array.
2739 * TODO: this magic number should be a member of the filetype */
2740 keyword_idx = 3;
2741 break;
2743 default:
2744 return; /* early out if type keywords are not supported */
2746 if (!app->tm_workspace->tags_array)
2747 return;
2749 /* get any type keywords and tell scintilla about them
2750 * this will cause the type keywords to be colourized in scintilla */
2751 keywords_str = symbols_find_typenames_as_string(doc->file_type->lang, FALSE);
2752 if (keywords_str)
2754 keywords = g_string_free(keywords_str, FALSE);
2755 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2756 g_free(keywords);
2757 queue_colourise(doc, FALSE); /* re-highlight the visible area */
2762 static gboolean on_document_update_tag_list_idle(gpointer data)
2764 GeanyDocument *doc = data;
2766 if (! DOC_VALID(doc))
2767 return FALSE;
2769 if (! main_status.quitting)
2770 document_update_tags(doc);
2772 doc->priv->tag_list_update_source = 0;
2774 /* don't update the tags until another modification of the buffer */
2775 return FALSE;
2779 void document_update_tag_list_in_idle(GeanyDocument *doc)
2781 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2782 return;
2784 /* prevent "stacking up" callback handlers, we only need one to run soon */
2785 if (doc->priv->tag_list_update_source != 0)
2786 g_source_remove(doc->priv->tag_list_update_source);
2788 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2789 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2793 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2794 gboolean filetype_changed)
2796 g_return_if_fail(doc);
2797 if (type == NULL)
2798 type = filetypes[GEANY_FILETYPES_NONE];
2800 if (filetype_changed)
2802 doc->file_type = type;
2804 /* delete tm file object to force creation of a new one */
2805 if (doc->tm_file != NULL)
2807 tm_workspace_remove_source_file(doc->tm_file);
2808 tm_source_file_free(doc->tm_file);
2809 doc->tm_file = NULL;
2811 /* load tags files before highlighting (some lexers highlight global typenames) */
2812 if (type->id != GEANY_FILETYPES_NONE)
2813 symbols_global_tags_loaded(type->id);
2815 highlighting_set_styles(doc->editor->sci, type);
2816 editor_set_indentation_guides(doc->editor);
2817 build_menu_update(doc);
2818 queue_colourise(doc, TRUE);
2819 if (type->priv->symbol_list_sort_mode == SYMBOLS_SORT_USE_PREVIOUS)
2820 doc->priv->symbol_list_sort_mode = interface_prefs.symbols_sort_mode;
2821 else
2822 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2825 document_update_tags(doc);
2829 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2830 * @param doc The document to use.
2831 * @param type The filetype. */
2832 GEANY_API_SYMBOL
2833 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2835 gboolean ft_changed;
2836 GeanyFiletype *old_ft;
2838 g_return_if_fail(doc);
2839 if (type == NULL)
2840 type = filetypes[GEANY_FILETYPES_NONE];
2842 old_ft = doc->file_type;
2843 geany_debug("%s : %s (%s)",
2844 (doc->file_name != NULL) ? doc->file_name : "unknown",
2845 type->name,
2846 (doc->encoding != NULL) ? doc->encoding : "unknown");
2848 ft_changed = (doc->file_type != type); /* filetype has changed */
2849 document_load_config(doc, type, ft_changed);
2851 if (ft_changed)
2853 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2855 /* assume that if previous filetype was none and the settings are the default ones, this
2856 * is the first time the filetype is carefully set, so we should apply indent settings */
2857 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2858 doc->editor->indent_type == iprefs->type &&
2859 doc->editor->indent_width == iprefs->width)
2861 document_apply_indent_settings(doc);
2862 ui_document_show_hide(doc);
2865 sidebar_openfiles_update(doc); /* to update the icon */
2866 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2871 void document_reload_config(GeanyDocument *doc)
2873 document_load_config(doc, doc->file_type, TRUE);
2878 * Sets the encoding of a document.
2879 * This function only set the encoding of the %document, it does not any conversions. The new
2880 * encoding is used when e.g. saving the file.
2882 * @param doc The document to use.
2883 * @param new_encoding The encoding to be set for the document.
2885 GEANY_API_SYMBOL
2886 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2888 if (doc == NULL || new_encoding == NULL ||
2889 utils_str_equal(new_encoding, doc->encoding))
2890 return;
2892 g_free(doc->encoding);
2893 doc->encoding = g_strdup(new_encoding);
2895 ui_update_statusbar(doc, -1);
2896 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2897 encodings_is_unicode_charset(doc->encoding));
2901 /* own Undo / Redo implementation to be able to undo / redo changes
2902 * to the encoding or the Unicode BOM (which are Scintilla independet).
2903 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2905 /* Clears an Undo or Redo buffer. */
2906 void document_undo_clear_stack(GTrashStack **stack)
2908 undo_action *a;
2910 while (g_trash_stack_height(stack) > 0)
2912 a = g_trash_stack_pop(stack);
2913 if (G_LIKELY(a != NULL))
2915 switch (a->type)
2917 case UNDO_ENCODING:
2918 case UNDO_RELOAD:
2919 g_free(a->data); break;
2920 default: break;
2922 g_free(a);
2925 *stack = NULL;
2928 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2929 void document_undo_clear(GeanyDocument *doc)
2931 document_undo_clear_stack(&doc->priv->undo_actions);
2932 document_undo_clear_stack(&doc->priv->redo_actions);
2934 if (! main_status.quitting && doc->editor != NULL)
2935 document_set_text_changed(doc, FALSE);
2939 /* Adds an undo action without clearing the redo stack. This function should
2940 * not be called directly, generally (use document_undo_add() instead), but is
2941 * used by document_redo() in order not to erase the redo stack while moving
2942 * an action from the redo stack to the undo stack. */
2943 void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data)
2945 undo_action *action;
2947 g_return_if_fail(doc != NULL);
2949 action = g_new0(undo_action, 1);
2950 action->type = type;
2951 action->data = data;
2953 g_trash_stack_push(&doc->priv->undo_actions, action);
2955 /* avoid unnecessary redraws */
2956 if (type != UNDO_SCINTILLA || !doc->changed)
2957 document_set_text_changed(doc, TRUE);
2959 ui_update_popup_reundo_items(doc);
2962 /* note: this is called on SCN_MODIFIED notifications */
2963 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2965 /* Clear the redo actions stack before adding the undo action. */
2966 document_undo_clear_stack(&doc->priv->redo_actions);
2968 document_undo_add_internal(doc, type, data);
2972 gboolean document_can_undo(GeanyDocument *doc)
2974 g_return_val_if_fail(doc != NULL, FALSE);
2976 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2977 return TRUE;
2978 else
2979 return FALSE;
2983 static void update_changed_state(GeanyDocument *doc)
2985 doc->changed =
2986 (sci_is_modified(doc->editor->sci) ||
2987 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2988 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2989 document_set_text_changed(doc, doc->changed);
2993 void document_undo(GeanyDocument *doc)
2995 undo_action *action;
2997 g_return_if_fail(doc != NULL);
2999 action = g_trash_stack_pop(&doc->priv->undo_actions);
3001 if (G_UNLIKELY(action == NULL))
3003 /* fallback, should not be necessary */
3004 geany_debug("%s: fallback used", G_STRFUNC);
3005 sci_undo(doc->editor->sci);
3007 else
3009 switch (action->type)
3011 case UNDO_SCINTILLA:
3013 document_redo_add(doc, UNDO_SCINTILLA, NULL);
3015 sci_undo(doc->editor->sci);
3016 break;
3018 case UNDO_BOM:
3020 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3022 doc->has_bom = GPOINTER_TO_INT(action->data);
3023 ui_update_statusbar(doc, -1);
3024 ui_document_show_hide(doc);
3025 break;
3027 case UNDO_ENCODING:
3029 /* use the "old" encoding */
3030 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3032 document_set_encoding(doc, (const gchar*)action->data);
3034 ignore_callback = TRUE;
3035 encodings_select_radio_item((const gchar*)action->data);
3036 ignore_callback = FALSE;
3038 g_free(action->data);
3039 break;
3041 case UNDO_RELOAD:
3043 UndoReloadData *data = (UndoReloadData*)action->data;
3044 gint eol_mode = data->eol_mode;
3045 guint i;
3047 /* We reuse 'data' for the redo action, so read the current EOL mode
3048 * into it before proceeding. */
3049 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3051 /* Undo the rest of the actions which are part of the reloading process. */
3052 for (i = 0; i < data->actions_count; i++)
3053 document_undo(doc);
3055 /* Restore the previous EOL mode. */
3056 sci_set_eol_mode(doc->editor->sci, eol_mode);
3057 /* This might affect the status bar and document menu, so update them. */
3058 ui_update_statusbar(doc, -1);
3059 ui_document_show_hide(doc);
3061 document_redo_add(doc, UNDO_RELOAD, data);
3062 break;
3064 default: break;
3067 g_free(action); /* free the action which was taken from the stack */
3069 update_changed_state(doc);
3070 ui_update_popup_reundo_items(doc);
3074 gboolean document_can_redo(GeanyDocument *doc)
3076 g_return_val_if_fail(doc != NULL, FALSE);
3078 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
3079 return TRUE;
3080 else
3081 return FALSE;
3085 void document_redo(GeanyDocument *doc)
3087 undo_action *action;
3089 g_return_if_fail(doc != NULL);
3091 action = g_trash_stack_pop(&doc->priv->redo_actions);
3093 if (G_UNLIKELY(action == NULL))
3095 /* fallback, should not be necessary */
3096 geany_debug("%s: fallback used", G_STRFUNC);
3097 sci_redo(doc->editor->sci);
3099 else
3101 switch (action->type)
3103 case UNDO_SCINTILLA:
3105 document_undo_add_internal(doc, UNDO_SCINTILLA, NULL);
3107 sci_redo(doc->editor->sci);
3108 break;
3110 case UNDO_BOM:
3112 document_undo_add_internal(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3114 doc->has_bom = GPOINTER_TO_INT(action->data);
3115 ui_update_statusbar(doc, -1);
3116 ui_document_show_hide(doc);
3117 break;
3119 case UNDO_ENCODING:
3121 document_undo_add_internal(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3123 document_set_encoding(doc, (const gchar*)action->data);
3125 ignore_callback = TRUE;
3126 encodings_select_radio_item((const gchar*)action->data);
3127 ignore_callback = FALSE;
3129 g_free(action->data);
3130 break;
3132 case UNDO_RELOAD:
3134 UndoReloadData *data = (UndoReloadData*)action->data;
3135 gint eol_mode = data->eol_mode;
3136 guint i;
3138 /* We reuse 'data' for the undo action, so read the current EOL mode
3139 * into it before proceeding. */
3140 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3142 /* Redo the rest of the actions which are part of the reloading process. */
3143 for (i = 0; i < data->actions_count; i++)
3144 document_redo(doc);
3146 /* Restore the previous EOL mode. */
3147 sci_set_eol_mode(doc->editor->sci, eol_mode);
3148 /* This might affect the status bar and document menu, so update them. */
3149 ui_update_statusbar(doc, -1);
3150 ui_document_show_hide(doc);
3152 document_undo_add_internal(doc, UNDO_RELOAD, data);
3153 break;
3155 default: break;
3158 g_free(action); /* free the action which was taken from the stack */
3160 update_changed_state(doc);
3161 ui_update_popup_reundo_items(doc);
3165 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
3167 undo_action *action;
3169 g_return_if_fail(doc != NULL);
3171 action = g_new0(undo_action, 1);
3172 action->type = type;
3173 action->data = data;
3175 g_trash_stack_push(&doc->priv->redo_actions, action);
3177 if (type != UNDO_SCINTILLA || !doc->changed)
3178 document_set_text_changed(doc, TRUE);
3180 ui_update_popup_reundo_items(doc);
3184 enum
3186 STATUS_CHANGED,
3187 STATUS_DISK_CHANGED,
3188 STATUS_READONLY
3191 static struct
3193 const gchar *name;
3194 GdkColor color;
3195 gboolean loaded;
3196 } document_status_styles[] = {
3197 { "geany-document-status-changed", {0}, FALSE },
3198 { "geany-document-status-disk-changed", {0}, FALSE },
3199 { "geany-document-status-readonly", {0}, FALSE }
3203 static gint document_get_status_id(GeanyDocument *doc)
3205 if (doc->changed)
3206 return STATUS_CHANGED;
3207 #ifdef USE_GIO_FILEMON
3208 else if (doc->priv->file_disk_status == FILE_CHANGED)
3209 #else
3210 else if (doc->priv->protected)
3211 #endif
3212 return STATUS_DISK_CHANGED;
3213 else if (doc->readonly)
3214 return STATUS_READONLY;
3216 return -1;
3220 /* returns an identifier that is to be set as a widget name or class to get it styled
3221 * depending on the document status (changed, readonly, etc.)
3222 * a NULL return value means default (unchanged) style */
3223 const gchar *document_get_status_widget_class(GeanyDocument *doc)
3225 gint status;
3227 g_return_val_if_fail(doc != NULL, NULL);
3229 status = document_get_status_id(doc);
3230 if (status < 0)
3231 return NULL;
3232 else
3233 return document_status_styles[status].name;
3238 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
3239 * Returned colors are red if the document has changes, green if the document is read-only
3240 * or simply @c NULL if the document is unmodified but writable.
3242 * @param doc The document to use.
3244 * @return The color for the document or @c NULL if the default color should be used. The color
3245 * object is owned by Geany and should not be modified or freed.
3247 * @since 0.16
3249 GEANY_API_SYMBOL
3250 const GdkColor *document_get_status_color(GeanyDocument *doc)
3252 gint status;
3254 g_return_val_if_fail(doc != NULL, NULL);
3256 status = document_get_status_id(doc);
3257 if (status < 0)
3258 return NULL;
3259 if (! document_status_styles[status].loaded)
3261 #if GTK_CHECK_VERSION(3, 0, 0)
3262 GdkRGBA color;
3263 GtkWidgetPath *path = gtk_widget_path_new();
3264 GtkStyleContext *ctx = gtk_style_context_new();
3265 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
3266 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
3267 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
3268 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
3269 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
3270 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
3271 gtk_style_context_set_path(ctx, path);
3272 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
3273 document_status_styles[status].color.red = 0xffff * color.red;
3274 document_status_styles[status].color.green = 0xffff * color.green;
3275 document_status_styles[status].color.blue = 0xffff * color.blue;
3276 document_status_styles[status].loaded = TRUE;
3277 gtk_widget_path_unref(path);
3278 g_object_unref(ctx);
3279 #else
3280 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
3281 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
3282 document_status_styles[status].name, NULL);
3283 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
3285 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
3286 document_status_styles[status].loaded = TRUE;
3287 g_free(path);
3288 #endif
3290 return &document_status_styles[status].color;
3294 /** Accessor function for @ref documents_array items.
3295 * @warning Always check the returned document is valid (@c doc->is_valid).
3296 * @param idx @c documents_array index.
3297 * @return The document, or @c NULL if @a idx is out of range.
3299 * @since 0.16
3301 GEANY_API_SYMBOL
3302 GeanyDocument *document_index(gint idx)
3304 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
3308 GeanyDocument *document_clone(GeanyDocument *old_doc)
3310 gchar *text;
3311 GeanyDocument *doc;
3312 ScintillaObject *old_sci;
3314 g_return_val_if_fail(old_doc, NULL);
3315 old_sci = old_doc->editor->sci;
3316 if (sci_has_selection(old_sci))
3317 text = sci_get_selection_contents(old_sci);
3318 else
3319 text = sci_get_contents(old_sci, -1);
3321 doc = document_new_file(NULL, old_doc->file_type, text);
3322 g_free(text);
3323 document_set_text_changed(doc, TRUE);
3325 /* copy file properties */
3326 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
3327 doc->editor->line_breaking = old_doc->editor->line_breaking;
3328 doc->editor->auto_indent = old_doc->editor->auto_indent;
3329 editor_set_indent(doc->editor, old_doc->editor->indent_type,
3330 old_doc->editor->indent_width);
3331 doc->readonly = old_doc->readonly;
3332 doc->has_bom = old_doc->has_bom;
3333 doc->priv->protected = 0;
3334 document_set_encoding(doc, old_doc->encoding);
3335 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
3336 sci_set_readonly(doc->editor->sci, doc->readonly);
3338 /* update ui */
3339 ui_document_show_hide(doc);
3340 return doc;
3344 /* @note If successful, this should always be followed up with a call to
3345 * document_close_all().
3346 * @return TRUE if all files were saved or had their changes discarded. */
3347 gboolean document_account_for_unsaved(void)
3349 guint i, p, page_count;
3351 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3352 /* iterate over documents in tabs order */
3353 for (p = 0; p < page_count; p++)
3355 GeanyDocument *doc = document_get_from_page(p);
3357 if (DOC_VALID(doc) && doc->changed)
3359 if (! dialogs_show_unsaved_file(doc))
3360 return FALSE;
3363 /* all documents should now be accounted for, so ignore any changes */
3364 foreach_document (i)
3366 documents[i]->changed = FALSE;
3368 return TRUE;
3372 static void force_close_all(void)
3374 guint i, len = documents_array->len;
3376 /* check all documents have been accounted for */
3377 for (i = 0; i < len; i++)
3379 if (documents[i]->is_valid)
3381 g_return_if_fail(!documents[i]->changed);
3384 main_status.closing_all = TRUE;
3386 foreach_document(i)
3388 document_close(documents[i]);
3391 main_status.closing_all = FALSE;
3395 gboolean document_close_all(void)
3397 if (! document_account_for_unsaved())
3398 return FALSE;
3400 force_close_all();
3402 return TRUE;
3406 /* *
3407 * Shows a message related to a document.
3409 * Use this whenever the user needs to see a document-related message,
3410 * for example when the file was externally modified or deleted.
3412 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3413 * @a response_1 response will be the default for the @c GtkInfoBar or
3414 * @c GtkDialog.
3416 * @param doc @c GeanyDocument.
3417 * @param msgtype The type of message.
3418 * @param response_cb A callback function called when there's a response.
3419 * @param btn_1 The first action area button.
3420 * @param response_1 The response for @a btn_1.
3421 * @param btn_2 The second action area button.
3422 * @param response_2 The response for @a btn_2.
3423 * @param btn_3 The third action area button.
3424 * @param response_3 The response for @a btn_3.
3425 * @param extra_text Text to show below the main message.
3426 * @param format The text format for the main message.
3427 * @param ... Used with @a format as in @c printf.
3429 * @since 1.25
3430 * */
3431 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3432 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3433 const gchar *btn_1, GtkResponseType response_1,
3434 const gchar *btn_2, GtkResponseType response_2,
3435 const gchar *btn_3, GtkResponseType response_3,
3436 const gchar *extra_text, const gchar *format, ...)
3438 va_list args;
3439 gchar *text, *markup;
3440 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3441 GtkWidget *info_widget, *parent;
3442 parent = document_get_notebook_child(doc);
3444 va_start(args, format);
3445 text = g_strdup_vprintf(format, args);
3446 va_end(args);
3448 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3449 g_free(text);
3451 info_widget = gtk_info_bar_new();
3452 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3453 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3455 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3457 if (btn_1)
3458 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3459 if (btn_2)
3460 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3461 if (btn_3)
3462 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3464 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3466 label = geany_wrap_label_new(NULL);
3467 gtk_label_set_markup(GTK_LABEL(label), markup);
3468 g_free(markup);
3470 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3472 hbox = gtk_hbox_new(FALSE, 12);
3473 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3475 switch (msgtype)
3477 case GTK_MESSAGE_INFO:
3478 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3479 break;
3480 case GTK_MESSAGE_WARNING:
3481 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3482 break;
3483 case GTK_MESSAGE_QUESTION:
3484 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3485 break;
3486 case GTK_MESSAGE_ERROR:
3487 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3488 break;
3489 default:
3490 icon = NULL;
3491 break;
3494 if (icon)
3495 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3497 if (extra_text)
3499 vbox = gtk_vbox_new(FALSE, 6);
3500 extra_label = geany_wrap_label_new(extra_text);
3501 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3502 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3503 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3505 else
3506 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3508 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3510 gtk_widget_show_all(info_widget);
3512 return info_widget;
3516 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3518 gboolean close = FALSE;
3520 // disable info bar so actions complete normally
3521 unprotect_document(doc);
3522 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3524 if (response_id == RESPONSE_DOCUMENT_RELOAD)
3526 close = doc->changed ?
3527 document_reload_prompt(doc, doc->encoding) :
3528 document_reload_force(doc, doc->encoding);
3530 else if (response_id == RESPONSE_DOCUMENT_SAVE)
3532 close = document_save_file(doc, TRUE); // force overwrite
3534 else if (response_id == GTK_RESPONSE_CANCEL)
3536 document_set_text_changed(doc, TRUE);
3537 close = TRUE;
3539 if (!close)
3541 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3542 protect_document(doc);
3543 return;
3545 gtk_widget_destroy(bar);
3549 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3551 GtkInfoBar *bar = GTK_INFO_BAR(data);
3553 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3555 switch (event->keyval)
3557 case GDK_Tab:
3558 case GDK_ISO_Left_Tab:
3560 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3561 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3562 gtk_widget_child_focus(action_area, dir);
3563 return TRUE;
3565 case GDK_Escape:
3567 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3568 return TRUE;
3570 default:
3571 return FALSE;
3576 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3577 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3579 /* automatically focus editor again on bar close */
3580 g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3581 G_CONNECT_SWAPPED);
3582 g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3586 static void monitor_reload_file(GeanyDocument *doc)
3588 gchar *base_name = g_path_get_basename(doc->file_name);
3590 /* show this message only once */
3591 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3593 GtkWidget *bar;
3595 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3596 _("_Reload"), RESPONSE_DOCUMENT_RELOAD,
3597 _("_Overwrite"), RESPONSE_DOCUMENT_SAVE,
3598 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3599 _("Do you want to reload it?"),
3600 _("The file '%s' on the disk is more recent than the current buffer."),
3601 base_name);
3603 protect_document(doc);
3604 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3605 enable_key_intercept(doc, bar);
3607 g_free(base_name);
3611 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3612 gint response_id,
3613 GeanyDocument *doc)
3615 gboolean close = TRUE;
3617 unprotect_document(doc);
3619 if (response_id == RESPONSE_DOCUMENT_SAVE)
3620 close = dialogs_show_save_as();
3622 if (close)
3624 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3625 gtk_widget_destroy(bar);
3627 else
3629 /* protect back the document if save didn't occur */
3630 protect_document(doc);
3635 static void monitor_resave_missing_file(GeanyDocument *doc)
3637 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3639 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3641 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3642 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3644 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3645 on_monitor_resave_missing_file_response,
3646 GTK_STOCK_SAVE, RESPONSE_DOCUMENT_SAVE,
3647 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3648 NULL, GTK_RESPONSE_NONE,
3649 _("Try to resave the file?"),
3650 _("File \"%s\" was not found on disk!"),
3651 doc->file_name);
3653 protect_document(doc);
3654 document_set_text_changed(doc, TRUE);
3655 /* don't prompt more than once */
3656 SETPTR(doc->real_path, NULL);
3657 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3658 enable_key_intercept(doc, bar);
3663 /* Set force to force a disk check, otherwise it is ignored if there was a check
3664 * in the last file_prefs.disk_check_timeout seconds.
3665 * @return @c TRUE if the file has changed. */
3666 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3668 gboolean ret = FALSE;
3669 gboolean use_gio_filemon;
3670 time_t cur_time = 0;
3671 time_t mtime;
3672 gchar *locale_filename;
3673 FileDiskStatus old_status;
3675 g_return_val_if_fail(doc != NULL, FALSE);
3677 /* ignore remote files and documents that have never been saved to disk */
3678 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3679 || doc->real_path == NULL || doc->priv->is_remote)
3680 return FALSE;
3682 use_gio_filemon = (doc->priv->monitor != NULL);
3684 if (use_gio_filemon)
3686 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3687 return FALSE;
3689 else
3691 cur_time = time(NULL);
3692 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3693 return FALSE;
3695 doc->priv->last_check = cur_time;
3698 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3699 if (!get_mtime(locale_filename, &mtime))
3701 monitor_resave_missing_file(doc);
3702 /* doc may be closed now */
3703 ret = TRUE;
3705 else if (doc->priv->mtime < mtime)
3707 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3708 doc->priv->mtime = mtime;
3709 monitor_reload_file(doc);
3710 /* doc may be closed now */
3711 ret = TRUE;
3713 g_free(locale_filename);
3715 if (DOC_VALID(doc))
3716 { /* doc can get invalid when a document was closed */
3717 old_status = doc->priv->file_disk_status;
3718 doc->priv->file_disk_status = FILE_OK;
3719 if (old_status != doc->priv->file_disk_status)
3720 ui_update_tab_status(doc);
3722 return ret;
3726 /** Compares documents by their display names.
3727 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3728 * @note 'Display name' means the base name of the document's filename.
3730 * @param a @c GeanyDocument**.
3731 * @param b @c GeanyDocument**.
3732 * @warning The arguments take the address of each document pointer.
3733 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3735 * @since 0.21
3737 GEANY_API_SYMBOL
3738 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3740 GeanyDocument *doc_a = *((GeanyDocument**) a);
3741 GeanyDocument *doc_b = *((GeanyDocument**) b);
3742 gchar *base_name_a, *base_name_b;
3743 gint result;
3745 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3746 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3748 result = strcmp(base_name_a, base_name_b);
3750 g_free(base_name_a);
3751 g_free(base_name_b);
3753 return result;
3757 /** Compares documents by their tab order.
3758 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3760 * @param a @c GeanyDocument**.
3761 * @param b @c GeanyDocument**.
3762 * @warning The arguments take the address of each document pointer.
3763 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3765 * @since 0.21 (GEANY_API_VERSION 209)
3767 GEANY_API_SYMBOL
3768 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3770 GeanyDocument *doc_a = *((GeanyDocument**) a);
3771 GeanyDocument *doc_b = *((GeanyDocument**) b);
3772 gint notebook_position_doc_a;
3773 gint notebook_position_doc_b;
3775 notebook_position_doc_a = document_get_notebook_page(doc_a);
3776 notebook_position_doc_b = document_get_notebook_page(doc_b);
3778 if (notebook_position_doc_a < notebook_position_doc_b)
3779 return -1;
3780 if (notebook_position_doc_a > notebook_position_doc_b)
3781 return 1;
3782 /* equality */
3783 return 0;
3787 /** Compares documents by their tab order, in reverse order.
3788 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3790 * @param a @c GeanyDocument**.
3791 * @param b @c GeanyDocument**.
3792 * @warning The arguments take the address of each document pointer.
3793 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3795 * @since 0.21 (GEANY_API_VERSION 209)
3797 GEANY_API_SYMBOL
3798 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3800 return -1 * document_compare_by_tab_order(a, b);
3804 void document_grab_focus(GeanyDocument *doc)
3806 g_return_if_fail(doc != NULL);
3808 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));