Fix unused warning when building without VTE support
[geany-mirror.git] / src / document.c
bloba5801f2ccb2c6e87a9e14aee08f2029bbefd79ee
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 #include "geany.h"
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #include <time.h>
34 #include <unistd.h>
35 #include <string.h>
36 #include <errno.h>
38 #ifdef HAVE_SYS_TYPES_H
39 # include <sys/types.h>
40 #endif
42 #include <stdlib.h>
44 /* gstdio.h also includes sys/stat.h */
45 #include <glib/gstdio.h>
47 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
48 /*#define USE_GIO_FILEMON 1*/
49 #include <gio/gio.h>
51 #include "document.h"
52 #include "documentprivate.h"
53 #include "filetypes.h"
54 #include "support.h"
55 #include "sciwrappers.h"
56 #include "editor.h"
57 #include "dialogs.h"
58 #include "msgwindow.h"
59 #include "templates.h"
60 #include "sidebar.h"
61 #include "ui_utils.h"
62 #include "utils.h"
63 #include "encodings.h"
64 #include "notebook.h"
65 #include "main.h"
66 #include "vte.h"
67 #include "build.h"
68 #include "symbols.h"
69 #include "highlighting.h"
70 #include "navqueue.h"
71 #include "win32.h"
72 #include "search.h"
73 #include "filetypesprivate.h"
74 #include "project.h"
76 #include "SciLexer.h"
79 GeanyFilePrefs file_prefs;
81 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
82 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
83 * to a document over time, but it might no longer represent a notebook tab. To check this,
84 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
85 * file by then.
87 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
88 * although usually you would just use the foreach_document() macro.
90 * Never assume that the order of document pointers is the same as the order of notebook tabs.
91 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
92 GPtrArray *documents_array = NULL;
95 /* an undo action, also used for redo actions */
96 typedef struct
98 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
99 guint type; /* to identify the action */
100 gpointer *data; /* the old value (before the change), in case of a redo action
101 * it contains the new value */
102 } undo_action;
105 static void document_undo_clear(GeanyDocument *doc);
106 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
107 static gboolean remove_page(guint page_num);
111 * Finds a document whose @c real_path field matches the given filename.
113 * @param realname The filename to search, which should be identical to the
114 * string returned by @c tm_get_real_path().
116 * @return The matching document, or @c NULL.
117 * @note This is only really useful when passing a @c TMWorkObject::file_name.
118 * @see GeanyDocument::real_path.
119 * @see document_find_by_filename().
121 * @since 0.15
123 GeanyDocument* document_find_by_real_path(const gchar *realname)
125 guint i;
127 if (! realname)
128 return NULL; /* file doesn't exist on disk */
130 for (i = 0; i < documents_array->len; i++)
132 GeanyDocument *doc = documents[i];
134 if (! doc->is_valid || ! doc->real_path)
135 continue;
137 if (utils_filenamecmp(realname, doc->real_path) == 0)
139 return doc;
142 return NULL;
146 /* dereference symlinks, /../ junk in path and return locale encoding */
147 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
149 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
150 gchar *realname = tm_get_real_path(locale_name);
152 g_free(locale_name);
153 return realname;
158 * Finds a document with the given filename.
159 * This matches either an exact GeanyDocument::file_name string, or variant
160 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
161 * match @c "/name").
163 * @param utf8_filename The filename to search (in UTF-8 encoding).
165 * @return The matching document, or @c NULL.
166 * @see document_find_by_real_path().
168 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
170 guint i;
171 GeanyDocument *doc;
172 gchar *realname;
174 g_return_val_if_fail(utf8_filename != NULL, NULL);
176 /* First search GeanyDocument::file_name, so we can find documents with a
177 * filename set but not saved on disk, like vcdiff produces */
178 for (i = 0; i < documents_array->len; i++)
180 doc = documents[i];
182 if (! doc->is_valid || doc->file_name == NULL)
183 continue;
185 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
187 return doc;
190 /* Now try matching based on the realpath(), which is unique per file on disk */
191 realname = get_real_path_from_utf8(utf8_filename);
192 doc = document_find_by_real_path(realname);
193 g_free(realname);
194 return doc;
198 /* returns the document which has sci, or NULL. */
199 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
201 guint i;
203 g_return_val_if_fail(sci != NULL, NULL);
205 for (i = 0; i < documents_array->len; i++)
207 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
208 return documents[i];
210 return NULL;
214 /** Gets the notebook page index for a document.
215 * @param doc The document.
216 * @return The index.
217 * @since 0.19 */
218 gint document_get_notebook_page(GeanyDocument *doc)
220 g_return_val_if_fail(doc != NULL, -1);
222 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
223 GTK_WIDGET(doc->editor->sci));
228 * Finds the document for the given notebook page @a page_num.
230 * @param page_num The notebook page number to search.
232 * @return The corresponding document for the given notebook page, or @c NULL.
234 GeanyDocument *document_get_from_page(guint page_num)
236 ScintillaObject *sci;
238 if (page_num >= documents_array->len)
239 return NULL;
241 sci = (ScintillaObject*)gtk_notebook_get_nth_page(
242 GTK_NOTEBOOK(main_widgets.notebook), page_num);
244 return document_find_by_sci(sci);
249 * Finds the current document.
251 * @return A pointer to the current document or @c NULL if there are no opened documents.
253 GeanyDocument *document_get_current(void)
255 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
257 if (cur_page == -1)
258 return NULL;
259 else
261 ScintillaObject *sci = (ScintillaObject*)
262 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
264 return document_find_by_sci(sci);
269 void document_init_doclist(void)
271 documents_array = g_ptr_array_new();
275 void document_finalize(void)
277 guint i;
279 for (i = 0; i < documents_array->len; i++)
280 g_free(documents[i]);
281 g_ptr_array_free(documents_array, TRUE);
286 * Returns the last part of the filename of the given GeanyDocument. The result is also
287 * truncated to a maximum of @a length characters in case the filename is very long.
289 * @param doc The document to use.
290 * @param length The length of the resulting string or -1 to use a default value.
292 * @return The ellipsized last part of the filename of @a doc, should be freed when no
293 * longer needed.
295 * @since 0.17
297 /* TODO make more use of this */
298 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
300 gchar *base_name, *short_name;
302 g_return_val_if_fail(doc != NULL, NULL);
304 if (length < 0)
305 length = 30;
307 base_name = g_path_get_basename(DOC_FILENAME(doc));
308 short_name = utils_str_middle_truncate(base_name, (guint)length);
310 g_free(base_name);
312 return short_name;
316 void document_update_tab_label(GeanyDocument *doc)
318 gchar *short_name;
319 GtkWidget *parent;
321 g_return_if_fail(doc != NULL);
323 short_name = document_get_basename_for_display(doc, -1);
325 /* we need to use the event box for the tooltip, labels don't get the necessary events */
326 parent = gtk_widget_get_parent(doc->priv->tab_label);
327 parent = gtk_widget_get_parent(parent);
329 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
331 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
333 g_free(short_name);
338 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
339 * according to the document's save state.
340 * This is called by Geany mostly when opening or saving files.
342 * @param doc The document to use.
343 * @param changed Whether the document state should indicate changes have been made.
345 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
347 g_return_if_fail(doc != NULL);
349 doc->changed = changed;
351 if (! main_status.quitting)
353 ui_update_tab_status(doc);
354 ui_save_buttons_toggle(changed);
355 ui_set_window_title(doc);
356 ui_update_statusbar(doc, -1);
361 /* returns the next free place in the document list,
362 * or -1 if the documents_array is full */
363 static gint document_get_new_idx(void)
365 guint i;
367 for (i = 0; i < documents_array->len; i++)
369 if (documents[i]->editor == NULL)
371 return (gint) i;
374 return -1;
378 static void queue_colourise(GeanyDocument *doc)
380 /* Colourise the editor before it is next drawn */
381 doc->priv->colourise_needed = TRUE;
383 /* If the editor doesn't need drawing (e.g. after saving the current
384 * document), we need to force a redraw, so the expose event is triggered.
385 * This ensures we don't start colourising before all documents are opened/saved,
386 * only once the editor is drawn. */
387 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
391 #ifdef USE_GIO_FILEMON
392 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
393 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
394 GeanyDocument *doc)
396 g_return_if_fail(doc != NULL);
398 if (file_prefs.disk_check_timeout == 0)
399 return;
401 geany_debug("%s: event: %d previous file status: %d",
402 G_STRFUNC, event, doc->priv->file_disk_status);
403 switch (event)
405 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
407 if (doc->priv->file_disk_status == FILE_IGNORE)
408 doc->priv->file_disk_status = FILE_OK;
409 else
410 doc->priv->file_disk_status = FILE_CHANGED;
411 g_message("%s: FILE_CHANGED", G_STRFUNC);
412 break;
414 case G_FILE_MONITOR_EVENT_DELETED:
416 doc->priv->file_disk_status = FILE_CHANGED;
417 g_message("%s: FILE_MISSING", G_STRFUNC);
418 break;
420 default:
421 break;
423 if (doc->priv->file_disk_status != FILE_OK)
425 ui_update_tab_status(doc);
428 #endif
431 static void document_stop_file_monitoring(GeanyDocument *doc)
433 g_return_if_fail(doc != NULL);
435 if (doc->priv->monitor != NULL)
437 g_object_unref(doc->priv->monitor);
438 doc->priv->monitor = NULL;
443 static void monitor_file_setup(GeanyDocument *doc)
445 g_return_if_fail(doc != NULL);
446 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
447 * doesn't work at all for remote files and legacy polling is too slow. */
448 if (! doc->priv->is_remote)
450 #ifdef USE_GIO_FILEMON
451 gchar *locale_filename;
453 /* stop any previous monitoring */
454 document_stop_file_monitoring(doc);
456 locale_filename = utils_get_locale_from_utf8(doc->file_name);
457 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
459 /* get a file monitor and connect to the 'changed' signal */
460 GFile *file = g_file_new_for_path(locale_filename);
461 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
462 g_signal_connect(doc->priv->monitor, "changed",
463 G_CALLBACK(monitor_file_changed_cb), doc);
465 /* we set the rate limit according to the GUI pref but it's most probably not used */
466 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
468 g_object_unref(file);
470 g_free(locale_filename);
471 #endif
473 doc->priv->file_disk_status = FILE_OK;
477 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
479 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
480 if (DOC_VALID(doc))
482 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
483 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
485 if (source_widget == NULL)
486 source_widget = doc->priv->tag_tree;
488 if (focusw == source_widget)
489 gtk_widget_grab_focus(sci);
494 static gboolean on_idle_focus(gpointer doc)
496 document_try_focus(doc, NULL);
497 return FALSE;
501 /* Creates a new document and editor, adding a tab in the notebook.
502 * @return The created document */
503 static GeanyDocument *document_create(const gchar *utf8_filename)
505 GeanyDocument *doc;
506 gint new_idx;
507 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
509 if (cur_pages == 1)
511 doc = document_get_current();
512 /* remove the empty document first */
513 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
514 /* prevent immediately opening another new doc with
515 * new_document_after_close pref */
516 remove_page(0);
519 new_idx = document_get_new_idx();
520 if (new_idx == -1) /* expand the array, no free places */
522 doc = g_new0(GeanyDocument, 1);
524 new_idx = documents_array->len;
525 g_ptr_array_add(documents_array, doc);
528 doc = documents[new_idx];
530 /* initialize default document settings */
531 doc->priv = g_new0(GeanyDocumentPrivate, 1);
532 doc->index = new_idx;
533 doc->file_name = g_strdup(utf8_filename);
534 doc->editor = editor_create(doc);
535 #ifndef USE_GIO_FILEMON
536 doc->priv->last_check = time(NULL);
537 #endif
539 sidebar_openfiles_add(doc); /* sets doc->iter */
541 notebook_new_tab(doc);
543 /* select document in sidebar */
545 GtkTreeSelection *sel;
547 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
548 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
551 ui_document_buttons_update();
553 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
554 return doc;
559 * Closes the given document.
561 * @param doc The document to remove.
563 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
565 * @since 0.15
567 gboolean document_close(GeanyDocument *doc)
569 g_return_val_if_fail(doc, FALSE);
571 return document_remove_page(document_get_notebook_page(doc));
575 /* Call document_remove_page() instead, this is only needed for document_create()
576 * to prevent re-opening a new document when the last document is closed (if enabled). */
577 static gboolean remove_page(guint page_num)
579 GeanyDocument *doc = document_get_from_page(page_num);
581 g_return_val_if_fail(doc != NULL, FALSE);
583 if (doc->changed && ! dialogs_show_unsaved_file(doc))
584 return FALSE;
586 /* tell any plugins that the document is about to be closed */
587 g_signal_emit_by_name(geany_object, "document-close", doc);
589 /* Checking real_path makes it likely the file exists on disk */
590 if (! main_status.closing_all && doc->real_path != NULL)
591 ui_add_recent_document(doc);
593 doc->is_valid = FALSE;
595 if (! main_status.quitting)
597 notebook_remove_page(page_num);
598 sidebar_remove_document(doc);
599 navqueue_remove_file(doc->file_name);
600 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
602 g_free(doc->encoding);
603 g_free(doc->priv->saved_encoding.encoding);
604 g_free(doc->file_name);
605 g_free(doc->real_path);
606 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
608 if (doc->priv->tag_tree)
609 gtk_widget_destroy(doc->priv->tag_tree);
611 editor_destroy(doc->editor);
612 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
614 document_stop_file_monitoring(doc);
616 document_undo_clear(doc);
618 g_free(doc->priv);
620 /* reset document settings to defaults for re-use */
621 memset(doc, 0, sizeof(GeanyDocument));
623 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
625 sidebar_update_tag_list(NULL, FALSE);
626 ui_set_window_title(NULL);
627 ui_save_buttons_toggle(FALSE);
628 ui_update_popup_reundo_items(NULL);
629 ui_document_buttons_update();
630 build_menu_update(NULL);
632 return TRUE;
637 * Removes the given notebook tab at @a page_num and clears all related information
638 * in the document list.
640 * @param page_num The notebook page number to remove.
642 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
644 gboolean document_remove_page(guint page_num)
646 gboolean done = remove_page(page_num);
648 if (done && ui_prefs.new_document_after_close)
649 document_new_file_if_non_open();
651 return done;
655 /* used to keep a record of the unchanged document state encoding */
656 static void store_saved_encoding(GeanyDocument *doc)
658 g_free(doc->priv->saved_encoding.encoding);
659 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
660 doc->priv->saved_encoding.has_bom = doc->has_bom;
664 /* Opens a new empty document only if there are no other documents open */
665 GeanyDocument *document_new_file_if_non_open(void)
667 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
668 return document_new_file(NULL, NULL, NULL);
670 return NULL;
675 * Creates a new document.
676 * Line endings in @a text will be converted to the default setting.
677 * Afterwards, the @c "document-new" signal is emitted for plugins.
679 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
680 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
681 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
683 * @return The new document.
685 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
687 GeanyDocument *doc;
689 if (utf8_filename && g_path_is_absolute(utf8_filename))
691 gchar *tmp;
692 tmp = utils_strdupa(utf8_filename); /* work around const */
693 utils_tidy_path(tmp);
694 utf8_filename = tmp;
696 doc = document_create(utf8_filename);
698 g_assert(doc != NULL);
700 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
701 if (text)
703 GString *template = g_string_new(text);
704 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
706 sci_set_text(doc->editor->sci, template->str);
707 g_string_free(template, TRUE);
709 else
710 sci_clear_all(doc->editor->sci);
712 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
714 sci_set_undo_collection(doc->editor->sci, TRUE);
715 sci_empty_undo_buffer(doc->editor->sci);
717 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
718 /* store the opened encoding for undo/redo */
719 store_saved_encoding(doc);
721 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
722 ft = filetypes_detect_from_document(doc);
724 document_set_filetype(doc, ft); /* also re-parses tags */
726 ui_set_window_title(doc);
727 build_menu_update(doc);
728 document_set_text_changed(doc, FALSE);
729 ui_document_show_hide(doc); /* update the document menu */
731 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
732 /* bring it in front, jump to the start and grab the focus */
733 editor_goto_pos(doc->editor, 0, FALSE);
734 document_try_focus(doc, NULL);
736 #ifdef USE_GIO_FILEMON
737 monitor_file_setup(doc);
738 #else
739 doc->priv->mtime = time(NULL);
740 #endif
742 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
743 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
745 g_signal_emit_by_name(geany_object, "document-new", doc);
747 msgwin_status_add(_("New file \"%s\" opened."),
748 DOC_FILENAME(doc));
750 return doc;
755 * Opens a document specified by @a locale_filename.
756 * Afterwards, the @c "document-open" signal is emitted for plugins.
758 * @param locale_filename The filename of the document to load, in locale encoding.
759 * @param readonly Whether to open the document in read-only mode.
760 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
761 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
763 * @return The document opened or @c NULL.
765 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
766 GeanyFiletype *ft, const gchar *forced_enc)
768 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
772 typedef struct
774 gchar *data; /* null-terminated file data */
775 gsize len; /* string length of data */
776 gchar *enc;
777 gboolean bom;
778 time_t mtime; /* modification time, read by stat::st_mtime */
779 gboolean readonly;
780 } FileData;
783 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
784 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
785 FileData *filedata, const gchar *forced_enc)
787 GError *err = NULL;
788 struct stat st;
790 filedata->data = NULL;
791 filedata->len = 0;
792 filedata->enc = NULL;
793 filedata->bom = FALSE;
794 filedata->readonly = FALSE;
796 if (g_stat(locale_filename, &st) != 0)
798 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
799 display_filename, g_strerror(errno));
800 return FALSE;
803 filedata->mtime = st.st_mtime;
805 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
807 ui_set_statusbar(TRUE, "%s", err->message);
808 g_error_free(err);
809 return FALSE;
812 filedata->len = (gsize) st.st_size;
813 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
814 &filedata->enc, &filedata->bom, &filedata->readonly))
816 if (forced_enc)
818 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
819 display_filename, forced_enc);
821 else
823 ui_set_statusbar(TRUE,
824 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
825 display_filename);
827 g_free(filedata->data);
828 return FALSE;
831 if (filedata->readonly)
833 const gchar *warn_msg = _(
834 "The file \"%s\" could not be opened properly and has been truncated. " \
835 "This can occur if the file contains a NULL byte. " \
836 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
838 if (main_status.main_window_realized)
839 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
841 ui_set_statusbar(TRUE, warn_msg, display_filename);
844 return TRUE;
848 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
849 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
850 * if cl_options.goto_column is set.
852 * returns the new position which may have changed */
853 static gint set_cursor_position(GeanyEditor *editor, gint pos)
855 if (cl_options.goto_line >= 0)
856 { /* goto line which was specified on command line and then undefine the line */
857 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
858 editor->scroll_percent = 0.5F;
859 cl_options.goto_line = -1;
861 else if (pos > 0)
863 sci_set_current_position(editor->sci, pos, FALSE);
864 editor->scroll_percent = 0.5F;
867 if (cl_options.goto_column >= 0)
868 { /* goto column which was specified on command line and then undefine the column */
870 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
871 sci_set_current_position(editor->sci, new_pos, FALSE);
872 editor->scroll_percent = 0.5F;
873 cl_options.goto_column = -1;
874 return new_pos;
876 return sci_get_current_position(editor->sci);
880 /* Count lines that start with some hard tabs then a soft tab. */
881 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
883 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
884 ScintillaObject *sci = editor->sci;
885 gsize count = 0;
886 struct Sci_TextToFind ttf;
887 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
888 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
890 g_free(soft_tab);
892 ttf.chrg.cpMin = 0;
893 ttf.chrg.cpMax = sci_get_length(sci);
894 ttf.lpstrText = regex;
895 while (1)
897 gint pos;
899 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
900 if (pos == -1)
901 break; /* no more matches */
902 count++;
903 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
905 g_free(regex);
906 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
907 return count > sci_get_line_count(sci) * 0.02;
911 /* Detect the indent type based on counting the leading indent characters for each line.
912 * Returns whether detection succeeded, and the detected type in *type_ upon success */
913 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
915 GeanyEditor *editor = doc->editor;
916 ScintillaObject *sci = editor->sci;
917 gint line, line_count;
918 gsize tabs = 0, spaces = 0;
920 if (detect_tabs_and_spaces(editor))
922 *type_ = GEANY_INDENT_TYPE_BOTH;
923 return TRUE;
926 line_count = sci_get_line_count(sci);
927 for (line = 0; line < line_count; line++)
929 gint pos = sci_get_position_from_line(sci, line);
930 gchar c;
932 /* most code will have indent total <= 24, otherwise it's more likely to be
933 * alignment than indentation */
934 if (sci_get_line_indentation(sci, line) > 24)
935 continue;
937 c = sci_get_char_at(sci, pos);
938 if (c == '\t')
939 tabs++;
940 /* check for at least 2 spaces */
941 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
942 spaces++;
944 if (spaces == 0 && tabs == 0)
945 return FALSE;
947 /* the factors may need to be tweaked */
948 if (spaces > tabs * 4)
949 *type_ = GEANY_INDENT_TYPE_SPACES;
950 else if (tabs > spaces * 4)
951 *type_ = GEANY_INDENT_TYPE_TABS;
952 else
953 *type_ = GEANY_INDENT_TYPE_BOTH;
955 return TRUE;
959 /* Detect the indent width based on counting the leading indent characters for each line.
960 * Returns whether detection succeeded, and the detected width in *width_ upon success */
961 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
963 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
964 ScintillaObject *sci = editor->sci;
965 gint line, line_count;
966 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
967 gint count, width, i;
969 /* can't easily detect the supposed width of a tab, guess the default is OK */
970 if (type == GEANY_INDENT_TYPE_TABS)
971 return FALSE;
973 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
974 sci_set_tab_width(sci, 8);
976 line_count = sci_get_line_count(sci);
977 for (line = 0; line < line_count; line++)
979 gint pos = sci_get_line_indent_position(sci, line);
981 /* We probably don't have style info yet, because we're generally called just after
982 * the document got created, so we can't use highlighting_is_code_style().
983 * That's not good, but the assumption below that concerning lines start with an
984 * asterisk (common continuation character for C/C++/Java/...) should do the trick
985 * without removing too much legitimate lines. */
986 if (sci_get_char_at(sci, pos) == '*')
987 continue;
989 width = sci_get_line_indentation(sci, line);
990 /* most code will have indent total <= 24, otherwise it's more likely to be
991 * alignment than indentation */
992 if (width > 24)
993 continue;
994 /* < 2 is no indentation */
995 if (width < 2)
996 continue;
998 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1000 if ((width % (i + 2)) == 0)
1001 widths[i]++;
1004 count = 0;
1005 width = iprefs->width;
1006 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1008 /* give large indents higher weight not to be fooled by spurious indents */
1009 if (widths[i] >= count * 1.5)
1011 width = i + 2;
1012 count = widths[i];
1016 if (count == 0)
1017 return FALSE;
1019 *width_ = width;
1020 return TRUE;
1024 /* same as detect_indent_width() but uses editor's indent type */
1025 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1027 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1031 void document_apply_indent_settings(GeanyDocument *doc)
1033 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1034 GeanyIndentType type = iprefs->type;
1035 gint width = iprefs->width;
1037 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1039 if (type != iprefs->type)
1041 const gchar *name = NULL;
1043 switch (type)
1045 case GEANY_INDENT_TYPE_SPACES:
1046 name = _("Spaces");
1047 break;
1048 case GEANY_INDENT_TYPE_TABS:
1049 name = _("Tabs");
1050 break;
1051 case GEANY_INDENT_TYPE_BOTH:
1052 name = _("Tabs and Spaces");
1053 break;
1055 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1056 * and Spaces), the second one is the filename */
1057 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1058 DOC_FILENAME(doc));
1061 else if (doc->file_type->indent_type > -1)
1062 type = doc->file_type->indent_type;
1064 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1066 if (width != iprefs->width)
1068 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1069 DOC_FILENAME(doc));
1072 else if (doc->file_type->indent_width > -1)
1073 width = doc->file_type->indent_width;
1075 editor_set_indent(doc->editor, type, width);
1079 void document_show_tab(GeanyDocument *doc)
1081 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1082 document_get_notebook_page(doc));
1086 /* To open a new file, set doc to NULL; filename should be locale encoded.
1087 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1088 * pos is the cursor position, which can be overridden by --line and --column.
1089 * forced_enc can be NULL to detect the file encoding.
1090 * Returns: doc of the opened file or NULL if an error occurred. */
1091 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1092 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1094 gint editor_mode;
1095 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1096 gchar *utf8_filename = NULL;
1097 gchar *display_filename = NULL;
1098 gchar *locale_filename = NULL;
1099 GeanyFiletype *use_ft;
1100 FileData filedata;
1102 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1104 if (reload)
1106 utf8_filename = g_strdup(doc->file_name);
1107 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1109 else
1111 /* filename must not be NULL when opening a file */
1112 g_return_val_if_fail(filename, NULL);
1114 #ifdef G_OS_WIN32
1115 /* if filename is a shortcut, try to resolve it */
1116 locale_filename = win32_get_shortcut_target(filename);
1117 #else
1118 locale_filename = g_strdup(filename);
1119 #endif
1120 /* remove relative junk */
1121 utils_tidy_path(locale_filename);
1123 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1124 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1126 /* if file is already open, switch to it and go */
1127 doc = document_find_by_filename(utf8_filename);
1128 if (doc != NULL)
1130 ui_add_recent_document(doc); /* either add or reorder recent item */
1131 /* show the doc before reload dialog */
1132 document_show_tab(doc);
1133 document_check_disk_status(doc, TRUE); /* force a file changed check */
1136 if (reload || doc == NULL)
1137 { /* doc possibly changed */
1138 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1140 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1142 g_free(display_filename);
1143 g_free(utf8_filename);
1144 g_free(locale_filename);
1145 return NULL;
1148 if (! reload)
1150 doc = document_create(utf8_filename);
1151 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1153 /* file exists on disk, set real_path */
1154 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1156 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1157 monitor_file_setup(doc);
1160 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1161 sci_empty_undo_buffer(doc->editor->sci);
1163 /* add the text to the ScintillaObject */
1164 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1165 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1166 queue_colourise(doc); /* Ensure the document gets colourised. */
1168 /* detect & set line endings */
1169 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1170 sci_set_eol_mode(doc->editor->sci, editor_mode);
1171 g_free(filedata.data);
1173 sci_set_undo_collection(doc->editor->sci, TRUE);
1175 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1176 g_free(doc->encoding); /* if reloading, free old encoding */
1177 doc->encoding = filedata.enc;
1178 doc->has_bom = filedata.bom;
1179 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1181 doc->readonly = readonly || filedata.readonly;
1182 sci_set_readonly(doc->editor->sci, doc->readonly);
1184 /* update line number margin width */
1185 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1186 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1188 if (! reload)
1191 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1192 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1193 doc->editor);
1195 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1197 else
1198 { /* reloading */
1199 document_undo_clear(doc);
1201 use_ft = ft;
1203 /* update taglist, typedef keywords and build menu if necessary */
1204 document_set_filetype(doc, use_ft);
1206 /* set indentation settings after setting the filetype */
1207 if (reload)
1208 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1209 else
1210 document_apply_indent_settings(doc);
1212 document_set_text_changed(doc, FALSE); /* also updates tab state */
1213 ui_document_show_hide(doc); /* update the document menu */
1215 /* finally add current file to recent files menu, but not the files from the last session */
1216 if (! main_status.opening_session_files)
1217 ui_add_recent_document(doc);
1219 if (reload)
1221 g_signal_emit_by_name(geany_object, "document-reload", doc);
1222 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1224 else
1226 g_signal_emit_by_name(geany_object, "document-open", doc);
1227 /* For translators: this is the status window message for opening a file. %d is the number
1228 * of the newly opened file, %s indicates whether the file is opened read-only
1229 * (it is replaced with the string ", read-only"). */
1230 msgwin_status_add(_("File %s opened(%d%s)."),
1231 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1232 (readonly) ? _(", read-only") : "");
1236 g_free(display_filename);
1237 g_free(utf8_filename);
1238 g_free(locale_filename);
1240 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1241 pos = set_cursor_position(doc->editor, pos);
1242 /* now bring the file in front */
1243 editor_goto_pos(doc->editor, pos, FALSE);
1245 /* finally, let the editor widget grab the focus so you can start coding
1246 * right away */
1247 g_idle_add(on_idle_focus, doc);
1248 return doc;
1252 /* Takes a new line separated list of filename URIs and opens each file.
1253 * length is the length of the string */
1254 void document_open_file_list(const gchar *data, gsize length)
1256 guint i;
1257 gchar *filename;
1258 gchar **list;
1260 g_return_if_fail(data != NULL);
1262 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1264 /* stop at the end or first empty item, because last item is empty but not null */
1265 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1267 filename = utils_get_path_from_uri(list[i]);
1268 if (filename == NULL)
1269 continue;
1270 document_open_file(filename, FALSE, NULL, NULL);
1271 g_free(filename);
1274 g_strfreev(list);
1279 * Opens each file in the list @a filenames.
1280 * Internally, document_open_file() is called for every list item.
1282 * @param filenames A list of filenames to load, in locale encoding.
1283 * @param readonly Whether to open the document in read-only mode.
1284 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1285 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1287 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1288 const gchar *forced_enc)
1290 const GSList *item;
1292 for (item = filenames; item != NULL; item = g_slist_next(item))
1294 document_open_file(item->data, readonly, ft, forced_enc);
1300 * Reloads the document with the specified file encoding
1301 * @a forced_enc or @c NULL to auto-detect the file encoding.
1303 * @param doc The document to reload.
1304 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1306 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1308 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1310 gint pos = 0;
1311 GeanyDocument *new_doc;
1313 g_return_val_if_fail(doc != NULL, FALSE);
1315 /* try to set the cursor to the position before reloading */
1316 pos = sci_get_current_position(doc->editor->sci);
1317 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1319 return (new_doc != NULL);
1323 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1325 #ifndef USE_GIO_FILEMON
1326 struct stat st;
1328 g_return_val_if_fail(doc != NULL, FALSE);
1330 /* stat the file to get the timestamp, otherwise on Windows the actual
1331 * timestamp can be ahead of time(NULL) */
1332 if (g_stat(locale_filename, &st) != 0)
1334 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1335 g_strerror(errno));
1336 return FALSE;
1339 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1340 #endif
1341 return TRUE;
1345 /* Sets line and column to the given position byte_pos in the document.
1346 * byte_pos is the position counted in bytes, not characters */
1347 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1349 gint i;
1350 gint line_start;
1352 /* for some reason we can use byte count instead of character count here */
1353 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1354 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1355 /* get the column in the line */
1356 *column = byte_pos - line_start;
1358 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1359 * skip one byte(i++) and decrease the column number which is based on byte count */
1360 for (i = line_start; i < (line_start + *column); i++)
1362 if (sci_get_char_at(doc->editor->sci, i) < 0)
1364 (*column)--;
1365 i++;
1371 static void replace_header_filename(GeanyDocument *doc)
1373 gchar *filebase;
1374 gchar *filename;
1375 struct Sci_TextToFind ttf;
1377 g_return_if_fail(doc != NULL);
1378 g_return_if_fail(doc->file_type != NULL);
1380 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1381 if (doc->file_type->extension)
1382 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1383 else
1384 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1386 filename = g_path_get_basename(doc->file_name);
1388 /* only search the first 3 lines */
1389 ttf.chrg.cpMin = 0;
1390 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1391 ttf.lpstrText = filebase;
1393 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf, NULL) != -1)
1395 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1396 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1397 sci_replace_target(doc->editor->sci, filename, FALSE);
1399 g_free(filebase);
1400 g_free(filename);
1405 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1406 * you still have to call @ref document_save_file_as() to change the @a doc object.
1407 * It also stops monitoring for file changes to prevent receiving too many file change events
1408 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1410 * @param doc The current document which should be renamed.
1411 * @param new_filename The new filename in UTF-8 encoding.
1413 * @since 0.16
1415 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1417 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1418 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1419 gint result;
1421 /* stop file monitoring to avoid getting events for deleting/creating files,
1422 * it's re-setup in document_save_file_as() */
1423 document_stop_file_monitoring(doc);
1425 result = g_rename(old_locale_filename, new_locale_filename);
1426 if (result != 0)
1428 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1429 _("Error renaming file."), g_strerror(errno));
1431 g_free(old_locale_filename);
1432 g_free(new_locale_filename);
1436 /* Return TRUE if the document doesn't have a full filename set.
1437 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1438 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1439 * new files. */
1440 gboolean document_need_save_as(GeanyDocument *doc)
1442 g_return_val_if_fail(doc != NULL, FALSE);
1444 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1449 * Saves the document, detecting the filetype.
1451 * @param doc The document for the file to save.
1452 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1453 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1455 * @see document_save_file().
1457 * @since 0.16
1459 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1461 gboolean ret;
1463 g_return_val_if_fail(doc != NULL, FALSE);
1465 if (utf8_fname != NULL)
1466 SETPTR(doc->file_name, g_strdup(utf8_fname));
1468 /* reset real path, it's retrieved again in document_save() */
1469 SETPTR(doc->real_path, NULL);
1471 /* detect filetype */
1472 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1474 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1476 document_set_filetype(doc, ft);
1477 if (document_get_current() == doc)
1479 ignore_callback = TRUE;
1480 filetypes_select_radio_item(doc->file_type);
1481 ignore_callback = FALSE;
1484 replace_header_filename(doc);
1486 ret = document_save_file(doc, TRUE);
1488 /* file monitoring support, add file monitoring after the file has been saved
1489 * to ignore any earlier events */
1490 monitor_file_setup(doc);
1491 doc->priv->file_disk_status = FILE_IGNORE;
1493 if (ret)
1494 ui_add_recent_document(doc);
1495 return ret;
1499 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1501 GError *conv_error = NULL;
1502 gchar* conv_file_contents = NULL;
1503 gsize bytes_read;
1504 gsize conv_len;
1506 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1507 g_return_val_if_fail(len != NULL, FALSE);
1509 /* try to convert it from UTF-8 to original encoding */
1510 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1511 &bytes_read, &conv_len, &conv_error);
1513 if (conv_error != NULL)
1515 gchar *text = g_strdup_printf(
1516 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1517 doc->encoding);
1518 gchar *error_text;
1520 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1522 gint line, column;
1523 gint context_len;
1524 gunichar unic;
1525 /* don't read over the doc length */
1526 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1527 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1528 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1530 /* take only one valid Unicode character from the context and discard the leftover */
1531 unic = g_utf8_get_char_validated(context, -1);
1532 context_len = g_unichar_to_utf8(unic, context);
1533 context[context_len] = '\0';
1534 get_line_column_from_pos(doc, bytes_read, &line, &column);
1536 error_text = g_strdup_printf(
1537 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1538 conv_error->message, context, line + 1, column);
1540 else
1541 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1543 geany_debug("encoding error: %s", conv_error->message);
1544 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1545 g_error_free(conv_error);
1546 g_free(text);
1547 g_free(error_text);
1548 return FALSE;
1550 else
1552 g_free(*data);
1553 *data = conv_file_contents;
1554 *len = conv_len;
1556 return TRUE;
1560 static gchar *write_data_to_disk(const gchar *locale_filename,
1561 const gchar *data, gsize len)
1563 GError *error = NULL;
1565 if (file_prefs.use_safe_file_saving)
1567 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1568 * This is the only option that handles disk space exhaustion. */
1569 if (g_file_set_contents(locale_filename, data, len, &error))
1570 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1572 else if (file_prefs.use_gio_unsafe_file_saving)
1574 GFile *fp;
1576 /* Use GIO API to save file (GVFS-safe)
1577 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1578 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1579 fp = g_file_new_for_path(locale_filename);
1580 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1581 G_FILE_CREATE_NONE, NULL, NULL, &error);
1582 g_object_unref(fp);
1584 else
1586 FILE *fp;
1587 int save_errno;
1588 gchar *display_name = g_filename_display_name(locale_filename);
1590 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1591 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1592 errno = 0;
1593 fp = g_fopen(locale_filename, "wb");
1594 if (fp == NULL)
1596 save_errno = errno;
1598 g_set_error(&error,
1599 G_FILE_ERROR,
1600 g_file_error_from_errno(save_errno),
1601 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1602 display_name,
1603 g_strerror(save_errno));
1605 else
1607 gsize bytes_written;
1609 errno = 0;
1610 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1612 if (len != bytes_written)
1614 save_errno = errno;
1616 g_set_error(&error,
1617 G_FILE_ERROR,
1618 g_file_error_from_errno(save_errno),
1619 _("Failed to write file '%s': fwrite() failed: %s"),
1620 display_name,
1621 g_strerror(save_errno));
1624 errno = 0;
1625 /* preserve the fwrite() error if any */
1626 if (fclose(fp) != 0 && error == NULL)
1628 save_errno = errno;
1630 g_set_error(&error,
1631 G_FILE_ERROR,
1632 g_file_error_from_errno(save_errno),
1633 _("Failed to close file '%s': fclose() failed: %s"),
1634 display_name,
1635 g_strerror(save_errno));
1639 g_free(display_name);
1641 if (error != NULL)
1643 gchar *msg = g_strdup(error->message);
1644 g_error_free(error);
1645 /* geany will warn about file truncation for unsafe saving below */
1646 return msg;
1648 return NULL;
1652 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1653 const gchar *data, gsize len)
1655 gchar *err;
1657 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1658 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1660 err = write_data_to_disk(locale_filename, data, len);
1661 if (err)
1662 return err;
1664 /* now the file is on disk, set real_path */
1665 if (doc->real_path == NULL)
1667 doc->real_path = tm_get_real_path(locale_filename);
1668 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1669 monitor_file_setup(doc);
1671 return NULL;
1676 * Saves the document.
1677 * Also shows the Save As dialog if necessary.
1678 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1680 * Saving may include replacing tabs by spaces,
1681 * stripping trailing spaces and adding a final new line at the end of the file, depending
1682 * on user preferences. Then the @c "document-before-save" signal is emitted,
1683 * allowing plugins to modify the document before it is saved, and data is
1684 * actually written to disk.
1686 * On successful saving:
1687 * - GeanyDocument::real_path is set.
1688 * - The filetype is set again or auto-detected if it wasn't set yet.
1689 * - The @c "document-save" signal is emitted for plugins.
1691 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1692 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1693 * added in Geany 1.22.
1695 * @param doc The document to save.
1696 * @param force Whether to save the file even if it is not modified.
1698 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1700 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1702 gchar *errmsg;
1703 gchar *data;
1704 gsize len;
1705 gchar *locale_filename;
1706 const GeanyFilePrefs *fp;
1708 g_return_val_if_fail(doc != NULL, FALSE);
1710 if (document_need_save_as(doc))
1712 /* ensure doc is the current tab before showing the dialog */
1713 document_show_tab(doc);
1714 return dialogs_show_save_as();
1717 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1718 if (! force && (! doc->changed || doc->readonly))
1719 return FALSE;
1721 fp = project_get_file_prefs();
1722 /* replaces tabs by spaces but only if the current file is not a Makefile */
1723 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1724 editor_replace_tabs(doc->editor);
1725 /* strip trailing spaces */
1726 if (fp->strip_trailing_spaces)
1727 editor_strip_trailing_spaces(doc->editor);
1728 /* ensure the file has a newline at the end */
1729 if (fp->final_new_line)
1730 editor_ensure_final_newline(doc->editor);
1731 /* ensure newlines are consistent */
1732 if (fp->ensure_convert_new_lines)
1733 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1735 /* notify plugins which may wish to modify the document before it's saved */
1736 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1738 len = sci_get_length(doc->editor->sci) + 1;
1739 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1740 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1741 * encoding, it will be converted to doc->encoding below and this conversion
1742 * also changes the BOM */
1743 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1744 data[0] = (gchar) 0xef;
1745 data[1] = (gchar) 0xbb;
1746 data[2] = (gchar) 0xbf;
1747 sci_get_text(doc->editor->sci, len, data + 3);
1748 len += 3;
1750 else
1752 data = (gchar*) g_malloc(len);
1753 sci_get_text(doc->editor->sci, len, data);
1756 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1757 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1758 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1760 if (! save_convert_to_encoding(doc, &data, &len))
1762 g_free(data);
1763 return FALSE;
1766 else
1768 len = strlen(data);
1771 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1773 /* ignore file changed notification when the file is written */
1774 doc->priv->file_disk_status = FILE_IGNORE;
1776 /* actually write the content of data to the file on disk */
1777 errmsg = save_doc(doc, locale_filename, data, len);
1778 g_free(data);
1780 if (errmsg != NULL)
1782 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1784 if (!file_prefs.use_safe_file_saving)
1786 SETPTR(errmsg,
1787 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1789 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1790 doc->priv->file_disk_status = FILE_OK;
1791 utils_beep();
1792 g_free(locale_filename);
1793 g_free(errmsg);
1794 return FALSE;
1797 /* store the opened encoding for undo/redo */
1798 store_saved_encoding(doc);
1800 /* ignore the following things if we are quitting */
1801 if (! main_status.quitting)
1803 sci_set_savepoint(doc->editor->sci);
1805 if (file_prefs.disk_check_timeout > 0)
1806 document_update_timestamp(doc, locale_filename);
1808 /* update filetype-related things */
1809 document_set_filetype(doc, doc->file_type);
1811 document_update_tab_label(doc);
1813 msgwin_status_add(_("File %s saved."), doc->file_name);
1814 ui_update_statusbar(doc, -1);
1815 #ifdef HAVE_VTE
1816 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1817 #endif
1819 g_free(locale_filename);
1821 g_signal_emit_by_name(geany_object, "document-save", doc);
1823 return TRUE;
1827 /* special search function, used from the find entry in the toolbar
1828 * return TRUE if text was found otherwise FALSE
1829 * return also TRUE if text is empty */
1830 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1831 gboolean backwards)
1833 gint start_pos, search_pos;
1834 struct Sci_TextToFind ttf;
1836 g_return_val_if_fail(text != NULL, FALSE);
1837 g_return_val_if_fail(doc != NULL, FALSE);
1838 if (! *text)
1839 return TRUE;
1841 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1842 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1844 /* search cursor to end or start */
1845 ttf.chrg.cpMin = start_pos;
1846 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1847 ttf.lpstrText = (gchar *)text;
1848 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1850 /* if no match, search start (or end) to cursor */
1851 if (search_pos == -1)
1853 if (backwards)
1855 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1856 ttf.chrg.cpMax = start_pos;
1858 else
1860 ttf.chrg.cpMin = 0;
1861 ttf.chrg.cpMax = start_pos + strlen(text);
1863 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1866 if (search_pos != -1)
1868 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1870 /* unfold maybe folded results */
1871 sci_ensure_line_is_visible(doc->editor->sci, line);
1873 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1874 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1876 if (! editor_line_in_view(doc->editor, line))
1877 { /* we need to force scrolling in case the cursor is outside of the current visible area
1878 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1879 * while searching */
1880 editor_scroll_to_line(doc->editor, -1, 0.3F);
1882 else
1883 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1884 return TRUE;
1886 else
1888 if (! inc)
1890 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1892 utils_beep();
1893 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1894 return FALSE;
1899 /* General search function, used from the find dialog.
1900 * Returns -1 on failure or the start position of the matching text.
1901 * Will skip past any selection, ignoring it.
1903 * @param text Text to find.
1904 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1906 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
1907 gint flags, gboolean search_backwards, GeanyMatchInfo **match_,
1908 gboolean scroll, GtkWidget *parent)
1910 gint selection_end, selection_start, search_pos;
1912 g_return_val_if_fail(doc != NULL && text != NULL, -1);
1913 if (! *text)
1914 return -1;
1916 /* Sci doesn't support searching backwards with a regex */
1917 if (flags & SCFIND_REGEXP)
1918 search_backwards = FALSE;
1920 if (!original_text)
1921 original_text = text;
1923 selection_start = sci_get_selection_start(doc->editor->sci);
1924 selection_end = sci_get_selection_end(doc->editor->sci);
1925 if ((selection_end - selection_start) > 0)
1926 { /* there's a selection so go to the end */
1927 if (search_backwards)
1928 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
1929 else
1930 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
1933 sci_set_search_anchor(doc->editor->sci);
1934 if (search_backwards)
1935 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
1936 else
1937 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
1939 if (search_pos != -1)
1941 /* unfold maybe folded results */
1942 sci_ensure_line_is_visible(doc->editor->sci,
1943 sci_get_line_from_position(doc->editor->sci, search_pos));
1944 if (scroll)
1945 doc->editor->scroll_percent = 0.3F;
1947 else
1949 gint sci_len = sci_get_length(doc->editor->sci);
1951 /* if we just searched the whole text, give up searching. */
1952 if ((selection_end == 0 && ! search_backwards) ||
1953 (selection_end == sci_len && search_backwards))
1955 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
1956 utils_beep();
1957 return -1;
1960 /* we searched only part of the document, so ask whether to wraparound. */
1961 if (search_prefs.always_wrap ||
1962 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
1963 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
1965 gint ret;
1967 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
1968 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
1969 if (ret == -1)
1970 { /* return to original cursor position if not found */
1971 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
1973 return ret;
1976 return search_pos;
1980 /* Replaces the selection if it matches, otherwise just finds the next match.
1981 * Returns: start of replaced text, or -1 if no replacement was made
1983 * @param find_text Text to find.
1984 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
1986 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
1987 const gchar *replace_text, gint flags, gboolean search_backwards)
1989 gint selection_end, selection_start, search_pos;
1990 GeanyMatchInfo *match = NULL;
1992 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
1994 if (! *find_text)
1995 return -1;
1997 /* Sci doesn't support searching backwards with a regex */
1998 if (flags & SCFIND_REGEXP)
1999 search_backwards = FALSE;
2001 if (!original_find_text)
2002 original_find_text = find_text;
2004 selection_start = sci_get_selection_start(doc->editor->sci);
2005 selection_end = sci_get_selection_end(doc->editor->sci);
2006 if (selection_end == selection_start)
2008 /* no selection so just find the next match */
2009 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2010 return -1;
2012 /* there's a selection so go to the start before finding to search through it
2013 * this ensures there is a match */
2014 if (search_backwards)
2015 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2016 else
2017 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2019 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2020 /* return if the original selected text did not match (at the start of the selection) */
2021 if (search_pos != selection_start)
2023 if (search_pos != -1)
2024 geany_match_info_free(match);
2025 return -1;
2028 if (search_pos != -1)
2030 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2031 /* select the replacement - find text will skip past the selected text */
2032 sci_set_selection_start(doc->editor->sci, search_pos);
2033 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2034 geany_match_info_free(match);
2036 else
2038 /* no match in the selection */
2039 utils_beep();
2041 return search_pos;
2045 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2046 const gchar *original_replace_text)
2048 gchar *filename;
2050 if (count == 0)
2052 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2053 return;
2056 filename = g_path_get_basename(DOC_FILENAME(doc));
2057 ui_set_statusbar(TRUE, ngettext(
2058 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2059 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2060 count), filename, count, original_find_text, original_replace_text);
2061 g_free(filename);
2065 /* Replace all text matches in a certain range within document.
2066 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2067 * or -1 if no text was found.
2068 * scroll_to_match is whether to scroll the last replacement in view (which also
2069 * clears the selection).
2070 * Returns: the number of replacements made. */
2071 static guint
2072 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2073 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2075 gint count = 0;
2076 struct Sci_TextToFind ttf;
2077 ScintillaObject *sci;
2079 if (new_range_end != NULL)
2080 *new_range_end = -1;
2082 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2084 if (! *find_text || doc->readonly)
2085 return 0;
2087 sci = doc->editor->sci;
2089 ttf.chrg.cpMin = start;
2090 ttf.chrg.cpMax = end;
2091 ttf.lpstrText = (gchar*)find_text;
2093 sci_start_undo_action(sci);
2094 count = search_replace_range(sci, &ttf, flags, replace_text);
2095 sci_end_undo_action(sci);
2097 if (count > 0)
2098 { /* scroll last match in view, will destroy the existing selection */
2099 if (scroll_to_match)
2100 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2102 if (new_range_end != NULL)
2103 *new_range_end = ttf.chrg.cpMax;
2105 return count;
2109 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2110 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2112 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2113 gint max_column = 0, count = 0;
2114 gboolean replaced = FALSE;
2116 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2118 if (! *find_text)
2119 return;
2121 selection_start = sci_get_selection_start(doc->editor->sci);
2122 selection_end = sci_get_selection_end(doc->editor->sci);
2123 /* do we have a selection? */
2124 if ((selection_end - selection_start) == 0)
2126 utils_beep();
2127 return;
2130 selection_mode = sci_get_selection_mode(doc->editor->sci);
2131 selected_lines = sci_get_lines_selected(doc->editor->sci);
2132 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2133 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2135 gint first_line, line;
2137 sci_start_undo_action(doc->editor->sci);
2139 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2140 /* Find the last line with chars selected (not EOL char) */
2141 last_line = sci_get_line_from_position(doc->editor->sci,
2142 selection_end - editor_get_eol_char_len(doc->editor));
2143 last_line = MAX(first_line, last_line);
2144 for (line = first_line; line < (first_line + selected_lines); line++)
2146 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2147 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2149 /* skip line if there is no selection */
2150 if (line_start != INVALID_POSITION)
2152 /* don't let document_replace_range() scroll to match to keep our selection */
2153 gint new_sel_end;
2155 count += document_replace_range(doc, find_text, replace_text, flags,
2156 line_start, line_end, FALSE, &new_sel_end);
2157 if (new_sel_end != -1)
2159 replaced = TRUE;
2160 /* this gets the greatest column within the selection after replacing */
2161 max_column = MAX(max_column,
2162 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2166 sci_end_undo_action(doc->editor->sci);
2168 else /* handle normal line selection */
2170 count += document_replace_range(doc, find_text, replace_text, flags,
2171 selection_start, selection_end, TRUE, &selection_end);
2172 if (selection_end != -1)
2173 replaced = TRUE;
2176 if (replaced)
2177 { /* update the selection for the new endpoint */
2179 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2181 /* now we can scroll to the selection and destroy it because we rebuild it later */
2182 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2184 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2185 * the highest column on the last line. The wrapped selection is completely different
2186 * from the original one, so skip the selection at all */
2187 /* TODO is there a better way to handle the wrapped selection? */
2188 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2189 { /* for keeping and adjusting the selection in multi line rectangle selection we
2190 * need the last line of the original selection and the greatest column number after
2191 * replacing and set the selection end to the last line at the greatest column */
2192 sci_set_selection_start(doc->editor->sci, selection_start);
2193 sci_set_selection_end(doc->editor->sci,
2194 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2195 sci_set_selection_mode(doc->editor->sci, selection_mode);
2198 else
2200 sci_set_selection_start(doc->editor->sci, selection_start);
2201 sci_set_selection_end(doc->editor->sci, selection_end);
2204 else /* no replacements */
2205 utils_beep();
2207 show_replace_summary(doc, count, original_find_text, original_replace_text);
2211 /* returns number of replacements made. */
2212 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2213 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2215 gint len, count;
2216 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2218 if (! *find_text)
2219 return FALSE;
2221 len = sci_get_length(doc->editor->sci);
2222 count = document_replace_range(
2223 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2225 show_replace_summary(doc, count, original_find_text, original_replace_text);
2226 return count;
2231 * Parses or re-parses the document's buffer and updates the type
2232 * keywords and symbol list.
2234 * @param doc The document.
2236 void document_update_tags(GeanyDocument *doc)
2238 guchar *buffer_ptr;
2239 gsize len;
2241 g_return_if_fail(DOC_VALID(doc));
2242 g_return_if_fail(app->tm_workspace != NULL);
2244 /* early out if it's a new file or doesn't support tags */
2245 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2247 /* We must call sidebar_update_tag_list() before returning,
2248 * to ensure that the symbol list is always updated properly (e.g.
2249 * when creating a new document with a partial filename set. */
2250 sidebar_update_tag_list(doc, FALSE);
2251 return;
2254 /* create a new TM file if there isn't one yet */
2255 if (! doc->tm_file)
2257 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2258 const gchar *name;
2260 /* lookup the name rather than using filetype name to support custom filetypes */
2261 name = tm_source_file_get_lang_name(doc->file_type->lang);
2262 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2263 g_free(locale_filename);
2265 if (doc->tm_file && !tm_workspace_add_object(doc->tm_file))
2267 tm_work_object_free(doc->tm_file);
2268 doc->tm_file = NULL;
2272 /* early out if there's no work object and we couldn't create one */
2273 if (doc->tm_file == NULL)
2275 /* We must call sidebar_update_tag_list() before returning,
2276 * to ensure that the symbol list is always updated properly (e.g.
2277 * when creating a new document with a partial filename set. */
2278 sidebar_update_tag_list(doc, FALSE);
2279 return;
2282 len = sci_get_length(doc->editor->sci);
2283 /* tm_source_file_buffer_update() below don't support 0-length data,
2284 * so just empty the tags array and leave */
2285 if (len < 1)
2287 tm_tags_array_free(doc->tm_file->tags_array, FALSE);
2288 sidebar_update_tag_list(doc, FALSE);
2289 return;
2292 /* Parse Scintilla's buffer directly using TagManager
2293 * Note: this buffer *MUST NOT* be modified */
2294 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2295 tm_source_file_buffer_update(doc->tm_file, buffer_ptr, len, TRUE);
2297 sidebar_update_tag_list(doc, TRUE);
2298 document_highlight_tags(doc);
2302 /* Re-highlights type keywords without re-parsing the whole document. */
2303 void document_highlight_tags(GeanyDocument *doc)
2305 GString *keywords_str;
2306 gchar *keywords;
2307 gint keyword_idx;
2309 /* some filetypes support type keywords (such as struct names), but not
2310 * necessarily all filetypes for a particular scintilla lexer. this
2311 * tells us whether the filetype supports keywords, and if so
2312 * which index to use for the scintilla keywords set. */
2313 switch (doc->file_type->id)
2315 case GEANY_FILETYPES_C:
2316 case GEANY_FILETYPES_CPP:
2317 case GEANY_FILETYPES_CS:
2318 case GEANY_FILETYPES_D:
2319 case GEANY_FILETYPES_JAVA:
2320 case GEANY_FILETYPES_OBJECTIVEC:
2321 case GEANY_FILETYPES_VALA:
2322 case GEANY_FILETYPES_RUST:
2325 /* index of the keyword set in the Scintilla lexer, for
2326 * example in LexCPP.cxx, see "cppWordLists" global array.
2327 * TODO: this magic number should be a member of the filetype */
2328 keyword_idx = 3;
2329 break;
2331 default:
2332 return; /* early out if type keywords are not supported */
2334 if (!app->tm_workspace->work_object.tags_array)
2335 return;
2337 /* get any type keywords and tell scintilla about them
2338 * this will cause the type keywords to be colourized in scintilla */
2339 keywords_str = symbols_find_tags_as_string(app->tm_workspace->work_object.tags_array,
2340 TM_GLOBAL_TYPE_MASK, doc->file_type->lang);
2341 if (keywords_str)
2343 keywords = g_string_free(keywords_str, FALSE);
2344 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2345 g_free(keywords);
2346 queue_colourise(doc); /* force re-highlighting the entire document */
2351 static gboolean on_document_update_tag_list_idle(gpointer data)
2353 GeanyDocument *doc = data;
2355 if (! DOC_VALID(doc))
2356 return FALSE;
2358 if (! main_status.quitting)
2359 document_update_tags(doc);
2361 doc->priv->tag_list_update_source = 0;
2363 /* don't update the tags until another modification of the buffer */
2364 return FALSE;
2368 void document_update_tag_list_in_idle(GeanyDocument *doc)
2370 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2371 return;
2373 /* prevent "stacking up" callback handlers, we only need one to run soon */
2374 if (doc->priv->tag_list_update_source != 0)
2375 g_source_remove(doc->priv->tag_list_update_source);
2377 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2378 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2382 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2383 gboolean filetype_changed)
2385 g_return_if_fail(doc);
2386 if (type == NULL)
2387 type = filetypes[GEANY_FILETYPES_NONE];
2389 if (filetype_changed)
2391 doc->file_type = type;
2393 /* delete tm file object to force creation of a new one */
2394 if (doc->tm_file != NULL)
2396 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2397 doc->tm_file = NULL;
2399 /* load tags files before highlighting (some lexers highlight global typenames) */
2400 if (type->id != GEANY_FILETYPES_NONE)
2401 symbols_global_tags_loaded(type->id);
2403 highlighting_set_styles(doc->editor->sci, type);
2404 editor_set_indentation_guides(doc->editor);
2405 build_menu_update(doc);
2406 queue_colourise(doc);
2407 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2410 document_update_tags(doc);
2414 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2415 * @param doc The document to use.
2416 * @param type The filetype. */
2417 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2419 gboolean ft_changed;
2420 GeanyFiletype *old_ft;
2422 g_return_if_fail(doc);
2423 if (type == NULL)
2424 type = filetypes[GEANY_FILETYPES_NONE];
2426 old_ft = doc->file_type;
2427 geany_debug("%s : %s (%s)",
2428 (doc->file_name != NULL) ? doc->file_name : "unknown",
2429 type->name,
2430 (doc->encoding != NULL) ? doc->encoding : "unknown");
2432 ft_changed = (doc->file_type != type); /* filetype has changed */
2433 document_load_config(doc, type, ft_changed);
2435 if (ft_changed)
2437 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2439 /* assume that if previous filetype was none and the settings are the default ones, this
2440 * is the first time the filetype is carefully set, so we should apply indent settings */
2441 if (old_ft && old_ft->id == GEANY_FILETYPES_NONE &&
2442 doc->editor->indent_type == iprefs->type &&
2443 doc->editor->indent_width == iprefs->width)
2445 document_apply_indent_settings(doc);
2446 ui_document_show_hide(doc);
2449 sidebar_openfiles_update(doc); /* to update the icon */
2450 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2455 void document_reload_config(GeanyDocument *doc)
2457 document_load_config(doc, doc->file_type, TRUE);
2462 * Sets the encoding of a document.
2463 * This function only set the encoding of the %document, it does not any conversions. The new
2464 * encoding is used when e.g. saving the file.
2466 * @param doc The document to use.
2467 * @param new_encoding The encoding to be set for the document.
2469 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2471 if (doc == NULL || new_encoding == NULL ||
2472 utils_str_equal(new_encoding, doc->encoding))
2473 return;
2475 g_free(doc->encoding);
2476 doc->encoding = g_strdup(new_encoding);
2478 ui_update_statusbar(doc, -1);
2479 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2480 encodings_is_unicode_charset(doc->encoding));
2484 /* own Undo / Redo implementation to be able to undo / redo changes
2485 * to the encoding or the Unicode BOM (which are Scintilla independet).
2486 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2488 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2489 void document_undo_clear(GeanyDocument *doc)
2491 undo_action *a;
2493 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2495 a = g_trash_stack_pop(&doc->priv->undo_actions);
2496 if (G_LIKELY(a != NULL))
2498 switch (a->type)
2500 case UNDO_ENCODING: g_free(a->data); break;
2501 default: break;
2503 g_free(a);
2506 doc->priv->undo_actions = NULL;
2508 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2510 a = g_trash_stack_pop(&doc->priv->redo_actions);
2511 if (G_LIKELY(a != NULL))
2513 switch (a->type)
2515 case UNDO_ENCODING: g_free(a->data); break;
2516 default: break;
2518 g_free(a);
2521 doc->priv->redo_actions = NULL;
2523 if (! main_status.quitting && doc->editor != NULL)
2524 document_set_text_changed(doc, FALSE);
2528 /* note: this is called on SCN_MODIFIED notifications */
2529 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2531 undo_action *action;
2533 g_return_if_fail(doc != NULL);
2535 action = g_new0(undo_action, 1);
2536 action->type = type;
2537 action->data = data;
2539 g_trash_stack_push(&doc->priv->undo_actions, action);
2541 /* avoid unnecessary redraws */
2542 if (type != UNDO_SCINTILLA || !doc->changed)
2543 document_set_text_changed(doc, TRUE);
2545 ui_update_popup_reundo_items(doc);
2549 gboolean document_can_undo(GeanyDocument *doc)
2551 g_return_val_if_fail(doc != NULL, FALSE);
2553 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2554 return TRUE;
2555 else
2556 return FALSE;
2560 static void update_changed_state(GeanyDocument *doc)
2562 doc->changed =
2563 (sci_is_modified(doc->editor->sci) ||
2564 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2565 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2566 document_set_text_changed(doc, doc->changed);
2570 void document_undo(GeanyDocument *doc)
2572 undo_action *action;
2574 g_return_if_fail(doc != NULL);
2576 action = g_trash_stack_pop(&doc->priv->undo_actions);
2578 if (G_UNLIKELY(action == NULL))
2580 /* fallback, should not be necessary */
2581 geany_debug("%s: fallback used", G_STRFUNC);
2582 sci_undo(doc->editor->sci);
2584 else
2586 switch (action->type)
2588 case UNDO_SCINTILLA:
2590 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2592 sci_undo(doc->editor->sci);
2593 break;
2595 case UNDO_BOM:
2597 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2599 doc->has_bom = GPOINTER_TO_INT(action->data);
2600 ui_update_statusbar(doc, -1);
2601 ui_document_show_hide(doc);
2602 break;
2604 case UNDO_ENCODING:
2606 /* use the "old" encoding */
2607 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2609 document_set_encoding(doc, (const gchar*)action->data);
2611 ignore_callback = TRUE;
2612 encodings_select_radio_item((const gchar*)action->data);
2613 ignore_callback = FALSE;
2615 g_free(action->data);
2616 break;
2618 default: break;
2621 g_free(action); /* free the action which was taken from the stack */
2623 update_changed_state(doc);
2624 ui_update_popup_reundo_items(doc);
2628 gboolean document_can_redo(GeanyDocument *doc)
2630 g_return_val_if_fail(doc != NULL, FALSE);
2632 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2633 return TRUE;
2634 else
2635 return FALSE;
2639 void document_redo(GeanyDocument *doc)
2641 undo_action *action;
2643 g_return_if_fail(doc != NULL);
2645 action = g_trash_stack_pop(&doc->priv->redo_actions);
2647 if (G_UNLIKELY(action == NULL))
2649 /* fallback, should not be necessary */
2650 geany_debug("%s: fallback used", G_STRFUNC);
2651 sci_redo(doc->editor->sci);
2653 else
2655 switch (action->type)
2657 case UNDO_SCINTILLA:
2659 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2661 sci_redo(doc->editor->sci);
2662 break;
2664 case UNDO_BOM:
2666 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2668 doc->has_bom = GPOINTER_TO_INT(action->data);
2669 ui_update_statusbar(doc, -1);
2670 ui_document_show_hide(doc);
2671 break;
2673 case UNDO_ENCODING:
2675 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2677 document_set_encoding(doc, (const gchar*)action->data);
2679 ignore_callback = TRUE;
2680 encodings_select_radio_item((const gchar*)action->data);
2681 ignore_callback = FALSE;
2683 g_free(action->data);
2684 break;
2686 default: break;
2689 g_free(action); /* free the action which was taken from the stack */
2691 update_changed_state(doc);
2692 ui_update_popup_reundo_items(doc);
2696 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2698 undo_action *action;
2700 g_return_if_fail(doc != NULL);
2702 action = g_new0(undo_action, 1);
2703 action->type = type;
2704 action->data = data;
2706 g_trash_stack_push(&doc->priv->redo_actions, action);
2708 if (type != UNDO_SCINTILLA || !doc->changed)
2709 document_set_text_changed(doc, TRUE);
2711 ui_update_popup_reundo_items(doc);
2715 enum
2717 STATUS_CHANGED,
2718 #ifdef USE_GIO_FILEMON
2719 STATUS_DISK_CHANGED,
2720 #endif
2721 STATUS_READONLY
2723 static struct
2725 const gchar *name;
2726 GdkColor color;
2727 gboolean loaded;
2728 } document_status_styles[] = {
2729 { "geany-document-status-changed", {0}, FALSE },
2730 #ifdef USE_GIO_FILEMON
2731 { "geany-document-status-disk-changed", {0}, FALSE },
2732 #endif
2733 { "geany-document-status-readonly", {0}, FALSE }
2737 static gint document_get_status_id(GeanyDocument *doc)
2739 if (doc->changed)
2740 return STATUS_CHANGED;
2741 #ifdef USE_GIO_FILEMON
2742 else if (doc->priv->file_disk_status == FILE_CHANGED)
2743 return STATUS_DISK_CHANGED;
2744 #endif
2745 else if (doc->readonly)
2746 return STATUS_READONLY;
2748 return -1;
2752 /* returns an identifier that is to be set as a widget name or class to get it styled
2753 * depending on the document status (changed, readonly, etc.)
2754 * a NULL return value means default (unchanged) style */
2755 const gchar *document_get_status_widget_class(GeanyDocument *doc)
2757 gint status;
2759 g_return_val_if_fail(doc != NULL, NULL);
2761 status = document_get_status_id(doc);
2762 if (status < 0)
2763 return NULL;
2764 else
2765 return document_status_styles[status].name;
2770 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2771 * Returned colors are red if the document has changes, green if the document is read-only
2772 * or simply @c NULL if the document is unmodified but writable.
2774 * @param doc The document to use.
2776 * @return The color for the document or @c NULL if the default color should be used. The color
2777 * object is owned by Geany and should not be modified or freed.
2779 * @since 0.16
2781 const GdkColor *document_get_status_color(GeanyDocument *doc)
2783 gint status;
2785 g_return_val_if_fail(doc != NULL, NULL);
2787 status = document_get_status_id(doc);
2788 if (status < 0)
2789 return NULL;
2790 if (! document_status_styles[status].loaded)
2792 #if GTK_CHECK_VERSION(3, 0, 0)
2793 GdkRGBA color;
2794 GtkWidgetPath *path = gtk_widget_path_new();
2795 GtkStyleContext *ctx = gtk_style_context_new();
2796 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
2797 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
2798 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
2799 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
2800 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
2801 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
2802 gtk_style_context_set_path(ctx, path);
2803 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
2804 document_status_styles[status].color.red = 0xffff * color.red;
2805 document_status_styles[status].color.green = 0xffff * color.green;
2806 document_status_styles[status].color.blue = 0xffff * color.blue;
2807 document_status_styles[status].loaded = TRUE;
2808 gtk_widget_path_unref(path);
2809 g_object_unref(ctx);
2810 #else
2811 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
2812 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
2813 document_status_styles[status].name, NULL);
2814 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
2816 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
2817 document_status_styles[status].loaded = TRUE;
2818 g_free(path);
2819 #endif
2821 return &document_status_styles[status].color;
2825 /** Accessor function for @ref GeanyData::documents_array items.
2826 * @warning Always check the returned document is valid (@c doc->is_valid).
2827 * @param idx @c documents_array index.
2828 * @return The document, or @c NULL if @a idx is out of range.
2830 * @since 0.16
2832 GeanyDocument *document_index(gint idx)
2834 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2838 /* create a new file and copy file content and properties */
2839 G_MODULE_EXPORT void on_clone1_activate(GtkMenuItem *menuitem, gpointer user_data)
2841 GeanyDocument *old_doc = document_get_current();
2843 if (old_doc)
2844 document_clone(old_doc);
2848 GeanyDocument *document_clone(GeanyDocument *old_doc)
2850 gchar *text;
2851 GeanyDocument *doc;
2852 ScintillaObject *old_sci;
2854 g_return_val_if_fail(old_doc, NULL);
2855 old_sci = old_doc->editor->sci;
2856 if (sci_has_selection(old_sci))
2857 text = sci_get_selection_contents(old_sci);
2858 else
2859 text = sci_get_contents(old_sci, -1);
2861 doc = document_new_file(NULL, old_doc->file_type, text);
2862 g_free(text);
2863 document_set_text_changed(doc, TRUE);
2865 /* copy file properties */
2866 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2867 doc->editor->line_breaking = old_doc->editor->line_breaking;
2868 doc->editor->auto_indent = old_doc->editor->auto_indent;
2869 editor_set_indent(doc->editor, old_doc->editor->indent_type,
2870 old_doc->editor->indent_width);
2871 doc->readonly = old_doc->readonly;
2872 doc->has_bom = old_doc->has_bom;
2873 document_set_encoding(doc, old_doc->encoding);
2874 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2875 sci_set_readonly(doc->editor->sci, doc->readonly);
2877 /* update ui */
2878 ui_document_show_hide(doc);
2879 return doc;
2883 /* @note If successful, this should always be followed up with a call to
2884 * document_close_all().
2885 * @return TRUE if all files were saved or had their changes discarded. */
2886 gboolean document_account_for_unsaved(void)
2888 guint i, p, page_count;
2890 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2891 /* iterate over documents in tabs order */
2892 for (p = 0; p < page_count; p++)
2894 GeanyDocument *doc = document_get_from_page(p);
2896 if (DOC_VALID(doc) && doc->changed)
2898 if (! dialogs_show_unsaved_file(doc))
2899 return FALSE;
2902 /* all documents should now be accounted for, so ignore any changes */
2903 foreach_document (i)
2905 documents[i]->changed = FALSE;
2907 return TRUE;
2911 static void force_close_all(void)
2913 guint i, len = documents_array->len;
2915 /* check all documents have been accounted for */
2916 for (i = 0; i < len; i++)
2918 if (documents[i]->is_valid)
2920 g_return_if_fail(!documents[i]->changed);
2923 main_status.closing_all = TRUE;
2925 foreach_document(i)
2927 document_close(documents[i]);
2930 main_status.closing_all = FALSE;
2934 gboolean document_close_all(void)
2936 if (! document_account_for_unsaved())
2937 return FALSE;
2939 force_close_all();
2941 return TRUE;
2945 static void monitor_reload_file(GeanyDocument *doc)
2947 gchar *base_name = g_path_get_basename(doc->file_name);
2948 gint ret;
2950 /* we use No instead of Cancel to avoid mnemonic clash */
2951 ret = dialogs_show_prompt(NULL,
2952 GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
2953 GTK_STOCK_NO, GTK_RESPONSE_CANCEL,
2954 _("_Reload"), GTK_RESPONSE_ACCEPT,
2955 _("Do you want to reload it?"),
2956 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2957 base_name);
2958 g_free(base_name);
2960 if (ret == GTK_RESPONSE_ACCEPT)
2961 document_reload_file(doc, doc->encoding);
2962 else if (ret == GTK_RESPONSE_CLOSE)
2963 document_close(doc);
2967 static gboolean monitor_resave_missing_file(GeanyDocument *doc)
2969 gboolean want_reload = FALSE;
2970 gboolean file_saved = FALSE;
2971 gint ret;
2973 ret = dialogs_show_prompt(NULL,
2974 _("Close _without saving"), GTK_RESPONSE_CLOSE,
2975 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2976 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
2977 _("Try to resave the file?"),
2978 _("File \"%s\" was not found on disk!"),
2979 doc->file_name);
2980 if (ret == GTK_RESPONSE_ACCEPT)
2982 file_saved = dialogs_show_save_as();
2983 want_reload = TRUE;
2985 else if (ret == GTK_RESPONSE_CLOSE)
2987 document_close(doc);
2989 if (ret != GTK_RESPONSE_CLOSE && ! file_saved)
2991 /* file is missing - set unsaved state */
2992 document_set_text_changed(doc, TRUE);
2993 /* don't prompt more than once */
2994 SETPTR(doc->real_path, NULL);
2997 return want_reload;
3001 /* Set force to force a disk check, otherwise it is ignored if there was a check
3002 * in the last file_prefs.disk_check_timeout seconds.
3003 * @return @c TRUE if the file has changed. */
3004 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3006 gboolean ret = FALSE;
3007 gboolean use_gio_filemon;
3008 time_t cur_time = 0;
3009 struct stat st;
3010 gchar *locale_filename;
3011 FileDiskStatus old_status;
3013 g_return_val_if_fail(doc != NULL, FALSE);
3015 /* ignore remote files and documents that have never been saved to disk */
3016 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3017 || doc->real_path == NULL || doc->priv->is_remote)
3018 return FALSE;
3020 use_gio_filemon = (doc->priv->monitor != NULL);
3022 if (use_gio_filemon)
3024 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3025 return FALSE;
3027 else
3029 cur_time = time(NULL);
3030 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3031 return FALSE;
3033 doc->priv->last_check = cur_time;
3036 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3037 if (g_stat(locale_filename, &st) != 0)
3039 monitor_resave_missing_file(doc);
3040 /* doc may be closed now */
3041 ret = TRUE;
3043 else if (! use_gio_filemon && /* ignore check when using GIO */
3044 doc->priv->mtime > cur_time)
3046 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3047 /* Note: on Windows st.st_mtime can be newer than cur_time */
3049 else if (doc->priv->mtime < st.st_mtime)
3051 doc->priv->mtime = st.st_mtime;
3052 monitor_reload_file(doc);
3053 /* doc may be closed now */
3054 ret = TRUE;
3056 g_free(locale_filename);
3058 if (DOC_VALID(doc))
3059 { /* doc can get invalid when a document was closed */
3060 old_status = doc->priv->file_disk_status;
3061 doc->priv->file_disk_status = FILE_OK;
3062 if (old_status != doc->priv->file_disk_status)
3063 ui_update_tab_status(doc);
3065 return ret;
3069 /** Compares documents by their display names.
3070 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3071 * @note 'Display name' means the base name of the document's filename.
3073 * @param a @c GeanyDocument**.
3074 * @param b @c GeanyDocument**.
3075 * @warning The arguments take the address of each document pointer.
3076 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3078 * @since 0.21
3080 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3082 GeanyDocument *doc_a = *((GeanyDocument**) a);
3083 GeanyDocument *doc_b = *((GeanyDocument**) b);
3084 gchar *base_name_a, *base_name_b;
3085 gint result;
3087 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3088 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3090 result = strcmp(base_name_a, base_name_b);
3092 g_free(base_name_a);
3093 g_free(base_name_b);
3095 return result;
3099 /** Compares documents by their tab order.
3100 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3102 * @param a @c GeanyDocument**.
3103 * @param b @c GeanyDocument**.
3104 * @warning The arguments take the address of each document pointer.
3105 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3107 * @since 0.21 (GEANY_API_VERSION 209)
3109 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3111 GeanyDocument *doc_a = *((GeanyDocument**) a);
3112 GeanyDocument *doc_b = *((GeanyDocument**) b);
3113 gint notebook_position_doc_a;
3114 gint notebook_position_doc_b;
3116 notebook_position_doc_a = document_get_notebook_page(doc_a);
3117 notebook_position_doc_b = document_get_notebook_page(doc_b);
3119 if (notebook_position_doc_a < notebook_position_doc_b)
3120 return -1;
3121 if (notebook_position_doc_a > notebook_position_doc_b)
3122 return 1;
3123 /* equality */
3124 return 0;
3128 /** Compares documents by their tab order, in reverse order.
3129 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3131 * @param a @c GeanyDocument**.
3132 * @param b @c GeanyDocument**.
3133 * @warning The arguments take the address of each document pointer.
3134 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3136 * @since 0.21 (GEANY_API_VERSION 209)
3138 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3140 GeanyDocument *doc_a = *((GeanyDocument**) a);
3141 GeanyDocument *doc_b = *((GeanyDocument**) b);
3142 gint notebook_position_doc_a;
3143 gint notebook_position_doc_b;
3145 notebook_position_doc_a = document_get_notebook_page(doc_a);
3146 notebook_position_doc_b = document_get_notebook_page(doc_b);
3148 if (notebook_position_doc_a < notebook_position_doc_b)
3149 return 1;
3150 if (notebook_position_doc_a > notebook_position_doc_b)
3151 return -1;
3152 /* equality */
3153 return 0;
3157 void document_grab_focus(GeanyDocument *doc)
3159 g_return_if_fail(doc != NULL);
3161 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));