Set errno to 0 before doing disk I/O to prevent confusing error
[geany-mirror.git] / src / document.c
blobc3a1bf27d0bd3844d7f2c04f9d4a36f992423799
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 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
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * $Id$
25 * Document related actions: new, save, open, etc.
26 * Also Scintilla search actions.
29 #include "geany.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #include <time.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <errno.h>
40 #ifdef HAVE_SYS_TYPES_H
41 # include <sys/types.h>
42 #endif
44 #include <stdlib.h>
46 /* gstdio.h also includes sys/stat.h */
47 #include <glib/gstdio.h>
49 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
50 /*#define USE_GIO_FILEMON 1*/
51 #ifdef HAVE_GIO
52 # include <gio/gio.h>
53 #else
54 # if USE_GIO_FILEMON
55 # undef USE_GIO_FILEMON
56 # endif
57 #endif
59 #include "document.h"
60 #include "documentprivate.h"
61 #include "filetypes.h"
62 #include "support.h"
63 #include "sciwrappers.h"
64 #include "editor.h"
65 #include "dialogs.h"
66 #include "msgwindow.h"
67 #include "templates.h"
68 #include "sidebar.h"
69 #include "ui_utils.h"
70 #include "utils.h"
71 #include "encodings.h"
72 #include "notebook.h"
73 #include "main.h"
74 #include "vte.h"
75 #include "build.h"
76 #include "symbols.h"
77 #include "highlighting.h"
78 #include "navqueue.h"
79 #include "win32.h"
80 #include "search.h"
81 #include "filetypesprivate.h"
84 GeanyFilePrefs file_prefs;
86 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
87 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
88 * to a document over time, but it might no longer represent a notebook tab. To check this,
89 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
90 * file by then.
92 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
93 * although usually you would just use the foreach_document() macro.
95 * Never assume that the order of document pointers is the same as the order of notebook tabs.
96 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
97 GPtrArray *documents_array = NULL;
100 /* an undo action, also used for redo actions */
101 typedef struct
103 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
104 guint type; /* to identify the action */
105 gpointer *data; /* the old value (before the change), in case of a redo action
106 * it contains the new value */
107 } undo_action;
110 static void document_undo_clear(GeanyDocument *doc);
111 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
112 static gboolean update_tags_from_buffer(GeanyDocument *doc);
115 /* ignore the case of filenames and paths under WIN32, causes errors if not */
116 #ifdef G_OS_WIN32
117 #define filenamecmp(a, b) utils_str_casecmp((a), (b))
118 #else
119 #define filenamecmp(a, b) strcmp((a), (b))
120 #endif
123 * Finds a document whose @c real_path field matches the given filename.
125 * @param realname The filename to search, which should be identical to the
126 * string returned by @c tm_get_real_path().
128 * @return The matching document, or @c NULL.
129 * @note This is only really useful when passing a @c TMWorkObject::file_name.
130 * @see GeanyDocument::real_path.
131 * @see document_find_by_filename().
133 * @since 0.15
135 GeanyDocument* document_find_by_real_path(const gchar *realname)
137 guint i;
139 if (! realname)
140 return NULL; /* file doesn't exist on disk */
142 for (i = 0; i < documents_array->len; i++)
144 GeanyDocument *doc = documents[i];
146 if (! doc->is_valid || G_UNLIKELY(! doc->real_path))
147 continue;
149 if (filenamecmp(realname, doc->real_path) == 0)
151 return doc;
154 return NULL;
158 /* dereference symlinks, /../ junk in path and return locale encoding */
159 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
161 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
162 gchar *realname = tm_get_real_path(locale_name);
164 g_free(locale_name);
165 return realname;
170 * Finds a document with the given filename.
171 * This matches either an exact GeanyDocument::file_name string, or variant
172 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
173 * match @c "/name").
175 * @param utf8_filename The filename to search (in UTF-8 encoding).
177 * @return The matching document, or @c NULL.
178 * @see document_find_by_real_path().
180 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
182 guint i;
183 GeanyDocument *doc;
184 gchar *realname;
186 g_return_val_if_fail(utf8_filename != NULL, NULL);
188 /* First search GeanyDocument::file_name, so we can find documents with a
189 * filename set but not saved on disk, like vcdiff produces */
190 for (i = 0; i < documents_array->len; i++)
192 doc = documents[i];
194 if (! doc->is_valid || G_UNLIKELY(doc->file_name == NULL))
195 continue;
197 if (filenamecmp(utf8_filename, doc->file_name) == 0)
199 return doc;
202 /* Now try matching based on the realpath(), which is unique per file on disk */
203 realname = get_real_path_from_utf8(utf8_filename);
204 doc = document_find_by_real_path(realname);
205 g_free(realname);
206 return doc;
210 /* returns the document which has sci, or NULL. */
211 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
213 guint i;
215 g_return_val_if_fail(sci != NULL, NULL);
217 for (i = 0; i < documents_array->len; i++)
219 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
220 return documents[i];
222 return NULL;
226 /** Gets the notebook page index for a document.
227 * @param doc The document.
228 * @return The index.
229 * @since 0.19 */
230 gint document_get_notebook_page(GeanyDocument *doc)
232 g_return_val_if_fail(doc != NULL, -1);
234 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
235 GTK_WIDGET(doc->editor->sci));
240 * Finds the document for the given notebook page @a page_num.
242 * @param page_num The notebook page number to search.
244 * @return The corresponding document for the given notebook page, or @c NULL.
246 GeanyDocument *document_get_from_page(guint page_num)
248 ScintillaObject *sci;
250 if (page_num >= documents_array->len)
251 return NULL;
253 sci = (ScintillaObject*)gtk_notebook_get_nth_page(
254 GTK_NOTEBOOK(main_widgets.notebook), page_num);
256 return document_find_by_sci(sci);
261 * Finds the current document.
263 * @return A pointer to the current document or @c NULL if there are no opened documents.
265 GeanyDocument *document_get_current(void)
267 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
269 if (cur_page == -1)
270 return NULL;
271 else
273 ScintillaObject *sci = (ScintillaObject*)
274 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
276 return document_find_by_sci(sci);
281 void document_init_doclist()
283 documents_array = g_ptr_array_new();
287 void document_finalize()
289 g_ptr_array_free(documents_array, TRUE);
294 * Returns the last part of the filename of the given GeanyDocument. The result is also
295 * truncated to a maximum of @a length characters in case the filename is very long.
297 * @param doc The document to use.
298 * @param length The length of the resulting string or -1 to use a default value.
300 * @return The ellipsized last part of the filename of @a doc, should be freed when no
301 * longer needed.
303 * @since 0.17
305 /* TODO make more use of this */
306 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
308 gchar *base_name, *short_name;
310 g_return_val_if_fail(doc != NULL, NULL);
312 if (length < 0)
313 length = 30;
315 base_name = g_path_get_basename(DOC_FILENAME(doc));
316 short_name = utils_str_middle_truncate(base_name, length);
318 g_free(base_name);
320 return short_name;
324 void document_update_tab_label(GeanyDocument *doc)
326 gchar *short_name;
327 GtkWidget *parent;
329 g_return_if_fail(doc != NULL);
331 short_name = document_get_basename_for_display(doc, -1);
333 /* we need to use the event box for the tooltip, labels don't get the necessary events */
334 parent = gtk_widget_get_parent(doc->priv->tab_label);
335 parent = gtk_widget_get_parent(parent);
337 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
339 ui_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
341 g_free(short_name);
346 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
347 * according to the document's save state.
348 * This is called by Geany mostly when opening or saving files.
350 * @param doc The document to use.
351 * @param changed Whether the document state should indicate changes have been made.
353 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
355 g_return_if_fail(doc != NULL);
357 doc->changed = changed;
359 if (! main_status.quitting)
361 ui_update_tab_status(doc);
362 ui_save_buttons_toggle(changed);
363 ui_set_window_title(doc);
364 ui_update_statusbar(doc, -1);
369 /* Sets is_valid to FALSE and initializes some members to NULL, to mark it uninitialized.
370 * The flag is_valid is set to TRUE in document_create(). */
371 static void init_doc_struct(GeanyDocument *new_doc)
373 GeanyDocumentPrivate *priv;
375 memset(new_doc, 0, sizeof(GeanyDocument));
377 new_doc->is_valid = FALSE;
378 new_doc->has_tags = FALSE;
379 new_doc->readonly = FALSE;
380 new_doc->file_name = NULL;
381 new_doc->file_type = NULL;
382 new_doc->tm_file = NULL;
383 new_doc->encoding = NULL;
384 new_doc->has_bom = FALSE;
385 new_doc->editor = NULL;
386 new_doc->changed = FALSE;
387 new_doc->real_path = NULL;
389 new_doc->priv = g_new0(GeanyDocumentPrivate, 1);
390 priv = new_doc->priv;
391 priv->tag_store = NULL;
392 priv->tag_tree = NULL;
393 priv->saved_encoding.encoding = NULL;
394 priv->saved_encoding.has_bom = FALSE;
395 priv->undo_actions = NULL;
396 priv->redo_actions = NULL;
397 priv->line_count = 0;
398 #if ! defined(USE_GIO_FILEMON)
399 priv->last_check = time(NULL);
400 #endif
404 /* returns the next free place in the document list,
405 * or -1 if the documents_array is full */
406 static gint document_get_new_idx(void)
408 guint i;
410 for (i = 0; i < documents_array->len; i++)
412 if (documents[i]->editor == NULL)
414 return (gint) i;
417 return -1;
421 static void queue_colourise(GeanyDocument *doc)
423 /* Colourise the editor before it is next drawn */
424 doc->priv->colourise_needed = TRUE;
426 /* If the editor doesn't need drawing (e.g. after saving the current
427 * document), we need to force a redraw, so the expose event is triggered.
428 * This ensures we don't start colourising before all documents are opened/saved,
429 * only once the editor is drawn. */
430 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
434 #if USE_GIO_FILEMON
435 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
436 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
437 GeanyDocument *doc)
439 g_return_if_fail(doc != NULL);
441 if (file_prefs.disk_check_timeout == 0)
442 return;
444 geany_debug("%s: event: %d previous file status: %d",
445 G_STRFUNC, event, doc->priv->file_disk_status);
446 switch (event)
448 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
450 if (doc->priv->file_disk_status == FILE_IGNORE)
451 doc->priv->file_disk_status = FILE_OK;
452 else
453 doc->priv->file_disk_status = FILE_CHANGED;
454 g_message("%s: FILE_CHANGED", G_STRFUNC);
455 break;
457 case G_FILE_MONITOR_EVENT_DELETED:
459 doc->priv->file_disk_status = FILE_CHANGED;
460 g_message("%s: FILE_MISSING", G_STRFUNC);
461 break;
463 default:
464 break;
466 if (doc->priv->file_disk_status != FILE_OK)
468 ui_update_tab_status(doc);
471 #endif
474 static void document_stop_file_monitoring(GeanyDocument *doc)
476 g_return_if_fail(doc != NULL);
478 if (doc->priv->monitor != NULL)
480 g_object_unref(doc->priv->monitor);
481 doc->priv->monitor = NULL;
486 static void monitor_file_setup(GeanyDocument *doc)
488 g_return_if_fail(doc != NULL);
489 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
490 * doesn't work at all for remote files and legacy polling is too slow. */
491 if (! doc->priv->is_remote)
493 #if USE_GIO_FILEMON
494 gchar *locale_filename;
496 /* stop any previous monitoring */
497 document_stop_file_monitoring(doc);
499 locale_filename = utils_get_locale_from_utf8(doc->file_name);
500 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
502 /* get a file monitor and connect to the 'changed' signal */
503 GFile *file = g_file_new_for_path(locale_filename);
504 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
505 g_signal_connect(doc->priv->monitor, "changed",
506 G_CALLBACK(monitor_file_changed_cb), doc);
508 /* we set the rate limit according to the GUI pref but it's most probably not used */
509 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
511 g_object_unref(file);
513 g_free(locale_filename);
514 #endif
516 doc->priv->file_disk_status = FILE_OK;
520 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
522 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
523 if (DOC_VALID(doc))
525 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
526 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
528 if (source_widget == NULL)
529 source_widget = doc->priv->tag_tree;
531 if (focusw == source_widget)
532 gtk_widget_grab_focus(sci);
537 static gboolean on_idle_focus(gpointer doc)
539 document_try_focus(doc, NULL);
540 return FALSE;
544 static gboolean remove_page(guint page_num);
546 /* Creates a new document and editor, adding a tab in the notebook.
547 * @return The created document */
548 static GeanyDocument *document_create(const gchar *utf8_filename)
550 GeanyDocument *doc;
551 gint new_idx;
552 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
554 if (cur_pages == 1)
556 GeanyDocument *cur = document_get_current();
557 /* remove the empty document first */
558 if (cur != NULL && cur->file_name == NULL && ! cur->changed)
559 /* prevent immediately opening another new doc with
560 * new_document_after_close pref */
561 remove_page(0);
564 new_idx = document_get_new_idx();
565 if (new_idx == -1) /* expand the array, no free places */
567 GeanyDocument *new_doc = g_new0(GeanyDocument, 1);
569 new_idx = documents_array->len;
570 g_ptr_array_add(documents_array, new_doc);
572 doc = documents[new_idx];
573 init_doc_struct(doc); /* initialize default document settings */
574 doc->index = new_idx;
576 doc->file_name = g_strdup(utf8_filename);
578 doc->editor = editor_create(doc);
580 sidebar_openfiles_add(doc); /* sets doc->iter */
582 notebook_new_tab(doc);
584 /* select document in sidebar */
586 GtkTreeSelection *sel;
588 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
589 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
592 ui_document_buttons_update();
594 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
595 return doc;
600 * Closes the given document.
602 * @param doc The document to remove.
604 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
606 * @since 0.15
608 gboolean document_close(GeanyDocument *doc)
610 g_return_val_if_fail(doc, FALSE);
612 return document_remove_page(document_get_notebook_page(doc));
616 /* Call document_remove_page() instead, this is only needed for document_create(). */
617 static gboolean remove_page(guint page_num)
619 GeanyDocument *doc = document_get_from_page(page_num);
621 if (G_UNLIKELY(doc == NULL))
623 g_warning("%s: page_num: %d", G_STRFUNC, page_num);
624 return FALSE;
627 if (doc->changed && ! dialogs_show_unsaved_file(doc))
629 return FALSE;
632 /* tell any plugins that the document is about to be closed */
633 g_signal_emit_by_name(geany_object, "document-close", doc);
635 /* Checking real_path makes it likely the file exists on disk */
636 if (! main_status.closing_all && doc->real_path != NULL)
637 ui_add_recent_file(doc->file_name);
639 doc->is_valid = FALSE;
641 if (! main_status.quitting)
643 notebook_remove_page(page_num);
644 sidebar_remove_document(doc);
645 navqueue_remove_file(doc->file_name);
646 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
648 g_free(doc->encoding);
649 g_free(doc->priv->saved_encoding.encoding);
650 g_free(doc->file_name);
651 g_free(doc->real_path);
652 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
654 editor_destroy(doc->editor);
655 doc->editor = NULL;
657 document_stop_file_monitoring(doc);
659 doc->file_name = NULL;
660 doc->real_path = NULL;
661 doc->file_type = NULL;
662 doc->encoding = NULL;
663 doc->has_bom = FALSE;
664 doc->tm_file = NULL;
665 document_undo_clear(doc);
666 g_free(doc->priv);
668 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
670 sidebar_update_tag_list(NULL, FALSE);
671 /*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
672 ui_set_window_title(NULL);
673 ui_save_buttons_toggle(FALSE);
674 ui_update_popup_reundo_items(NULL);
675 ui_document_buttons_update();
676 build_menu_update(NULL);
678 return TRUE;
683 * Removes the given notebook tab at @a page_num and clears all related information
684 * in the document list.
686 * @param page_num The notebook page number to remove.
688 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
690 gboolean document_remove_page(guint page_num)
692 gboolean done = remove_page(page_num);
694 if (done && ui_prefs.new_document_after_close)
695 document_new_file_if_non_open();
697 return done;
701 /* used to keep a record of the unchanged document state encoding */
702 static void store_saved_encoding(GeanyDocument *doc)
704 g_free(doc->priv->saved_encoding.encoding);
705 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
706 doc->priv->saved_encoding.has_bom = doc->has_bom;
710 /* Opens a new empty document only if there are no other documents open */
711 GeanyDocument *document_new_file_if_non_open(void)
713 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
714 return document_new_file(NULL, NULL, NULL);
716 return NULL;
721 * Creates a new document.
722 * Line endings in @a text will be converted to the default setting.
723 * Afterwards, the @c "document-new" signal is emitted for plugins.
725 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
726 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
727 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
729 * @return The new document.
731 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
733 GeanyDocument *doc;
735 if (utf8_filename && g_path_is_absolute(utf8_filename))
737 gchar *tmp;
738 tmp = utils_strdupa(utf8_filename); /* work around const */
739 utils_tidy_path(tmp);
740 utf8_filename = tmp;
742 doc = document_create(utf8_filename);
744 g_assert(doc != NULL);
746 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
747 if (text)
749 GString *template = g_string_new(text);
750 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
752 sci_set_text(doc->editor->sci, template->str);
753 g_string_free(template, TRUE);
755 else
756 sci_clear_all(doc->editor->sci);
758 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
760 sci_set_undo_collection(doc->editor->sci, TRUE);
761 sci_empty_undo_buffer(doc->editor->sci);
763 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
764 /* store the opened encoding for undo/redo */
765 store_saved_encoding(doc);
767 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
768 ft = filetypes_detect_from_document(doc);
770 document_set_filetype(doc, ft); /* also clears taglist */
772 ui_set_window_title(doc);
773 build_menu_update(doc);
774 document_update_tag_list(doc, FALSE);
775 document_set_text_changed(doc, FALSE);
776 ui_document_show_hide(doc); /* update the document menu */
778 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
779 /* bring it in front, jump to the start and grab the focus */
780 editor_goto_pos(doc->editor, 0, FALSE);
781 document_try_focus(doc, NULL);
783 #if USE_GIO_FILEMON
784 monitor_file_setup(doc);
785 #else
786 doc->priv->mtime = time(NULL);
787 #endif
789 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
790 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
792 g_signal_emit_by_name(geany_object, "document-new", doc);
794 msgwin_status_add(_("New file \"%s\" opened."),
795 DOC_FILENAME(doc));
797 return doc;
802 * Opens a document specified by @a locale_filename.
803 * Afterwards, the @c "document-open" signal is emitted for plugins.
805 * @param locale_filename The filename of the document to load, in locale encoding.
806 * @param readonly Whether to open the document in read-only mode.
807 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
808 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
810 * @return The document opened or @c NULL.
812 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
813 GeanyFiletype *ft, const gchar *forced_enc)
815 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
819 typedef struct
821 gchar *data; /* null-terminated file data */
822 gsize size; /* actual file size on disk */
823 gsize len; /* string length of data */
824 gchar *enc;
825 gboolean bom;
826 time_t mtime; /* modification time, read by stat::st_mtime */
827 gboolean readonly;
828 } FileData;
831 /* reload file with specified encoding */
832 static gboolean
833 handle_forced_encoding(FileData *filedata, const gchar *forced_enc)
835 GeanyEncodingIndex enc_idx;
837 if (utils_str_equal(forced_enc, "UTF-8"))
839 if (! g_utf8_validate(filedata->data, filedata->len, NULL))
841 return FALSE;
844 else
846 gchar *converted_text = encodings_convert_to_utf8_from_charset(
847 filedata->data, filedata->size, forced_enc, FALSE);
848 if (converted_text == NULL)
850 return FALSE;
852 else
854 g_free(filedata->data);
855 filedata->data = converted_text;
856 filedata->len = strlen(converted_text);
859 enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
860 filedata->bom = (enc_idx == GEANY_ENCODING_UTF_8);
861 filedata->enc = g_strdup(forced_enc);
862 return TRUE;
866 /* detect encoding and convert to UTF-8 if necessary */
867 static gboolean
868 handle_encoding(FileData *filedata, GeanyEncodingIndex enc_idx)
870 g_return_val_if_fail(filedata->enc == NULL, FALSE);
871 g_return_val_if_fail(filedata->bom == FALSE, FALSE);
873 if (filedata->size == 0)
875 /* we have no data so assume UTF-8, filedata->len can be 0 even we have an empty
876 * e.g. UTF32 file with a BOM(so size is 4, len is 0) */
877 filedata->enc = g_strdup("UTF-8");
879 else
881 /* first check for a BOM */
882 if (enc_idx != GEANY_ENCODING_NONE)
884 filedata->enc = g_strdup(encodings[enc_idx].charset);
885 filedata->bom = TRUE;
887 if (enc_idx != GEANY_ENCODING_UTF_8) /* the BOM indicated something else than UTF-8 */
889 gchar *converted_text = encodings_convert_to_utf8_from_charset(
890 filedata->data, filedata->size, filedata->enc, FALSE);
891 if (converted_text != NULL)
893 g_free(filedata->data);
894 filedata->data = converted_text;
895 filedata->len = strlen(converted_text);
897 else
899 /* there was a problem converting data from BOM encoding type */
900 g_free(filedata->enc);
901 filedata->enc = NULL;
902 filedata->bom = FALSE;
907 if (filedata->enc == NULL) /* either there was no BOM or the BOM encoding failed */
909 /* try UTF-8 first */
910 if ((filedata->size == filedata->len) &&
911 g_utf8_validate(filedata->data, filedata->len, NULL))
913 filedata->enc = g_strdup("UTF-8");
915 else
917 /* detect the encoding */
918 gchar *converted_text = encodings_convert_to_utf8(filedata->data,
919 filedata->size, &filedata->enc);
921 if (converted_text == NULL)
923 return FALSE;
925 g_free(filedata->data);
926 filedata->data = converted_text;
927 filedata->len = strlen(converted_text);
931 return TRUE;
935 static void
936 handle_bom(FileData *filedata)
938 guint bom_len;
940 encodings_scan_unicode_bom(filedata->data, filedata->size, &bom_len);
941 g_return_if_fail(bom_len != 0);
943 /* use filedata->len here because the contents are already converted into UTF-8 */
944 filedata->len -= bom_len;
945 /* overwrite the BOM with the remainder of the file contents, plus the NULL terminator. */
946 g_memmove(filedata->data, filedata->data + bom_len, filedata->len + 1);
947 filedata->data = g_realloc(filedata->data, filedata->len + 1);
951 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
952 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
953 FileData *filedata, const gchar *forced_enc)
955 GError *err = NULL;
956 struct stat st;
957 GeanyEncodingIndex tmp_enc_idx;
959 filedata->data = NULL;
960 filedata->len = 0;
961 filedata->enc = NULL;
962 filedata->bom = FALSE;
963 filedata->readonly = FALSE;
965 if (g_stat(locale_filename, &st) != 0)
967 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
968 display_filename, g_strerror(errno));
969 return FALSE;
972 filedata->mtime = st.st_mtime;
974 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
976 ui_set_statusbar(TRUE, "%s", err->message);
977 g_error_free(err);
978 return FALSE;
981 /* use strlen to check for null chars */
982 filedata->size = (gsize) st.st_size;
983 filedata->len = strlen(filedata->data);
985 /* temporarily retrieve the encoding idx based on the BOM to suppress the following warning
986 * if we have a BOM */
987 tmp_enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
989 /* check whether the size of the loaded data is equal to the size of the file in the
990 * filesystem file size may be 0 to allow opening files in /proc/ which have typically a
991 * file size of 0 bytes */
992 if (filedata->len != filedata->size && filedata->size != 0 && (
993 tmp_enc_idx == GEANY_ENCODING_UTF_8 || /* tmp_enc_idx can be UTF-7/8/16/32, UCS and None */
994 tmp_enc_idx == GEANY_ENCODING_UTF_7)) /* filter UTF-7/8 where no NULL bytes are allowed */
996 const gchar *warn_msg = _(
997 "The file \"%s\" could not be opened properly and has been truncated. " \
998 "This can occur if the file contains a NULL byte. " \
999 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1001 if (main_status.main_window_realized)
1002 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
1004 ui_set_statusbar(TRUE, warn_msg, display_filename);
1006 /* set the file to read-only mode because saving it is probably dangerous */
1007 filedata->readonly = TRUE;
1010 /* Determine character encoding and convert to UTF-8 */
1011 if (forced_enc != NULL)
1013 /* the encoding should be ignored(requested by user), so open the file "as it is" */
1014 if (utils_str_equal(forced_enc, encodings[GEANY_ENCODING_NONE].charset))
1016 filedata->bom = FALSE;
1017 filedata->enc = g_strdup(encodings[GEANY_ENCODING_NONE].charset);
1019 else if (! handle_forced_encoding(filedata, forced_enc))
1021 /* For translators: the second wildcard is an encoding name, e.g.
1022 * The file \"test.txt\" is not valid UTF-8. */
1023 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
1024 display_filename, forced_enc);
1025 utils_beep();
1026 g_free(filedata->data);
1027 return FALSE;
1030 else if (! handle_encoding(filedata, tmp_enc_idx))
1032 ui_set_statusbar(TRUE,
1033 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1034 display_filename);
1035 utils_beep();
1036 g_free(filedata->data);
1037 return FALSE;
1040 if (filedata->bom)
1041 handle_bom(filedata);
1042 return TRUE;
1046 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1047 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1048 * if cl_options.goto_column is set.
1050 * returns the new position which may have changed */
1051 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1053 if (cl_options.goto_line >= 0)
1054 { /* goto line which was specified on command line and then undefine the line */
1055 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1056 editor->scroll_percent = 0.5F;
1057 cl_options.goto_line = -1;
1059 else if (pos > 0)
1061 sci_set_current_position(editor->sci, pos, FALSE);
1062 editor->scroll_percent = 0.5F;
1065 if (cl_options.goto_column >= 0)
1066 { /* goto column which was specified on command line and then undefine the column */
1068 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1069 sci_set_current_position(editor->sci, new_pos, FALSE);
1070 editor->scroll_percent = 0.5F;
1071 cl_options.goto_column = -1;
1072 return new_pos;
1074 return sci_get_current_position(editor->sci);
1078 /* Count lines that start with some hard tabs then a soft tab. */
1079 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1081 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1082 ScintillaObject *sci = editor->sci;
1083 gsize count = 0;
1084 struct Sci_TextToFind ttf;
1085 gchar *soft_tab = g_strnfill(iprefs->width, ' ');
1086 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1088 g_free(soft_tab);
1090 ttf.chrg.cpMin = 0;
1091 ttf.chrg.cpMax = sci_get_length(sci);
1092 ttf.lpstrText = regex;
1093 while (1)
1095 gint pos;
1097 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1098 if (pos == -1)
1099 break; /* no more matches */
1100 count++;
1101 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1103 g_free(regex);
1104 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1105 return count > sci_get_line_count(sci) * 0.02;
1109 /* Detect the indent type based on counting the leading indent characters for each line. */
1110 static GeanyIndentType detect_indent_type(GeanyEditor *editor)
1112 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1113 ScintillaObject *sci = editor->sci;
1114 guint line, line_count;
1115 gsize tabs = 0, spaces = 0;
1117 if (detect_tabs_and_spaces(editor))
1118 return GEANY_INDENT_TYPE_BOTH;
1120 line_count = sci_get_line_count(sci);
1121 for (line = 0; line < line_count; line++)
1123 gint pos = sci_get_position_from_line(sci, line);
1124 gchar c;
1126 /* most code will have indent total <= 24, otherwise it's more likely to be
1127 * alignment than indentation */
1128 if (sci_get_line_indentation(sci, line) > 24)
1129 continue;
1131 c = sci_get_char_at(sci, pos);
1132 if (c == '\t')
1133 tabs++;
1134 else
1135 if (c == ' ')
1137 /* check for at least 2 spaces */
1138 if (sci_get_char_at(sci, pos + 1) == ' ')
1139 spaces++;
1142 if (spaces == 0 && tabs == 0)
1143 return iprefs->type;
1145 /* the factors may need to be tweaked */
1146 if (spaces > tabs * 4)
1147 return GEANY_INDENT_TYPE_SPACES;
1148 else if (tabs > spaces * 4)
1149 return GEANY_INDENT_TYPE_TABS;
1150 else
1151 return GEANY_INDENT_TYPE_BOTH;
1155 void document_apply_indent_settings(GeanyDocument *doc)
1157 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1158 GeanyIndentType type = iprefs->type;
1160 switch (doc->file_type->id)
1162 case GEANY_FILETYPES_MAKE:
1163 /* force using tabs for indentation for Makefiles */
1164 editor_set_indent(doc->editor, GEANY_INDENT_TYPE_TABS, iprefs->width);
1165 return;
1166 case GEANY_FILETYPES_F77:
1167 /* force using spaces for indentation for Fortran 77 */
1168 editor_set_indent(doc->editor, GEANY_INDENT_TYPE_SPACES, iprefs->width);
1169 return;
1170 default:
1171 break;
1173 if (iprefs->detect_type)
1175 type = detect_indent_type(doc->editor);
1177 if (type != iprefs->type)
1179 const gchar *name = NULL;
1181 switch (type)
1183 case GEANY_INDENT_TYPE_SPACES:
1184 name = _("Spaces");
1185 break;
1186 case GEANY_INDENT_TYPE_TABS:
1187 name = _("Tabs");
1188 break;
1189 case GEANY_INDENT_TYPE_BOTH:
1190 name = _("Tabs and Spaces");
1191 break;
1193 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1194 * and Spaces), the second one is the filename */
1195 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1196 DOC_FILENAME(doc));
1199 editor_set_indent(doc->editor, type, iprefs->width);
1203 #if 0
1204 static gboolean auto_update_tag_list(gpointer data)
1206 GeanyDocument *doc = data;
1208 if (! doc || ! doc->is_valid || doc->tm_file == NULL)
1209 return FALSE;
1211 if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != GTK_WIDGET(doc->editor->sci))
1212 return TRUE;
1214 if (update_tags_from_buffer(doc))
1215 sidebar_update_tag_list(doc, TRUE);
1217 return TRUE;
1219 #endif
1222 /* To open a new file, set doc to NULL; filename should be locale encoded.
1223 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1224 * pos is the cursor position, which can be overridden by --line and --column.
1225 * forced_enc can be NULL to detect the file encoding.
1226 * Returns: doc of the opened file or NULL if an error occurred. */
1227 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1228 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1230 gint editor_mode;
1231 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1232 gchar *utf8_filename = NULL;
1233 gchar *display_filename = NULL;
1234 gchar *locale_filename = NULL;
1235 GeanyFiletype *use_ft;
1236 FileData filedata;
1238 if (reload)
1240 utf8_filename = g_strdup(doc->file_name);
1241 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1243 else
1245 /* filename must not be NULL when opening a file */
1246 if (filename == NULL)
1248 ui_set_statusbar(FALSE, _("Invalid filename"));
1249 return NULL;
1252 #ifdef G_OS_WIN32
1253 /* if filename is a shortcut, try to resolve it */
1254 locale_filename = win32_get_shortcut_target(filename);
1255 #else
1256 locale_filename = g_strdup(filename);
1257 #endif
1258 /* remove relative junk */
1259 utils_tidy_path(locale_filename);
1261 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1262 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1264 /* if file is already open, switch to it and go */
1265 doc = document_find_by_filename(utf8_filename);
1266 if (doc != NULL)
1268 ui_add_recent_file(utf8_filename); /* either add or reorder recent item */
1269 /* show the doc before reload dialog */
1270 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1271 gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
1272 (GtkWidget*) doc->editor->sci));
1273 document_check_disk_status(doc, TRUE); /* force a file changed check */
1276 if (reload || doc == NULL)
1277 { /* doc possibly changed */
1278 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1280 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1282 g_free(display_filename);
1283 g_free(utf8_filename);
1284 g_free(locale_filename);
1285 return NULL;
1288 if (! reload)
1290 doc = document_create(utf8_filename);
1291 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1293 /* file exists on disk, set real_path */
1294 setptr(doc->real_path, tm_get_real_path(locale_filename));
1296 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1297 monitor_file_setup(doc);
1300 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1301 sci_empty_undo_buffer(doc->editor->sci);
1303 /* add the text to the ScintillaObject */
1304 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1305 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1306 queue_colourise(doc); /* Ensure the document gets colourised. */
1308 /* detect & set line endings */
1309 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1310 sci_set_eol_mode(doc->editor->sci, editor_mode);
1311 g_free(filedata.data);
1313 sci_set_undo_collection(doc->editor->sci, TRUE);
1315 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1316 g_free(doc->encoding); /* if reloading, free old encoding */
1317 doc->encoding = filedata.enc;
1318 doc->has_bom = filedata.bom;
1319 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1321 doc->readonly = readonly || filedata.readonly;
1322 sci_set_readonly(doc->editor->sci, doc->readonly);
1324 /* update line number margin width */
1325 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1326 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1328 if (! reload)
1331 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1332 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1333 doc->editor);
1335 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1337 else
1338 { /* reloading */
1339 document_undo_clear(doc);
1341 use_ft = ft;
1343 /* update taglist, typedef keywords and build menu if necessary */
1344 document_set_filetype(doc, use_ft);
1346 /* set indentation settings after setting the filetype */
1347 if (reload)
1348 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1349 else
1350 document_apply_indent_settings(doc);
1352 document_set_text_changed(doc, FALSE); /* also updates tab state */
1353 ui_document_show_hide(doc); /* update the document menu */
1355 /* finally add current file to recent files menu, but not the files from the last session */
1356 if (! main_status.opening_session_files)
1357 ui_add_recent_file(utf8_filename);
1359 if (! reload)
1360 g_signal_emit_by_name(geany_object, "document-open", doc);
1362 if (reload)
1363 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1364 else
1365 /* For translators: this is the status window message for opening a file. %d is the number
1366 * of the newly opened file, %s indicates whether the file is opened read-only
1367 * (it is replaced with the string ", read-only"). */
1368 msgwin_status_add(_("File %s opened(%d%s)."),
1369 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1370 (readonly) ? _(", read-only") : "");
1373 g_free(display_filename);
1374 g_free(utf8_filename);
1375 g_free(locale_filename);
1377 /* TODO This could be used to automatically update the symbol list,
1378 * based on a configurable interval */
1379 /*g_timeout_add(10000, auto_update_tag_list, doc);*/
1381 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1382 pos = set_cursor_position(doc->editor, pos);
1383 /* now bring the file in front */
1384 editor_goto_pos(doc->editor, pos, FALSE);
1386 /* finally, let the editor widget grab the focus so you can start coding
1387 * right away */
1388 g_idle_add(on_idle_focus, doc);
1389 return doc;
1393 /* Takes a new line separated list of filename URIs and opens each file.
1394 * length is the length of the string or -1 if it should be detected */
1395 void document_open_file_list(const gchar *data, gssize length)
1397 gint i;
1398 gchar *filename;
1399 gchar **list;
1401 g_return_if_fail(data != NULL);
1403 if (length < 0)
1404 length = strlen(data);
1406 switch (utils_get_line_endings(data, length))
1408 case SC_EOL_CR: list = g_strsplit(data, "\r", 0); break;
1409 case SC_EOL_CRLF: list = g_strsplit(data, "\r\n", 0); break;
1410 case SC_EOL_LF: list = g_strsplit(data, "\n", 0); break;
1411 default: list = g_strsplit(data, "\n", 0);
1414 for (i = 0; ; i++)
1416 if (list[i] == NULL)
1417 break;
1418 filename = g_filename_from_uri(list[i], NULL, NULL);
1419 if (G_UNLIKELY(filename == NULL))
1420 continue;
1421 document_open_file(filename, FALSE, NULL, NULL);
1422 g_free(filename);
1425 g_strfreev(list);
1430 * Opens each file in the list @a filenames.
1431 * Internally, document_open_file() is called for every list item.
1433 * @param filenames A list of filenames to load, in locale encoding.
1434 * @param readonly Whether to open the document in read-only mode.
1435 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1436 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1438 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1439 const gchar *forced_enc)
1441 const GSList *item;
1443 for (item = filenames; item != NULL; item = g_slist_next(item))
1445 document_open_file(item->data, readonly, ft, forced_enc);
1451 * Reloads the document with the specified file encoding
1452 * @a forced_enc or @c NULL to auto-detect the file encoding.
1454 * @param doc The document to reload.
1455 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1457 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1459 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1461 gint pos = 0;
1462 GeanyDocument *new_doc;
1464 g_return_val_if_fail(doc != NULL, FALSE);
1466 /* try to set the cursor to the position before reloading */
1467 pos = sci_get_current_position(doc->editor->sci);
1468 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1470 return (new_doc != NULL);
1474 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1476 #if ! USE_GIO_FILEMON
1477 struct stat st;
1479 g_return_val_if_fail(doc != NULL, FALSE);
1481 /* stat the file to get the timestamp, otherwise on Windows the actual
1482 * timestamp can be ahead of time(NULL) */
1483 if (g_stat(locale_filename, &st) != 0)
1485 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1486 g_strerror(errno));
1487 return FALSE;
1490 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1491 #endif
1492 return TRUE;
1496 /* Sets line and column to the given position byte_pos in the document.
1497 * byte_pos is the position counted in bytes, not characters */
1498 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1500 gint i;
1501 gint line_start;
1503 /* for some reason we can use byte count instead of character count here */
1504 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1505 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1506 /* get the column in the line */
1507 *column = byte_pos - line_start;
1509 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1510 * skip one byte(i++) and decrease the column number which is based on byte count */
1511 for (i = line_start; i < (line_start + *column); i++)
1513 if (sci_get_char_at(doc->editor->sci, i) < 0)
1515 (*column)--;
1516 i++;
1522 static void replace_header_filename(GeanyDocument *doc)
1524 gchar *filebase;
1525 gchar *filename;
1526 struct Sci_TextToFind ttf;
1528 g_return_if_fail(doc != NULL);
1529 g_return_if_fail(doc->file_type != NULL);
1531 if (doc->file_type->extension)
1532 filebase = g_strconcat("\\<", GEANY_STRING_UNTITLED, "\\.\\w+", NULL);
1533 else
1534 filebase = g_strdup(GEANY_STRING_UNTITLED);
1536 filename = g_path_get_basename(doc->file_name);
1538 /* only search the first 3 lines */
1539 ttf.chrg.cpMin = 0;
1540 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 3);
1541 ttf.lpstrText = filebase;
1543 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf) != -1)
1545 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1546 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1547 sci_replace_target(doc->editor->sci, filename, FALSE);
1549 g_free(filebase);
1550 g_free(filename);
1555 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1556 * you still have to call @ref document_save_file_as() to change the @a doc object.
1557 * It also stops monitoring for file changes to prevent receiving too many file change events
1558 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1560 * @param doc The current document which should be renamed.
1561 * @param new_filename The new filename in UTF-8 encoding.
1563 * @since 0.16
1565 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1567 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1568 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1569 gint result;
1571 /* stop file monitoring to avoid getting events for deleting/creating files,
1572 * it's re-setup in document_save_file_as() */
1573 document_stop_file_monitoring(doc);
1575 result = g_rename(old_locale_filename, new_locale_filename);
1576 if (result != 0)
1578 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1579 _("Error renaming file."), g_strerror(errno));
1581 g_free(old_locale_filename);
1582 g_free(new_locale_filename);
1586 /* Return TRUE if the document doesn't have a full filename set.
1587 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1588 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1589 * new files. */
1590 gboolean document_need_save_as(GeanyDocument *doc)
1592 g_return_val_if_fail(doc != NULL, FALSE);
1594 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1599 * Saves the document, detecting the filetype.
1601 * @param doc The document for the file to save.
1602 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1603 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1605 * @see document_save_file().
1607 * @since 0.16
1609 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1611 gboolean ret;
1613 g_return_val_if_fail(doc != NULL, FALSE);
1615 if (utf8_fname != NULL)
1616 setptr(doc->file_name, g_strdup(utf8_fname));
1618 /* reset real path, it's retrieved again in document_save() */
1619 setptr(doc->real_path, NULL);
1621 /* detect filetype */
1622 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1624 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1626 document_set_filetype(doc, ft);
1627 if (document_get_current() == doc)
1629 ignore_callback = TRUE;
1630 filetypes_select_radio_item(doc->file_type);
1631 ignore_callback = FALSE;
1634 replace_header_filename(doc);
1636 ret = document_save_file(doc, TRUE);
1638 /* file monitoring support, add file monitoring after the file has been saved
1639 * to ignore any earlier events */
1640 monitor_file_setup(doc);
1641 doc->priv->file_disk_status = FILE_IGNORE;
1643 if (ret)
1644 ui_add_recent_file(doc->file_name);
1645 return ret;
1649 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1651 GError *conv_error = NULL;
1652 gchar* conv_file_contents = NULL;
1653 gsize bytes_read;
1654 gsize conv_len;
1656 g_return_val_if_fail(data != NULL || *data == NULL, FALSE);
1657 g_return_val_if_fail(len != NULL, FALSE);
1659 /* try to convert it from UTF-8 to original encoding */
1660 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1661 &bytes_read, &conv_len, &conv_error);
1663 if (conv_error != NULL)
1665 gchar *text = g_strdup_printf(
1666 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1667 doc->encoding);
1668 gchar *error_text;
1670 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1672 gchar *context = NULL;
1673 gint line, column;
1674 gint context_len;
1675 gunichar unic;
1676 /* don't read over the doc length */
1677 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1678 context = g_malloc(7); /* read 6 bytes from Sci + '\0' */
1679 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1681 /* take only one valid Unicode character from the context and discard the leftover */
1682 unic = g_utf8_get_char_validated(context, -1);
1683 context_len = g_unichar_to_utf8(unic, context);
1684 context[context_len] = '\0';
1685 get_line_column_from_pos(doc, bytes_read, &line, &column);
1687 error_text = g_strdup_printf(
1688 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1689 conv_error->message, context, line + 1, column);
1690 g_free(context);
1692 else
1693 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1695 geany_debug("encoding error: %s", conv_error->message);
1696 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1697 g_error_free(conv_error);
1698 g_free(text);
1699 g_free(error_text);
1700 return FALSE;
1702 else
1704 g_free(*data);
1705 *data = conv_file_contents;
1706 *len = conv_len;
1708 return TRUE;
1712 static gchar *write_data_to_disk(const gchar *locale_filename,
1713 const gchar *data, gint len)
1715 GError *error = NULL;
1717 if (! file_prefs.use_safe_file_saving)
1719 #ifdef HAVE_GIO
1720 GFile *fp;
1722 /* Use GIO API to save file (GVFS-safe) */
1723 fp = g_file_new_for_path(locale_filename);
1724 g_file_replace_contents(fp, data, len, NULL, FALSE,
1725 G_FILE_CREATE_NONE, NULL, NULL, &error);
1726 g_object_unref(fp);
1727 #else
1728 FILE *fp;
1729 gint bytes_written;
1730 gboolean fail = FALSE;
1732 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1733 errno = 0;
1734 fp = g_fopen(locale_filename, "wb");
1735 if (fp == NULL)
1736 fail = TRUE;
1737 else
1739 errno = 0;
1740 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1742 if (len != bytes_written)
1743 fail = TRUE;
1745 if (fclose(fp) != 0)
1746 fail = TRUE;
1748 if (fail)
1750 gint err = errno;
1751 if (!err)
1752 err = EIO;
1753 return g_strdup(g_strerror(err));
1755 #endif
1757 else
1759 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1760 * This is the only option that handles disk space exhaustion. */
1761 if (g_file_set_contents(locale_filename, data, len, &error))
1762 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1764 if (error != NULL)
1766 gchar *msg = g_strdup(error->message);
1767 g_error_free(error);
1768 return msg;
1770 return NULL;
1774 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1775 const gchar *data, gint len)
1777 gchar *err;
1779 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1780 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1782 err = write_data_to_disk(locale_filename, data, len);
1783 if (err)
1784 return err;
1786 /* now the file is on disk, set real_path */
1787 if (doc->real_path == NULL)
1789 doc->real_path = tm_get_real_path(locale_filename);
1790 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1791 monitor_file_setup(doc);
1793 return NULL;
1798 * Saves the document. Saving includes replacing tabs by spaces,
1799 * stripping trailing spaces and adding a final new line at the end of the file (all only if
1800 * user enabled these features). Then the @c "document-before-save" signal is emitted,
1801 * allowing plugins to modify the document before it is saved, and data is
1802 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1803 * Afterwards, the @c "document-save" signal is emitted for plugins.
1805 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1807 * @param doc The document to save.
1808 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1810 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1812 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1814 gchar *errmsg;
1815 gchar *data;
1816 gsize len;
1817 gchar *locale_filename;
1819 g_return_val_if_fail(doc != NULL, FALSE);
1821 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1822 if (! force && ! ui_prefs.allow_always_save && (! doc->changed || doc->readonly))
1823 return FALSE;
1825 if (G_UNLIKELY(doc->file_name == NULL))
1827 ui_set_statusbar(TRUE, _("Error saving file."));
1828 utils_beep();
1829 return FALSE;
1832 /* replaces tabs by spaces but only if the current file is not a Makefile */
1833 if (file_prefs.replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1834 editor_replace_tabs(doc->editor);
1835 /* strip trailing spaces */
1836 if (file_prefs.strip_trailing_spaces)
1837 editor_strip_trailing_spaces(doc->editor);
1838 /* ensure the file has a newline at the end */
1839 if (file_prefs.final_new_line)
1840 editor_ensure_final_newline(doc->editor);
1841 /* ensure newlines are consistent */
1842 if (file_prefs.ensure_convert_new_lines)
1843 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1845 /* notify plugins which may wish to modify the document before it's saved */
1846 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1848 len = sci_get_length(doc->editor->sci) + 1;
1849 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1850 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1851 * encoding, it will be converted to doc->encoding below and this conversion
1852 * also changes the BOM */
1853 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1854 data[0] = (gchar) 0xef;
1855 data[1] = (gchar) 0xbb;
1856 data[2] = (gchar) 0xbf;
1857 sci_get_text(doc->editor->sci, len, data + 3);
1858 len += 3;
1860 else
1862 data = (gchar*) g_malloc(len);
1863 sci_get_text(doc->editor->sci, len, data);
1866 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1867 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1868 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1870 if (! save_convert_to_encoding(doc, &data, &len))
1872 g_free(data);
1873 return FALSE;
1876 else
1878 len = strlen(data);
1881 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1883 /* ignore file changed notification when the file is written */
1884 doc->priv->file_disk_status = FILE_IGNORE;
1886 /* actually write the content of data to the file on disk */
1887 errmsg = save_doc(doc, locale_filename, data, len);
1888 g_free(data);
1890 if (errmsg != NULL)
1892 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1893 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1894 doc->priv->file_disk_status = FILE_OK;
1895 utils_beep();
1896 g_free(locale_filename);
1897 g_free(errmsg);
1898 return FALSE;
1901 /* store the opened encoding for undo/redo */
1902 store_saved_encoding(doc);
1904 /* ignore the following things if we are quitting */
1905 if (! main_status.quitting)
1907 sci_set_savepoint(doc->editor->sci);
1909 if (file_prefs.disk_check_timeout > 0)
1910 document_update_timestamp(doc, locale_filename);
1912 /* update filetype-related things */
1913 document_set_filetype(doc, doc->file_type);
1915 document_update_tab_label(doc);
1917 msgwin_status_add(_("File %s saved."), doc->file_name);
1918 ui_update_statusbar(doc, -1);
1919 #ifdef HAVE_VTE
1920 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1921 #endif
1923 g_free(locale_filename);
1925 g_signal_emit_by_name(geany_object, "document-save", doc);
1927 return TRUE;
1931 /* special search function, used from the find entry in the toolbar
1932 * return TRUE if text was found otherwise FALSE
1933 * return also TRUE if text is empty */
1934 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc)
1936 gint start_pos, search_pos;
1937 struct Sci_TextToFind ttf;
1939 g_return_val_if_fail(text != NULL, FALSE);
1940 g_return_val_if_fail(doc != NULL, FALSE);
1941 if (! *text)
1942 return TRUE;
1944 start_pos = (inc) ? sci_get_selection_start(doc->editor->sci) :
1945 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1947 /* search cursor to end */
1948 ttf.chrg.cpMin = start_pos;
1949 ttf.chrg.cpMax = sci_get_length(doc->editor->sci);
1950 ttf.lpstrText = (gchar *)text;
1951 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1953 /* if no match, search start to cursor */
1954 if (search_pos == -1)
1956 ttf.chrg.cpMin = 0;
1957 ttf.chrg.cpMax = start_pos + strlen(text);
1958 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1961 if (search_pos != -1)
1963 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1965 /* unfold maybe folded results */
1966 sci_ensure_line_is_visible(doc->editor->sci, line);
1968 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1969 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1971 if (! editor_line_in_view(doc->editor, line))
1972 { /* we need to force scrolling in case the cursor is outside of the current visible area
1973 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1974 * while searching */
1975 editor_scroll_to_line(doc->editor, -1, 0.3F);
1977 else
1978 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1979 return TRUE;
1981 else
1983 if (! inc)
1985 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1987 utils_beep();
1988 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1989 return FALSE;
1994 /* General search function, used from the find dialog.
1995 * Returns -1 on failure or the start position of the matching text.
1996 * Will skip past any selection, ignoring it. */
1997 gint document_find_text(GeanyDocument *doc, const gchar *text, gint flags, gboolean search_backwards,
1998 gboolean scroll, GtkWidget *parent)
2000 gint selection_end, selection_start, search_pos;
2002 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2003 if (! *text)
2004 return -1;
2006 /* Sci doesn't support searching backwards with a regex */
2007 if (flags & SCFIND_REGEXP)
2008 search_backwards = FALSE;
2010 selection_start = sci_get_selection_start(doc->editor->sci);
2011 selection_end = sci_get_selection_end(doc->editor->sci);
2012 if ((selection_end - selection_start) > 0)
2013 { /* there's a selection so go to the end */
2014 if (search_backwards)
2015 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2016 else
2017 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2020 sci_set_search_anchor(doc->editor->sci);
2021 if (search_backwards)
2022 search_pos = sci_search_prev(doc->editor->sci, flags, text);
2023 else
2024 search_pos = search_find_next(doc->editor->sci, text, flags);
2026 if (search_pos != -1)
2028 /* unfold maybe folded results */
2029 sci_ensure_line_is_visible(doc->editor->sci,
2030 sci_get_line_from_position(doc->editor->sci, search_pos));
2031 if (scroll)
2032 doc->editor->scroll_percent = 0.3F;
2034 else
2036 gint sci_len = sci_get_length(doc->editor->sci);
2038 /* if we just searched the whole text, give up searching. */
2039 if ((selection_end == 0 && ! search_backwards) ||
2040 (selection_end == sci_len && search_backwards))
2042 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2043 utils_beep();
2044 return -1;
2047 /* we searched only part of the document, so ask whether to wraparound. */
2048 if (search_prefs.suppress_dialogs ||
2049 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2050 _("Wrap search and find again?"), _("\"%s\" was not found."), text))
2052 gint ret;
2054 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2055 ret = document_find_text(doc, text, flags, search_backwards, scroll, parent);
2056 if (ret == -1)
2057 { /* return to original cursor position if not found */
2058 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2060 return ret;
2063 return search_pos;
2067 /* Replaces the selection if it matches, otherwise just finds the next match.
2068 * Returns: start of replaced text, or -1 if no replacement was made */
2069 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2070 gint flags, gboolean search_backwards)
2072 gint selection_end, selection_start, search_pos;
2074 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2076 if (! *find_text)
2077 return -1;
2079 /* Sci doesn't support searching backwards with a regex */
2080 if (flags & SCFIND_REGEXP)
2081 search_backwards = FALSE;
2083 selection_start = sci_get_selection_start(doc->editor->sci);
2084 selection_end = sci_get_selection_end(doc->editor->sci);
2085 if (selection_end == selection_start)
2087 /* no selection so just find the next match */
2088 document_find_text(doc, find_text, flags, search_backwards, TRUE, NULL);
2089 return -1;
2091 /* there's a selection so go to the start before finding to search through it
2092 * this ensures there is a match */
2093 if (search_backwards)
2094 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2095 else
2096 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2098 search_pos = document_find_text(doc, find_text, flags, search_backwards, TRUE, NULL);
2099 /* return if the original selected text did not match (at the start of the selection) */
2100 if (search_pos != selection_start)
2101 return -1;
2103 if (search_pos != -1)
2105 gint replace_len;
2106 /* search next/prev will select matching text, which we use to set the replace target */
2107 sci_target_from_selection(doc->editor->sci);
2108 replace_len = search_replace_target(doc->editor->sci, replace_text, flags & SCFIND_REGEXP);
2109 /* select the replacement - find text will skip past the selected text */
2110 sci_set_selection_start(doc->editor->sci, search_pos);
2111 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2113 else
2115 /* no match in the selection */
2116 utils_beep();
2118 return search_pos;
2122 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *find_text,
2123 const gchar *replace_text, gboolean escaped_chars)
2125 gchar *escaped_find_text, *escaped_replace_text, *filename;
2127 if (count == 0)
2129 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), find_text);
2130 return;
2133 filename = g_path_get_basename(DOC_FILENAME(doc));
2135 if (escaped_chars)
2136 { /* escape special characters for showing */
2137 escaped_find_text = g_strescape(find_text, NULL);
2138 escaped_replace_text = g_strescape(replace_text, NULL);
2139 ui_set_statusbar(TRUE, ngettext(
2140 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2141 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2142 count), filename, count, escaped_find_text, escaped_replace_text);
2143 g_free(escaped_find_text);
2144 g_free(escaped_replace_text);
2146 else
2148 ui_set_statusbar(TRUE, ngettext(
2149 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2150 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2151 count), filename, count, find_text, replace_text);
2153 g_free(filename);
2157 /* Replace all text matches in a certain range within document.
2158 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2159 * or -1 if no text was found.
2160 * scroll_to_match is whether to scroll the last replacement in view (which also
2161 * clears the selection).
2162 * Returns: the number of replacements made. */
2163 static guint
2164 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2165 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2167 gint count = 0;
2168 struct Sci_TextToFind ttf;
2169 ScintillaObject *sci;
2171 if (new_range_end != NULL)
2172 *new_range_end = -1;
2174 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2176 if (! *find_text || doc->readonly)
2177 return 0;
2179 sci = doc->editor->sci;
2181 ttf.chrg.cpMin = start;
2182 ttf.chrg.cpMax = end;
2183 ttf.lpstrText = (gchar*)find_text;
2185 sci_start_undo_action(sci);
2186 count = search_replace_range(sci, &ttf, flags, replace_text);
2187 sci_end_undo_action(sci);
2189 if (count > 0)
2190 { /* scroll last match in view, will destroy the existing selection */
2191 if (scroll_to_match)
2192 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2194 if (new_range_end != NULL)
2195 *new_range_end = ttf.chrg.cpMax;
2197 return count;
2201 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2202 gint flags, gboolean escaped_chars)
2204 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2205 gint max_column = 0, count = 0;
2206 gboolean replaced = FALSE;
2208 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2210 if (! *find_text)
2211 return;
2213 selection_start = sci_get_selection_start(doc->editor->sci);
2214 selection_end = sci_get_selection_end(doc->editor->sci);
2215 /* do we have a selection? */
2216 if ((selection_end - selection_start) == 0)
2218 utils_beep();
2219 return;
2222 selection_mode = sci_get_selection_mode(doc->editor->sci);
2223 selected_lines = sci_get_lines_selected(doc->editor->sci);
2224 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2225 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2227 gint first_line, line;
2229 sci_start_undo_action(doc->editor->sci);
2231 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2232 /* Find the last line with chars selected (not EOL char) */
2233 last_line = sci_get_line_from_position(doc->editor->sci,
2234 selection_end - editor_get_eol_char_len(doc->editor));
2235 last_line = MAX(first_line, last_line);
2236 for (line = first_line; line < (first_line + selected_lines); line++)
2238 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2239 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2241 /* skip line if there is no selection */
2242 if (line_start != INVALID_POSITION)
2244 /* don't let document_replace_range() scroll to match to keep our selection */
2245 gint new_sel_end;
2247 count += document_replace_range(doc, find_text, replace_text, flags,
2248 line_start, line_end, FALSE, &new_sel_end);
2249 if (new_sel_end != -1)
2251 replaced = TRUE;
2252 /* this gets the greatest column within the selection after replacing */
2253 max_column = MAX(max_column,
2254 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2258 sci_end_undo_action(doc->editor->sci);
2260 else /* handle normal line selection */
2262 count += document_replace_range(doc, find_text, replace_text, flags,
2263 selection_start, selection_end, TRUE, &selection_end);
2264 if (selection_end != -1)
2265 replaced = TRUE;
2268 if (replaced)
2269 { /* update the selection for the new endpoint */
2271 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2273 /* now we can scroll to the selection and destroy it because we rebuild it later */
2274 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2276 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2277 * the highest column on the last line. The wrapped selection is completely different
2278 * from the original one, so skip the selection at all */
2279 /* TODO is there a better way to handle the wrapped selection? */
2280 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2281 { /* for keeping and adjusting the selection in multi line rectangle selection we
2282 * need the last line of the original selection and the greatest column number after
2283 * replacing and set the selection end to the last line at the greatest column */
2284 sci_set_selection_start(doc->editor->sci, selection_start);
2285 sci_set_selection_end(doc->editor->sci,
2286 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2287 sci_set_selection_mode(doc->editor->sci, selection_mode);
2290 else
2292 sci_set_selection_start(doc->editor->sci, selection_start);
2293 sci_set_selection_end(doc->editor->sci, selection_end);
2296 else /* no replacements */
2297 utils_beep();
2299 show_replace_summary(doc, count, find_text, replace_text, escaped_chars);
2303 /* returns number of replacements made. */
2304 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2305 gint flags, gboolean escaped_chars)
2307 gint len, count;
2308 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2310 if (! *find_text)
2311 return FALSE;
2313 len = sci_get_length(doc->editor->sci);
2314 count = document_replace_range(
2315 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2317 show_replace_summary(doc, count, find_text, replace_text, escaped_chars);
2318 return count;
2322 static gboolean update_tags_from_buffer(GeanyDocument *doc)
2324 gboolean result;
2325 #if 1
2326 /* old code */
2327 result = tm_source_file_update(doc->tm_file, TRUE, FALSE, TRUE);
2328 #else
2329 gsize len = sci_get_length(doc->editor->sci) + 1;
2330 gchar *text = g_malloc(len);
2332 /* we copy the whole text into memory instead using a direct char pointer from
2333 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2334 sci_get_text(doc->editor->sci, len, text);
2335 result = tm_source_file_buffer_update(doc->tm_file, (guchar*) text, len, TRUE);
2336 g_free(text);
2337 #endif
2338 return result;
2342 void document_update_tag_list(GeanyDocument *doc, gboolean update)
2344 /* We must call sidebar_update_tag_list() before returning,
2345 * to ensure that the symbol list is always updated properly (e.g.
2346 * when creating a new document with a partial filename set. */
2347 gboolean success = FALSE;
2349 /* if the filetype doesn't have a tag parser or it is a new file */
2350 if (doc == NULL || doc->file_type == NULL || app->tm_workspace == NULL ||
2351 ! filetype_has_tags(doc->file_type) || ! doc->file_name)
2353 /* set the default (empty) tag list */
2354 sidebar_update_tag_list(doc, FALSE);
2355 return;
2358 if (doc->tm_file == NULL)
2360 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2361 const gchar *name;
2363 /* lookup the name rather than using filetype name to support custom filetypes */
2364 name = tm_source_file_get_lang_name(doc->file_type->lang);
2365 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2366 g_free(locale_filename);
2368 if (doc->tm_file)
2370 if (!tm_workspace_add_object(doc->tm_file))
2372 tm_work_object_free(doc->tm_file);
2373 doc->tm_file = NULL;
2375 else
2377 if (update)
2378 update_tags_from_buffer(doc);
2379 success = TRUE;
2383 else
2385 success = update_tags_from_buffer(doc);
2386 if (G_UNLIKELY(! success))
2387 geany_debug("tag list updating failed");
2389 sidebar_update_tag_list(doc, success);
2393 /* Caches the list of project typenames, as a space separated GString.
2394 * Returns: TRUE if typenames have changed.
2395 * (*types) is set to the list of typenames, or NULL if there are none. */
2396 static gboolean get_project_typenames(const GString **types, gint lang)
2398 static GString *last_typenames = NULL;
2399 GString *s = NULL;
2401 if (app->tm_workspace)
2403 GPtrArray *tags_array = app->tm_workspace->work_object.tags_array;
2405 if (tags_array)
2407 s = symbols_find_tags_as_string(tags_array, TM_GLOBAL_TYPE_MASK, lang);
2411 if (s && last_typenames && g_string_equal(s, last_typenames))
2413 g_string_free(s, TRUE);
2414 *types = last_typenames;
2415 return FALSE; /* project typenames haven't changed */
2417 /* cache typename list for next time */
2418 if (last_typenames)
2419 g_string_free(last_typenames, TRUE);
2420 last_typenames = s;
2422 *types = s;
2423 if (s == NULL)
2424 return FALSE;
2425 return TRUE;
2429 /* If sci is NULL, update project typenames for all documents that support typenames,
2430 * if typenames have changed.
2431 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2432 * if necessary, and typename keywords are set for sci.
2433 * Returns: TRUE if any scintilla type keywords were updated. */
2434 static gboolean update_type_keywords(GeanyDocument *doc, gint lang)
2436 gboolean ret = FALSE;
2437 guint n;
2438 const GString *s;
2439 ScintillaObject *sci;
2441 g_return_val_if_fail(doc != NULL, FALSE);
2442 sci = doc->editor->sci;
2444 switch (doc->file_type->id)
2445 { /* continue working with the following languages, skip on all others */
2446 case GEANY_FILETYPES_C:
2447 case GEANY_FILETYPES_CPP:
2448 case GEANY_FILETYPES_CS:
2449 case GEANY_FILETYPES_D:
2450 case GEANY_FILETYPES_JAVA:
2451 case GEANY_FILETYPES_VALA:
2452 break;
2453 default:
2454 return FALSE;
2457 sci = doc->editor->sci;
2458 if (sci != NULL && editor_lexer_get_type_keyword_idx(sci_get_lexer(sci)) == -1)
2459 return FALSE;
2461 if (! get_project_typenames(&s, lang))
2462 { /* typenames have not changed */
2463 if (s != NULL && sci != NULL)
2465 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(sci));
2467 sci_set_keywords(sci, keyword_idx, s->str);
2468 queue_colourise(doc);
2470 return FALSE;
2472 g_return_val_if_fail(s != NULL, FALSE);
2474 for (n = 0; n < documents_array->len; n++)
2476 if (documents[n]->is_valid)
2478 ScintillaObject *wid = documents[n]->editor->sci;
2479 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(wid));
2481 if (keyword_idx > 0)
2483 sci_set_keywords(wid, keyword_idx, s->str);
2484 queue_colourise(documents[n]);
2485 ret = TRUE;
2489 return ret;
2493 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2494 gboolean filetype_changed)
2496 g_return_if_fail(doc);
2497 if (type == NULL)
2498 type = filetypes[GEANY_FILETYPES_NONE];
2500 if (filetype_changed)
2502 doc->file_type = type;
2504 /* delete tm file object to force creation of a new one */
2505 if (doc->tm_file != NULL)
2507 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2508 doc->tm_file = NULL;
2510 /* load tags files before highlighting (some lexers highlight global typenames) */
2511 if (type->id != GEANY_FILETYPES_NONE)
2512 symbols_global_tags_loaded(type->id);
2514 highlighting_set_styles(doc->editor->sci, type);
2515 editor_set_indentation_guides(doc->editor);
2516 build_menu_update(doc);
2517 queue_colourise(doc);
2518 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2521 document_update_tag_list(doc, TRUE);
2523 /* Update session typename keywords. */
2524 update_type_keywords(doc, type->lang);
2528 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2529 * @param doc The document to use.
2530 * @param type The filetype. */
2531 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2533 gboolean ft_changed;
2534 GeanyFiletype *old_ft;
2536 g_return_if_fail(doc);
2537 if (type == NULL)
2538 type = filetypes[GEANY_FILETYPES_NONE];
2540 old_ft = doc->file_type;
2541 geany_debug("%s : %s (%s)",
2542 (doc->file_name != NULL) ? doc->file_name : "unknown",
2543 type->name,
2544 (doc->encoding != NULL) ? doc->encoding : "unknown");
2546 ft_changed = (doc->file_type != type); /* filetype has changed */
2547 document_load_config(doc, type, ft_changed);
2549 if (ft_changed)
2551 sidebar_openfiles_update(doc); /* to update the icon */
2552 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2557 void document_reload_config(GeanyDocument *doc)
2559 document_load_config(doc, doc->file_type, TRUE);
2564 * Sets the encoding of a document.
2565 * This function only set the encoding of the %document, it does not any conversions. The new
2566 * encoding is used when e.g. saving the file.
2568 * @param doc The document to use.
2569 * @param new_encoding The encoding to be set for the document.
2571 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2573 if (doc == NULL || new_encoding == NULL ||
2574 utils_str_equal(new_encoding, doc->encoding))
2575 return;
2577 g_free(doc->encoding);
2578 doc->encoding = g_strdup(new_encoding);
2580 ui_update_statusbar(doc, -1);
2581 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2582 encodings_is_unicode_charset(doc->encoding));
2586 /* own Undo / Redo implementation to be able to undo / redo changes
2587 * to the encoding or the Unicode BOM (which are Scintilla independet).
2588 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2590 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2591 void document_undo_clear(GeanyDocument *doc)
2593 undo_action *a;
2595 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2597 a = g_trash_stack_pop(&doc->priv->undo_actions);
2598 if (G_LIKELY(a != NULL))
2600 switch (a->type)
2602 case UNDO_ENCODING: g_free(a->data); break;
2603 default: break;
2605 g_free(a);
2608 doc->priv->undo_actions = NULL;
2610 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2612 a = g_trash_stack_pop(&doc->priv->redo_actions);
2613 if (G_LIKELY(a != NULL))
2615 switch (a->type)
2617 case UNDO_ENCODING: g_free(a->data); break;
2618 default: break;
2620 g_free(a);
2623 doc->priv->redo_actions = NULL;
2625 if (! main_status.quitting && doc->editor != NULL)
2626 document_set_text_changed(doc, FALSE);
2630 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2632 undo_action *action;
2634 g_return_if_fail(doc != NULL);
2636 action = g_new0(undo_action, 1);
2637 action->type = type;
2638 action->data = data;
2640 g_trash_stack_push(&doc->priv->undo_actions, action);
2642 document_set_text_changed(doc, TRUE);
2643 ui_update_popup_reundo_items(doc);
2647 gboolean document_can_undo(GeanyDocument *doc)
2649 g_return_val_if_fail(doc != NULL, FALSE);
2651 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2652 return TRUE;
2653 else
2654 return FALSE;
2658 static void update_changed_state(GeanyDocument *doc)
2660 doc->changed =
2661 (sci_is_modified(doc->editor->sci) ||
2662 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2663 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2664 document_set_text_changed(doc, doc->changed);
2668 void document_undo(GeanyDocument *doc)
2670 undo_action *action;
2672 g_return_if_fail(doc != NULL);
2674 action = g_trash_stack_pop(&doc->priv->undo_actions);
2676 if (G_UNLIKELY(action == NULL))
2678 /* fallback, should not be necessary */
2679 geany_debug("%s: fallback used", G_STRFUNC);
2680 sci_undo(doc->editor->sci);
2682 else
2684 switch (action->type)
2686 case UNDO_SCINTILLA:
2688 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2690 sci_undo(doc->editor->sci);
2691 break;
2693 case UNDO_BOM:
2695 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2697 doc->has_bom = GPOINTER_TO_INT(action->data);
2698 ui_update_statusbar(doc, -1);
2699 ui_document_show_hide(doc);
2700 break;
2702 case UNDO_ENCODING:
2704 /* use the "old" encoding */
2705 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2707 document_set_encoding(doc, (const gchar*)action->data);
2709 ignore_callback = TRUE;
2710 encodings_select_radio_item((const gchar*)action->data);
2711 ignore_callback = FALSE;
2713 g_free(action->data);
2714 break;
2716 default: break;
2719 g_free(action); /* free the action which was taken from the stack */
2721 update_changed_state(doc);
2722 ui_update_popup_reundo_items(doc);
2726 gboolean document_can_redo(GeanyDocument *doc)
2728 g_return_val_if_fail(doc != NULL, FALSE);
2730 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2731 return TRUE;
2732 else
2733 return FALSE;
2737 void document_redo(GeanyDocument *doc)
2739 undo_action *action;
2741 g_return_if_fail(doc != NULL);
2743 action = g_trash_stack_pop(&doc->priv->redo_actions);
2745 if (G_UNLIKELY(action == NULL))
2747 /* fallback, should not be necessary */
2748 geany_debug("%s: fallback used", G_STRFUNC);
2749 sci_redo(doc->editor->sci);
2751 else
2753 switch (action->type)
2755 case UNDO_SCINTILLA:
2757 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2759 sci_redo(doc->editor->sci);
2760 break;
2762 case UNDO_BOM:
2764 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2766 doc->has_bom = GPOINTER_TO_INT(action->data);
2767 ui_update_statusbar(doc, -1);
2768 ui_document_show_hide(doc);
2769 break;
2771 case UNDO_ENCODING:
2773 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2775 document_set_encoding(doc, (const gchar*)action->data);
2777 ignore_callback = TRUE;
2778 encodings_select_radio_item((const gchar*)action->data);
2779 ignore_callback = FALSE;
2781 g_free(action->data);
2782 break;
2784 default: break;
2787 g_free(action); /* free the action which was taken from the stack */
2789 update_changed_state(doc);
2790 ui_update_popup_reundo_items(doc);
2794 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2796 undo_action *action;
2798 g_return_if_fail(doc != NULL);
2800 action = g_new0(undo_action, 1);
2801 action->type = type;
2802 action->data = data;
2804 g_trash_stack_push(&doc->priv->redo_actions, action);
2806 document_set_text_changed(doc, TRUE);
2807 ui_update_popup_reundo_items(doc);
2812 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2813 * Returned colors are red if the document has changes, green if the document is read-only
2814 * or simply @c NULL if the document is unmodified but writable.
2816 * @param doc The document to use.
2818 * @return The color for the document or @c NULL if the default color should be used. The color
2819 * object is owned by Geany and should not be modified or freed.
2821 * @since 0.16
2823 const GdkColor *document_get_status_color(GeanyDocument *doc)
2825 static GdkColor red = {0, 0xFFFF, 0, 0};
2826 static GdkColor green = {0, 0, 0x7FFF, 0};
2827 #if USE_GIO_FILEMON
2828 static GdkColor orange = {0, 0xFFFF, 0x7FFF, 0};
2829 #endif
2830 GdkColor *color = NULL;
2832 g_return_val_if_fail(doc != NULL, NULL);
2834 if (doc->changed)
2835 color = &red;
2836 #if USE_GIO_FILEMON
2837 else if (doc->priv->file_disk_status == FILE_CHANGED)
2838 color = &orange;
2839 #endif
2840 else if (doc->readonly)
2841 color = &green;
2843 return color; /* return pointer to static GdkColor. */
2847 /** Accessor function for @ref GeanyData::documents_array items.
2848 * @warning Always check the returned document is valid (@c doc->is_valid).
2849 * @param idx @c documents_array index.
2850 * @return The document, or @c NULL if @a idx is out of range.
2852 * @since 0.16
2854 GeanyDocument *document_index(gint idx)
2856 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2860 /* create a new file and copy file content and properties */
2861 GeanyDocument *document_clone(GeanyDocument *old_doc, const gchar *utf8_filename)
2863 gint len;
2864 gchar *text;
2865 GeanyDocument *doc;
2867 g_return_val_if_fail(old_doc != NULL, NULL);
2869 len = sci_get_length(old_doc->editor->sci) + 1;
2870 text = (gchar*) g_malloc(len);
2871 sci_get_text(old_doc->editor->sci, len, text);
2872 /* use old file type (or maybe NULL for auto detect would be better?) */
2873 doc = document_new_file(utf8_filename, old_doc->file_type, text);
2874 g_free(text);
2876 /* copy file properties */
2877 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2878 doc->readonly = old_doc->readonly;
2879 doc->has_bom = old_doc->has_bom;
2880 document_set_encoding(doc, old_doc->encoding);
2881 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2882 sci_set_readonly(doc->editor->sci, doc->readonly);
2884 ui_document_show_hide(doc);
2885 return doc;
2889 /* @note If successful, this should always be followed up with a call to
2890 * document_close_all().
2891 * @return TRUE if all files were saved or had their changes discarded. */
2892 gboolean document_account_for_unsaved(void)
2894 guint i, p, page_count, len = documents_array->len;
2895 GeanyDocument *doc;
2897 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2898 for (p = 0; p < page_count; p++)
2900 doc = document_get_from_page(p);
2901 if (DOC_VALID(doc) && doc->changed)
2903 if (! dialogs_show_unsaved_file(doc))
2904 return FALSE;
2907 /* all documents should now be accounted for, so ignore any changes */
2908 for (i = 0; i < len; i++)
2910 doc = documents[i];
2911 if (doc->is_valid && doc->changed)
2913 doc->changed = FALSE;
2916 return TRUE;
2920 static void force_close_all(void)
2922 guint i, len = documents_array->len;
2924 /* check all documents have been accounted for */
2925 for (i = 0; i < len; i++)
2927 if (documents[i]->is_valid)
2929 g_return_if_fail(!documents[i]->changed);
2932 main_status.closing_all = TRUE;
2934 foreach_document(i)
2936 document_close(documents[i]);
2939 main_status.closing_all = FALSE;
2943 gboolean document_close_all(void)
2945 if (! document_account_for_unsaved())
2946 return FALSE;
2948 force_close_all();
2950 return TRUE;
2954 static void monitor_reload_file(GeanyDocument *doc)
2956 gchar *base_name = g_path_get_basename(doc->file_name);
2957 gint ret;
2959 ret = dialogs_show_prompt(NULL,
2960 GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
2961 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2962 _("_Reload"), GTK_RESPONSE_ACCEPT,
2963 _("Do you want to reload it?"),
2964 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2965 base_name);
2966 g_free(base_name);
2968 if (ret == GTK_RESPONSE_ACCEPT)
2969 document_reload_file(doc, doc->encoding);
2970 else if (ret == GTK_RESPONSE_CLOSE)
2971 document_close(doc);
2975 static gboolean monitor_resave_missing_file(GeanyDocument *doc)
2977 gboolean want_reload = FALSE;
2978 gboolean file_saved = FALSE;
2979 gint ret;
2981 ret = dialogs_show_prompt(NULL,
2982 _("Close _without saving"), GTK_RESPONSE_CLOSE,
2983 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2984 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
2985 _("Try to resave the file?"),
2986 _("File \"%s\" was not found on disk!"),
2987 doc->file_name);
2988 if (ret == GTK_RESPONSE_ACCEPT)
2990 file_saved = dialogs_show_save_as();
2991 want_reload = TRUE;
2993 else if (ret == GTK_RESPONSE_CLOSE)
2995 document_close(doc);
2997 if (ret != GTK_RESPONSE_CLOSE && ! file_saved)
2999 /* file is missing - set unsaved state */
3000 document_set_text_changed(doc, TRUE);
3001 /* don't prompt more than once */
3002 setptr(doc->real_path, NULL);
3005 return want_reload;
3009 /* Set force to force a disk check, otherwise it is ignored if there was a check
3010 * in the last file_prefs.disk_check_timeout seconds.
3011 * @return @c TRUE if the file has changed. */
3012 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3014 gboolean ret = FALSE;
3015 gboolean use_gio_filemon;
3016 time_t cur_time = 0;
3017 struct stat st;
3018 gchar *locale_filename;
3019 FileDiskStatus old_status;
3021 g_return_val_if_fail(doc != NULL, FALSE);
3023 /* ignore remote files and documents that have never been saved to disk */
3024 if (file_prefs.disk_check_timeout == 0 || doc->real_path == NULL || doc->priv->is_remote)
3025 return FALSE;
3027 use_gio_filemon = (doc->priv->monitor != NULL);
3029 if (use_gio_filemon)
3031 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3032 return FALSE;
3034 else
3036 cur_time = time(NULL);
3037 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3038 return FALSE;
3040 doc->priv->last_check = cur_time;
3043 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3044 if (g_stat(locale_filename, &st) != 0)
3046 monitor_resave_missing_file(doc);
3047 /* doc may be closed now */
3048 ret = TRUE;
3050 else if (! use_gio_filemon && /* ignore these checks when using GIO */
3051 (G_UNLIKELY(doc->priv->mtime > cur_time) || G_UNLIKELY(st.st_mtime > cur_time)))
3053 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3055 else if (doc->priv->mtime < st.st_mtime)
3057 doc->priv->mtime = st.st_mtime;
3058 monitor_reload_file(doc);
3059 /* doc may be closed now */
3060 ret = TRUE;
3062 g_free(locale_filename);
3064 if (DOC_VALID(doc))
3065 { /* doc can get invalid when a document was closed */
3066 old_status = doc->priv->file_disk_status;
3067 doc->priv->file_disk_status = FILE_OK;
3068 if (old_status != doc->priv->file_disk_status)
3069 ui_update_tab_status(doc);
3071 return ret;