Update Scintilla keywords and highlighting when changing document tabs
[geany-mirror.git] / src / document.c
blobdc1bd5ef886a6d7682c5fa56b02a714a8675a622
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2011 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2011 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
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"
76 GeanyFilePrefs file_prefs;
78 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
79 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
80 * to a document over time, but it might no longer represent a notebook tab. To check this,
81 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
82 * file by then.
84 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
85 * although usually you would just use the foreach_document() macro.
87 * Never assume that the order of document pointers is the same as the order of notebook tabs.
88 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
89 GPtrArray *documents_array = NULL;
92 /* an undo action, also used for redo actions */
93 typedef struct
95 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
96 guint type; /* to identify the action */
97 gpointer *data; /* the old value (before the change), in case of a redo action
98 * it contains the new value */
99 } undo_action;
102 static void document_undo_clear(GeanyDocument *doc);
103 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
104 static gboolean update_tags_from_buffer(GeanyDocument *doc);
107 /* ignore the case of filenames and paths under WIN32, causes errors if not */
108 #ifdef G_OS_WIN32
109 #define filenamecmp(a, b) utils_str_casecmp((a), (b))
110 #else
111 #define filenamecmp(a, b) strcmp((a), (b))
112 #endif
115 * Finds a document whose @c real_path field matches the given filename.
117 * @param realname The filename to search, which should be identical to the
118 * string returned by @c tm_get_real_path().
120 * @return The matching document, or @c NULL.
121 * @note This is only really useful when passing a @c TMWorkObject::file_name.
122 * @see GeanyDocument::real_path.
123 * @see document_find_by_filename().
125 * @since 0.15
127 GeanyDocument* document_find_by_real_path(const gchar *realname)
129 guint i;
131 if (! realname)
132 return NULL; /* file doesn't exist on disk */
134 for (i = 0; i < documents_array->len; i++)
136 GeanyDocument *doc = documents[i];
138 if (! doc->is_valid || ! doc->real_path)
139 continue;
141 if (filenamecmp(realname, doc->real_path) == 0)
143 return doc;
146 return NULL;
150 /* dereference symlinks, /../ junk in path and return locale encoding */
151 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
153 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
154 gchar *realname = tm_get_real_path(locale_name);
156 g_free(locale_name);
157 return realname;
162 * Finds a document with the given filename.
163 * This matches either an exact GeanyDocument::file_name string, or variant
164 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
165 * match @c "/name").
167 * @param utf8_filename The filename to search (in UTF-8 encoding).
169 * @return The matching document, or @c NULL.
170 * @see document_find_by_real_path().
172 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
174 guint i;
175 GeanyDocument *doc;
176 gchar *realname;
178 g_return_val_if_fail(utf8_filename != NULL, NULL);
180 /* First search GeanyDocument::file_name, so we can find documents with a
181 * filename set but not saved on disk, like vcdiff produces */
182 for (i = 0; i < documents_array->len; i++)
184 doc = documents[i];
186 if (! doc->is_valid || doc->file_name == NULL)
187 continue;
189 if (filenamecmp(utf8_filename, doc->file_name) == 0)
191 return doc;
194 /* Now try matching based on the realpath(), which is unique per file on disk */
195 realname = get_real_path_from_utf8(utf8_filename);
196 doc = document_find_by_real_path(realname);
197 g_free(realname);
198 return doc;
202 /* returns the document which has sci, or NULL. */
203 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
205 guint i;
207 g_return_val_if_fail(sci != NULL, NULL);
209 for (i = 0; i < documents_array->len; i++)
211 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
212 return documents[i];
214 return NULL;
218 /** Gets the notebook page index for a document.
219 * @param doc The document.
220 * @return The index.
221 * @since 0.19 */
222 gint document_get_notebook_page(GeanyDocument *doc)
224 g_return_val_if_fail(doc != NULL, -1);
226 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
227 GTK_WIDGET(doc->editor->sci));
232 * Finds the document for the given notebook page @a page_num.
234 * @param page_num The notebook page number to search.
236 * @return The corresponding document for the given notebook page, or @c NULL.
238 GeanyDocument *document_get_from_page(guint page_num)
240 ScintillaObject *sci;
242 if (page_num >= documents_array->len)
243 return NULL;
245 sci = (ScintillaObject*)gtk_notebook_get_nth_page(
246 GTK_NOTEBOOK(main_widgets.notebook), page_num);
248 return document_find_by_sci(sci);
253 * Finds the current document.
255 * @return A pointer to the current document or @c NULL if there are no opened documents.
257 GeanyDocument *document_get_current(void)
259 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
261 if (cur_page == -1)
262 return NULL;
263 else
265 ScintillaObject *sci = (ScintillaObject*)
266 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
268 return document_find_by_sci(sci);
273 void document_init_doclist()
275 documents_array = g_ptr_array_new();
279 void document_finalize()
281 guint i;
283 for (i = 0; i < documents_array->len; i++)
284 g_free(documents[i]);
285 g_ptr_array_free(documents_array, TRUE);
290 * Returns the last part of the filename of the given GeanyDocument. The result is also
291 * truncated to a maximum of @a length characters in case the filename is very long.
293 * @param doc The document to use.
294 * @param length The length of the resulting string or -1 to use a default value.
296 * @return The ellipsized last part of the filename of @a doc, should be freed when no
297 * longer needed.
299 * @since 0.17
301 /* TODO make more use of this */
302 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
304 gchar *base_name, *short_name;
306 g_return_val_if_fail(doc != NULL, NULL);
308 if (length < 0)
309 length = 30;
311 base_name = g_path_get_basename(DOC_FILENAME(doc));
312 short_name = utils_str_middle_truncate(base_name, (guint)length);
314 g_free(base_name);
316 return short_name;
320 void document_update_tab_label(GeanyDocument *doc)
322 gchar *short_name;
323 GtkWidget *parent;
325 g_return_if_fail(doc != NULL);
327 short_name = document_get_basename_for_display(doc, -1);
329 /* we need to use the event box for the tooltip, labels don't get the necessary events */
330 parent = gtk_widget_get_parent(doc->priv->tab_label);
331 parent = gtk_widget_get_parent(parent);
333 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
335 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
337 g_free(short_name);
342 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
343 * according to the document's save state.
344 * This is called by Geany mostly when opening or saving files.
346 * @param doc The document to use.
347 * @param changed Whether the document state should indicate changes have been made.
349 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
351 g_return_if_fail(doc != NULL);
353 doc->changed = changed;
355 if (! main_status.quitting)
357 ui_update_tab_status(doc);
358 ui_save_buttons_toggle(changed);
359 ui_set_window_title(doc);
360 ui_update_statusbar(doc, -1);
365 /* Sets is_valid to FALSE and initializes some members to NULL, to mark it uninitialized.
366 * The flag is_valid is set to TRUE in document_create(). */
367 static void init_doc_struct(GeanyDocument *new_doc)
369 GeanyDocumentPrivate *priv;
371 memset(new_doc, 0, sizeof(GeanyDocument));
373 new_doc->is_valid = FALSE;
374 new_doc->has_tags = FALSE;
375 new_doc->readonly = FALSE;
376 new_doc->file_name = NULL;
377 new_doc->file_type = NULL;
378 new_doc->tm_file = NULL;
379 new_doc->encoding = NULL;
380 new_doc->has_bom = FALSE;
381 new_doc->editor = NULL;
382 new_doc->changed = FALSE;
383 new_doc->real_path = NULL;
385 new_doc->priv = g_new0(GeanyDocumentPrivate, 1);
386 priv = new_doc->priv;
387 priv->tag_store = NULL;
388 priv->tag_tree = NULL;
389 priv->saved_encoding.encoding = NULL;
390 priv->saved_encoding.has_bom = FALSE;
391 priv->undo_actions = NULL;
392 priv->redo_actions = NULL;
393 priv->line_count = 0;
394 priv->tag_list_update_source = 0;
395 #ifndef USE_GIO_FILEMON
396 priv->last_check = time(NULL);
397 #endif
401 /* returns the next free place in the document list,
402 * or -1 if the documents_array is full */
403 static gint document_get_new_idx(void)
405 guint i;
407 for (i = 0; i < documents_array->len; i++)
409 if (documents[i]->editor == NULL)
411 return (gint) i;
414 return -1;
418 static void queue_colourise(GeanyDocument *doc)
420 /* Colourise the editor before it is next drawn */
421 doc->priv->colourise_needed = TRUE;
423 /* If the editor doesn't need drawing (e.g. after saving the current
424 * document), we need to force a redraw, so the expose event is triggered.
425 * This ensures we don't start colourising before all documents are opened/saved,
426 * only once the editor is drawn. */
427 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
431 #ifdef USE_GIO_FILEMON
432 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
433 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
434 GeanyDocument *doc)
436 g_return_if_fail(doc != NULL);
438 if (file_prefs.disk_check_timeout == 0)
439 return;
441 geany_debug("%s: event: %d previous file status: %d",
442 G_STRFUNC, event, doc->priv->file_disk_status);
443 switch (event)
445 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
447 if (doc->priv->file_disk_status == FILE_IGNORE)
448 doc->priv->file_disk_status = FILE_OK;
449 else
450 doc->priv->file_disk_status = FILE_CHANGED;
451 g_message("%s: FILE_CHANGED", G_STRFUNC);
452 break;
454 case G_FILE_MONITOR_EVENT_DELETED:
456 doc->priv->file_disk_status = FILE_CHANGED;
457 g_message("%s: FILE_MISSING", G_STRFUNC);
458 break;
460 default:
461 break;
463 if (doc->priv->file_disk_status != FILE_OK)
465 ui_update_tab_status(doc);
468 #endif
471 static void document_stop_file_monitoring(GeanyDocument *doc)
473 g_return_if_fail(doc != NULL);
475 if (doc->priv->monitor != NULL)
477 g_object_unref(doc->priv->monitor);
478 doc->priv->monitor = NULL;
483 static void monitor_file_setup(GeanyDocument *doc)
485 g_return_if_fail(doc != NULL);
486 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
487 * doesn't work at all for remote files and legacy polling is too slow. */
488 if (! doc->priv->is_remote)
490 #ifdef USE_GIO_FILEMON
491 gchar *locale_filename;
493 /* stop any previous monitoring */
494 document_stop_file_monitoring(doc);
496 locale_filename = utils_get_locale_from_utf8(doc->file_name);
497 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
499 /* get a file monitor and connect to the 'changed' signal */
500 GFile *file = g_file_new_for_path(locale_filename);
501 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
502 g_signal_connect(doc->priv->monitor, "changed",
503 G_CALLBACK(monitor_file_changed_cb), doc);
505 /* we set the rate limit according to the GUI pref but it's most probably not used */
506 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
508 g_object_unref(file);
510 g_free(locale_filename);
511 #endif
513 doc->priv->file_disk_status = FILE_OK;
517 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
519 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
520 if (DOC_VALID(doc))
522 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
523 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
525 if (source_widget == NULL)
526 source_widget = doc->priv->tag_tree;
528 if (focusw == source_widget)
529 gtk_widget_grab_focus(sci);
534 static gboolean on_idle_focus(gpointer doc)
536 document_try_focus(doc, NULL);
537 return FALSE;
541 static gboolean remove_page(guint page_num);
543 /* Creates a new document and editor, adding a tab in the notebook.
544 * @return The created document */
545 static GeanyDocument *document_create(const gchar *utf8_filename)
547 GeanyDocument *doc;
548 gint new_idx;
549 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
551 if (cur_pages == 1)
553 GeanyDocument *cur = document_get_current();
554 /* remove the empty document first */
555 if (cur != NULL && cur->file_name == NULL && ! cur->changed)
556 /* prevent immediately opening another new doc with
557 * new_document_after_close pref */
558 remove_page(0);
561 new_idx = document_get_new_idx();
562 if (new_idx == -1) /* expand the array, no free places */
564 GeanyDocument *new_doc = g_new0(GeanyDocument, 1);
566 new_idx = documents_array->len;
567 g_ptr_array_add(documents_array, new_doc);
569 doc = documents[new_idx];
570 init_doc_struct(doc); /* initialize default document settings */
571 doc->index = new_idx;
573 doc->file_name = g_strdup(utf8_filename);
575 doc->editor = editor_create(doc);
577 sidebar_openfiles_add(doc); /* sets doc->iter */
579 notebook_new_tab(doc);
581 /* select document in sidebar */
583 GtkTreeSelection *sel;
585 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
586 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
589 ui_document_buttons_update();
591 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
592 return doc;
597 * Closes the given document.
599 * @param doc The document to remove.
601 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
603 * @since 0.15
605 gboolean document_close(GeanyDocument *doc)
607 g_return_val_if_fail(doc, FALSE);
609 return document_remove_page(document_get_notebook_page(doc));
613 /* Call document_remove_page() instead, this is only needed for document_create(). */
614 static gboolean remove_page(guint page_num)
616 GeanyDocument *doc = document_get_from_page(page_num);
618 if (G_UNLIKELY(doc == NULL))
620 g_warning("%s: page_num: %d", G_STRFUNC, page_num);
621 return FALSE;
624 if (doc->changed && ! dialogs_show_unsaved_file(doc))
626 return FALSE;
629 /* tell any plugins that the document is about to be closed */
630 g_signal_emit_by_name(geany_object, "document-close", doc);
632 /* Checking real_path makes it likely the file exists on disk */
633 if (! main_status.closing_all && doc->real_path != NULL)
634 ui_add_recent_file(doc->file_name);
636 doc->is_valid = FALSE;
638 if (! main_status.quitting)
640 notebook_remove_page(page_num);
641 sidebar_remove_document(doc);
642 navqueue_remove_file(doc->file_name);
643 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
645 g_free(doc->encoding);
646 g_free(doc->priv->saved_encoding.encoding);
647 g_free(doc->file_name);
648 g_free(doc->real_path);
649 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
651 editor_destroy(doc->editor);
652 doc->editor = NULL;
654 document_stop_file_monitoring(doc);
656 doc->file_name = NULL;
657 doc->real_path = NULL;
658 doc->file_type = NULL;
659 doc->encoding = NULL;
660 doc->has_bom = FALSE;
661 doc->tm_file = NULL;
662 document_undo_clear(doc);
663 g_free(doc->priv);
665 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
667 sidebar_update_tag_list(NULL, FALSE);
668 /*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
669 ui_set_window_title(NULL);
670 ui_save_buttons_toggle(FALSE);
671 ui_update_popup_reundo_items(NULL);
672 ui_document_buttons_update();
673 build_menu_update(NULL);
675 return TRUE;
680 * Removes the given notebook tab at @a page_num and clears all related information
681 * in the document list.
683 * @param page_num The notebook page number to remove.
685 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
687 gboolean document_remove_page(guint page_num)
689 gboolean done = remove_page(page_num);
691 if (done && ui_prefs.new_document_after_close)
692 document_new_file_if_non_open();
694 return done;
698 /* used to keep a record of the unchanged document state encoding */
699 static void store_saved_encoding(GeanyDocument *doc)
701 g_free(doc->priv->saved_encoding.encoding);
702 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
703 doc->priv->saved_encoding.has_bom = doc->has_bom;
707 /* Opens a new empty document only if there are no other documents open */
708 GeanyDocument *document_new_file_if_non_open(void)
710 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
711 return document_new_file(NULL, NULL, NULL);
713 return NULL;
718 * Creates a new document.
719 * Line endings in @a text will be converted to the default setting.
720 * Afterwards, the @c "document-new" signal is emitted for plugins.
722 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
723 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
724 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
726 * @return The new document.
728 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
730 GeanyDocument *doc;
732 if (utf8_filename && g_path_is_absolute(utf8_filename))
734 gchar *tmp;
735 tmp = utils_strdupa(utf8_filename); /* work around const */
736 utils_tidy_path(tmp);
737 utf8_filename = tmp;
739 doc = document_create(utf8_filename);
741 g_assert(doc != NULL);
743 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
744 if (text)
746 GString *template = g_string_new(text);
747 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
749 sci_set_text(doc->editor->sci, template->str);
750 g_string_free(template, TRUE);
752 else
753 sci_clear_all(doc->editor->sci);
755 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
757 sci_set_undo_collection(doc->editor->sci, TRUE);
758 sci_empty_undo_buffer(doc->editor->sci);
760 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
761 /* store the opened encoding for undo/redo */
762 store_saved_encoding(doc);
764 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
765 ft = filetypes_detect_from_document(doc);
767 document_set_filetype(doc, ft); /* also clears taglist */
769 ui_set_window_title(doc);
770 build_menu_update(doc);
771 document_update_tag_list(doc, FALSE);
772 document_set_text_changed(doc, FALSE);
773 ui_document_show_hide(doc); /* update the document menu */
775 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
776 /* bring it in front, jump to the start and grab the focus */
777 editor_goto_pos(doc->editor, 0, FALSE);
778 document_try_focus(doc, NULL);
780 #ifdef USE_GIO_FILEMON
781 monitor_file_setup(doc);
782 #else
783 doc->priv->mtime = time(NULL);
784 #endif
786 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
787 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
789 g_signal_emit_by_name(geany_object, "document-new", doc);
791 msgwin_status_add(_("New file \"%s\" opened."),
792 DOC_FILENAME(doc));
794 return doc;
799 * Opens a document specified by @a locale_filename.
800 * Afterwards, the @c "document-open" signal is emitted for plugins.
802 * @param locale_filename The filename of the document to load, in locale encoding.
803 * @param readonly Whether to open the document in read-only mode.
804 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
805 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
807 * @return The document opened or @c NULL.
809 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
810 GeanyFiletype *ft, const gchar *forced_enc)
812 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
816 typedef struct
818 gchar *data; /* null-terminated file data */
819 gsize len; /* string length of data */
820 gchar *enc;
821 gboolean bom;
822 time_t mtime; /* modification time, read by stat::st_mtime */
823 gboolean readonly;
824 } FileData;
827 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
828 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
829 FileData *filedata, const gchar *forced_enc)
831 GError *err = NULL;
832 struct stat st;
834 filedata->data = NULL;
835 filedata->len = 0;
836 filedata->enc = NULL;
837 filedata->bom = FALSE;
838 filedata->readonly = FALSE;
840 if (g_stat(locale_filename, &st) != 0)
842 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
843 display_filename, g_strerror(errno));
844 return FALSE;
847 filedata->mtime = st.st_mtime;
849 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
851 ui_set_statusbar(TRUE, "%s", err->message);
852 g_error_free(err);
853 return FALSE;
856 filedata->len = (gsize) st.st_size;
857 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
858 &filedata->enc, &filedata->bom, &filedata->readonly))
860 if (forced_enc)
862 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
863 display_filename, forced_enc);
865 else
867 ui_set_statusbar(TRUE,
868 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
869 display_filename);
871 g_free(filedata->data);
872 return FALSE;
875 if (filedata->readonly)
877 const gchar *warn_msg = _(
878 "The file \"%s\" could not be opened properly and has been truncated. " \
879 "This can occur if the file contains a NULL byte. " \
880 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
882 if (main_status.main_window_realized)
883 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
885 ui_set_statusbar(TRUE, warn_msg, display_filename);
888 return TRUE;
892 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
893 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
894 * if cl_options.goto_column is set.
896 * returns the new position which may have changed */
897 static gint set_cursor_position(GeanyEditor *editor, gint pos)
899 if (cl_options.goto_line >= 0)
900 { /* goto line which was specified on command line and then undefine the line */
901 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
902 editor->scroll_percent = 0.5F;
903 cl_options.goto_line = -1;
905 else if (pos > 0)
907 sci_set_current_position(editor->sci, pos, FALSE);
908 editor->scroll_percent = 0.5F;
911 if (cl_options.goto_column >= 0)
912 { /* goto column which was specified on command line and then undefine the column */
914 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
915 sci_set_current_position(editor->sci, new_pos, FALSE);
916 editor->scroll_percent = 0.5F;
917 cl_options.goto_column = -1;
918 return new_pos;
920 return sci_get_current_position(editor->sci);
924 /* Count lines that start with some hard tabs then a soft tab. */
925 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
927 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
928 ScintillaObject *sci = editor->sci;
929 gsize count = 0;
930 struct Sci_TextToFind ttf;
931 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
932 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
934 g_free(soft_tab);
936 ttf.chrg.cpMin = 0;
937 ttf.chrg.cpMax = sci_get_length(sci);
938 ttf.lpstrText = regex;
939 while (1)
941 gint pos;
943 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
944 if (pos == -1)
945 break; /* no more matches */
946 count++;
947 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
949 g_free(regex);
950 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
951 return count > sci_get_line_count(sci) * 0.02;
955 /* Detect the indent type based on counting the leading indent characters for each line.
956 * Returns whether detection succeeded, and the detected type in *type_ upon success */
957 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
959 GeanyEditor *editor = doc->editor;
960 ScintillaObject *sci = editor->sci;
961 gint line, line_count;
962 gsize tabs = 0, spaces = 0;
964 if (detect_tabs_and_spaces(editor))
966 *type_ = GEANY_INDENT_TYPE_BOTH;
967 return TRUE;
970 line_count = sci_get_line_count(sci);
971 for (line = 0; line < line_count; line++)
973 gint pos = sci_get_position_from_line(sci, line);
974 gchar c;
976 /* most code will have indent total <= 24, otherwise it's more likely to be
977 * alignment than indentation */
978 if (sci_get_line_indentation(sci, line) > 24)
979 continue;
981 c = sci_get_char_at(sci, pos);
982 if (c == '\t')
983 tabs++;
984 /* check for at least 2 spaces */
985 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
986 spaces++;
988 if (spaces == 0 && tabs == 0)
989 return FALSE;
991 /* the factors may need to be tweaked */
992 if (spaces > tabs * 4)
993 *type_ = GEANY_INDENT_TYPE_SPACES;
994 else if (tabs > spaces * 4)
995 *type_ = GEANY_INDENT_TYPE_TABS;
996 else
997 *type_ = GEANY_INDENT_TYPE_BOTH;
999 return TRUE;
1003 /* Detect the indent width based on counting the leading indent characters for each line.
1004 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1005 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1007 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1008 ScintillaObject *sci = editor->sci;
1009 gint line, line_count;
1010 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1011 gint count, width, i;
1013 /* can't easily detect the supposed width of a tab, guess the default is OK */
1014 if (type == GEANY_INDENT_TYPE_TABS)
1015 return FALSE;
1017 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1018 sci_set_tab_width(sci, 8);
1020 line_count = sci_get_line_count(sci);
1021 for (line = 0; line < line_count; line++)
1023 width = sci_get_line_indentation(sci, line);
1024 /* most code will have indent total <= 24, otherwise it's more likely to be
1025 * alignment than indentation */
1026 if (width > 24)
1027 continue;
1028 /* < 2 is no indentation */
1029 if (width < 2)
1030 continue;
1032 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1034 if ((width % (i + 2)) == 0)
1035 widths[i]++;
1038 count = 0;
1039 width = iprefs->width;
1040 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1042 /* give large indents higher weight not to be fooled by spurious indents */
1043 if (widths[i] >= count * 1.5)
1045 width = i + 2;
1046 count = widths[i];
1050 if (count == 0)
1051 return FALSE;
1053 *width_ = width;
1054 return TRUE;
1058 /* same as detect_indent_width() but uses editor's indent type */
1059 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1061 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1065 void document_apply_indent_settings(GeanyDocument *doc)
1067 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1068 GeanyIndentType type = iprefs->type;
1069 gint width = iprefs->width;
1071 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1073 if (type != iprefs->type)
1075 const gchar *name = NULL;
1077 switch (type)
1079 case GEANY_INDENT_TYPE_SPACES:
1080 name = _("Spaces");
1081 break;
1082 case GEANY_INDENT_TYPE_TABS:
1083 name = _("Tabs");
1084 break;
1085 case GEANY_INDENT_TYPE_BOTH:
1086 name = _("Tabs and Spaces");
1087 break;
1089 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1090 * and Spaces), the second one is the filename */
1091 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1092 DOC_FILENAME(doc));
1095 else if (doc->file_type->indent_type > -1)
1096 type = doc->file_type->indent_type;
1098 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1100 if (width != iprefs->width)
1102 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1103 DOC_FILENAME(doc));
1106 else if (doc->file_type->indent_width > -1)
1107 width = doc->file_type->indent_width;
1109 editor_set_indent(doc->editor, type, width);
1113 void document_show_tab(GeanyDocument *doc)
1115 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1116 document_get_notebook_page(doc));
1120 /* To open a new file, set doc to NULL; filename should be locale encoded.
1121 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1122 * pos is the cursor position, which can be overridden by --line and --column.
1123 * forced_enc can be NULL to detect the file encoding.
1124 * Returns: doc of the opened file or NULL if an error occurred. */
1125 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1126 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1128 gint editor_mode;
1129 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1130 gchar *utf8_filename = NULL;
1131 gchar *display_filename = NULL;
1132 gchar *locale_filename = NULL;
1133 GeanyFiletype *use_ft;
1134 FileData filedata;
1136 if (reload)
1138 utf8_filename = g_strdup(doc->file_name);
1139 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1141 else
1143 /* filename must not be NULL when opening a file */
1144 if (filename == NULL)
1146 ui_set_statusbar(FALSE, _("Invalid filename"));
1147 return NULL;
1150 #ifdef G_OS_WIN32
1151 /* if filename is a shortcut, try to resolve it */
1152 locale_filename = win32_get_shortcut_target(filename);
1153 #else
1154 locale_filename = g_strdup(filename);
1155 #endif
1156 /* remove relative junk */
1157 utils_tidy_path(locale_filename);
1159 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1160 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1162 /* if file is already open, switch to it and go */
1163 doc = document_find_by_filename(utf8_filename);
1164 if (doc != NULL)
1166 ui_add_recent_file(utf8_filename); /* either add or reorder recent item */
1167 /* show the doc before reload dialog */
1168 document_show_tab(doc);
1169 document_check_disk_status(doc, TRUE); /* force a file changed check */
1172 if (reload || doc == NULL)
1173 { /* doc possibly changed */
1174 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1176 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1178 g_free(display_filename);
1179 g_free(utf8_filename);
1180 g_free(locale_filename);
1181 return NULL;
1184 if (! reload)
1186 doc = document_create(utf8_filename);
1187 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1189 /* file exists on disk, set real_path */
1190 setptr(doc->real_path, tm_get_real_path(locale_filename));
1192 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1193 monitor_file_setup(doc);
1196 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1197 sci_empty_undo_buffer(doc->editor->sci);
1199 /* add the text to the ScintillaObject */
1200 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1201 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1202 queue_colourise(doc); /* Ensure the document gets colourised. */
1204 /* detect & set line endings */
1205 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1206 sci_set_eol_mode(doc->editor->sci, editor_mode);
1207 g_free(filedata.data);
1209 sci_set_undo_collection(doc->editor->sci, TRUE);
1211 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1212 g_free(doc->encoding); /* if reloading, free old encoding */
1213 doc->encoding = filedata.enc;
1214 doc->has_bom = filedata.bom;
1215 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1217 doc->readonly = readonly || filedata.readonly;
1218 sci_set_readonly(doc->editor->sci, doc->readonly);
1220 /* update line number margin width */
1221 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1222 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1224 if (! reload)
1227 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1228 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1229 doc->editor);
1231 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1233 else
1234 { /* reloading */
1235 document_undo_clear(doc);
1237 use_ft = ft;
1239 /* update taglist, typedef keywords and build menu if necessary */
1240 document_set_filetype(doc, use_ft);
1242 /* set indentation settings after setting the filetype */
1243 if (reload)
1244 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1245 else
1246 document_apply_indent_settings(doc);
1248 document_set_text_changed(doc, FALSE); /* also updates tab state */
1249 ui_document_show_hide(doc); /* update the document menu */
1251 /* finally add current file to recent files menu, but not the files from the last session */
1252 if (! main_status.opening_session_files)
1253 ui_add_recent_file(utf8_filename);
1255 if (reload)
1257 g_signal_emit_by_name(geany_object, "document-reload", doc);
1258 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1260 else
1262 g_signal_emit_by_name(geany_object, "document-open", doc);
1263 /* For translators: this is the status window message for opening a file. %d is the number
1264 * of the newly opened file, %s indicates whether the file is opened read-only
1265 * (it is replaced with the string ", read-only"). */
1266 msgwin_status_add(_("File %s opened(%d%s)."),
1267 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1268 (readonly) ? _(", read-only") : "");
1272 g_free(display_filename);
1273 g_free(utf8_filename);
1274 g_free(locale_filename);
1276 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1277 pos = set_cursor_position(doc->editor, pos);
1278 /* now bring the file in front */
1279 editor_goto_pos(doc->editor, pos, FALSE);
1281 /* finally, let the editor widget grab the focus so you can start coding
1282 * right away */
1283 g_idle_add(on_idle_focus, doc);
1284 return doc;
1288 /* Takes a new line separated list of filename URIs and opens each file.
1289 * length is the length of the string */
1290 void document_open_file_list(const gchar *data, gsize length)
1292 guint i;
1293 gchar *filename;
1294 gchar **list;
1296 g_return_if_fail(data != NULL);
1298 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1300 for (i = 0; list[i] != NULL; i++)
1302 filename = g_filename_from_uri(list[i], NULL, NULL);
1303 if (G_UNLIKELY(filename == NULL))
1304 continue;
1305 document_open_file(filename, FALSE, NULL, NULL);
1306 g_free(filename);
1309 g_strfreev(list);
1314 * Opens each file in the list @a filenames.
1315 * Internally, document_open_file() is called for every list item.
1317 * @param filenames A list of filenames to load, in locale encoding.
1318 * @param readonly Whether to open the document in read-only mode.
1319 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1320 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1322 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1323 const gchar *forced_enc)
1325 const GSList *item;
1327 for (item = filenames; item != NULL; item = g_slist_next(item))
1329 document_open_file(item->data, readonly, ft, forced_enc);
1335 * Reloads the document with the specified file encoding
1336 * @a forced_enc or @c NULL to auto-detect the file encoding.
1338 * @param doc The document to reload.
1339 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1341 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1343 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1345 gint pos = 0;
1346 GeanyDocument *new_doc;
1348 g_return_val_if_fail(doc != NULL, FALSE);
1350 /* try to set the cursor to the position before reloading */
1351 pos = sci_get_current_position(doc->editor->sci);
1352 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1354 return (new_doc != NULL);
1358 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1360 #ifndef USE_GIO_FILEMON
1361 struct stat st;
1363 g_return_val_if_fail(doc != NULL, FALSE);
1365 /* stat the file to get the timestamp, otherwise on Windows the actual
1366 * timestamp can be ahead of time(NULL) */
1367 if (g_stat(locale_filename, &st) != 0)
1369 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1370 g_strerror(errno));
1371 return FALSE;
1374 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1375 #endif
1376 return TRUE;
1380 /* Sets line and column to the given position byte_pos in the document.
1381 * byte_pos is the position counted in bytes, not characters */
1382 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1384 gint i;
1385 gint line_start;
1387 /* for some reason we can use byte count instead of character count here */
1388 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1389 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1390 /* get the column in the line */
1391 *column = byte_pos - line_start;
1393 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1394 * skip one byte(i++) and decrease the column number which is based on byte count */
1395 for (i = line_start; i < (line_start + *column); i++)
1397 if (sci_get_char_at(doc->editor->sci, i) < 0)
1399 (*column)--;
1400 i++;
1406 static void replace_header_filename(GeanyDocument *doc)
1408 gchar *filebase;
1409 gchar *filename;
1410 struct Sci_TextToFind ttf;
1412 g_return_if_fail(doc != NULL);
1413 g_return_if_fail(doc->file_type != NULL);
1415 if (doc->file_type->extension)
1416 filebase = g_strconcat("\\<", GEANY_STRING_UNTITLED, "\\.\\w+", NULL);
1417 else
1418 filebase = g_strdup(GEANY_STRING_UNTITLED);
1420 filename = g_path_get_basename(doc->file_name);
1422 /* only search the first 3 lines */
1423 ttf.chrg.cpMin = 0;
1424 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 3);
1425 ttf.lpstrText = filebase;
1427 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf) != -1)
1429 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1430 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1431 sci_replace_target(doc->editor->sci, filename, FALSE);
1433 g_free(filebase);
1434 g_free(filename);
1439 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1440 * you still have to call @ref document_save_file_as() to change the @a doc object.
1441 * It also stops monitoring for file changes to prevent receiving too many file change events
1442 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1444 * @param doc The current document which should be renamed.
1445 * @param new_filename The new filename in UTF-8 encoding.
1447 * @since 0.16
1449 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1451 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1452 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1453 gint result;
1455 /* stop file monitoring to avoid getting events for deleting/creating files,
1456 * it's re-setup in document_save_file_as() */
1457 document_stop_file_monitoring(doc);
1459 result = g_rename(old_locale_filename, new_locale_filename);
1460 if (result != 0)
1462 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1463 _("Error renaming file."), g_strerror(errno));
1465 g_free(old_locale_filename);
1466 g_free(new_locale_filename);
1470 /* Return TRUE if the document doesn't have a full filename set.
1471 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1472 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1473 * new files. */
1474 gboolean document_need_save_as(GeanyDocument *doc)
1476 g_return_val_if_fail(doc != NULL, FALSE);
1478 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1483 * Saves the document, detecting the filetype.
1485 * @param doc The document for the file to save.
1486 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1487 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1489 * @see document_save_file().
1491 * @since 0.16
1493 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1495 gboolean ret;
1497 g_return_val_if_fail(doc != NULL, FALSE);
1499 if (utf8_fname != NULL)
1500 setptr(doc->file_name, g_strdup(utf8_fname));
1502 /* reset real path, it's retrieved again in document_save() */
1503 setptr(doc->real_path, NULL);
1505 /* detect filetype */
1506 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1508 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1510 document_set_filetype(doc, ft);
1511 if (document_get_current() == doc)
1513 ignore_callback = TRUE;
1514 filetypes_select_radio_item(doc->file_type);
1515 ignore_callback = FALSE;
1518 replace_header_filename(doc);
1520 ret = document_save_file(doc, TRUE);
1522 /* file monitoring support, add file monitoring after the file has been saved
1523 * to ignore any earlier events */
1524 monitor_file_setup(doc);
1525 doc->priv->file_disk_status = FILE_IGNORE;
1527 if (ret)
1528 ui_add_recent_file(doc->file_name);
1529 return ret;
1533 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1535 GError *conv_error = NULL;
1536 gchar* conv_file_contents = NULL;
1537 gsize bytes_read;
1538 gsize conv_len;
1540 g_return_val_if_fail(data != NULL || *data == NULL, FALSE);
1541 g_return_val_if_fail(len != NULL, FALSE);
1543 /* try to convert it from UTF-8 to original encoding */
1544 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1545 &bytes_read, &conv_len, &conv_error);
1547 if (conv_error != NULL)
1549 gchar *text = g_strdup_printf(
1550 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1551 doc->encoding);
1552 gchar *error_text;
1554 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1556 gchar *context = NULL;
1557 gint line, column;
1558 gint context_len;
1559 gunichar unic;
1560 /* don't read over the doc length */
1561 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1562 context = g_malloc(7); /* read 6 bytes from Sci + '\0' */
1563 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1565 /* take only one valid Unicode character from the context and discard the leftover */
1566 unic = g_utf8_get_char_validated(context, -1);
1567 context_len = g_unichar_to_utf8(unic, context);
1568 context[context_len] = '\0';
1569 get_line_column_from_pos(doc, bytes_read, &line, &column);
1571 error_text = g_strdup_printf(
1572 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1573 conv_error->message, context, line + 1, column);
1574 g_free(context);
1576 else
1577 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1579 geany_debug("encoding error: %s", conv_error->message);
1580 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1581 g_error_free(conv_error);
1582 g_free(text);
1583 g_free(error_text);
1584 return FALSE;
1586 else
1588 g_free(*data);
1589 *data = conv_file_contents;
1590 *len = conv_len;
1592 return TRUE;
1596 static gchar *write_data_to_disk(const gchar *locale_filename,
1597 const gchar *data, gint len)
1599 GError *error = NULL;
1601 if (file_prefs.use_safe_file_saving)
1603 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1604 * This is the only option that handles disk space exhaustion. */
1605 if (g_file_set_contents(locale_filename, data, len, &error))
1606 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1608 else if (file_prefs.use_gio_unsafe_file_saving)
1610 GFile *fp;
1612 /* Use GIO API to save file (GVFS-safe)
1613 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1614 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1615 fp = g_file_new_for_path(locale_filename);
1616 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1617 G_FILE_CREATE_NONE, NULL, NULL, &error);
1618 g_object_unref(fp);
1620 else
1622 FILE *fp;
1623 int save_errno;
1624 gchar *display_name = g_filename_display_name(locale_filename);
1626 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1627 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1628 errno = 0;
1629 fp = g_fopen(locale_filename, "wb");
1630 if (fp == NULL)
1632 save_errno = errno;
1634 g_set_error(&error,
1635 G_FILE_ERROR,
1636 g_file_error_from_errno(save_errno),
1637 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1638 display_name,
1639 g_strerror(save_errno));
1641 else
1643 gint bytes_written;
1645 errno = 0;
1646 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1648 if (len != bytes_written)
1650 save_errno = errno;
1652 g_set_error(&error,
1653 G_FILE_ERROR,
1654 g_file_error_from_errno(save_errno),
1655 _("Failed to write file '%s': fwrite() failed: %s"),
1656 display_name,
1657 g_strerror(save_errno));
1660 errno = 0;
1661 /* preserve the fwrite() error if any */
1662 if (fclose(fp) != 0 && error == NULL)
1664 save_errno = errno;
1666 g_set_error(&error,
1667 G_FILE_ERROR,
1668 g_file_error_from_errno(save_errno),
1669 _("Failed to close file '%s': fclose() failed: %s"),
1670 display_name,
1671 g_strerror(save_errno));
1675 g_free(display_name);
1677 if (error != NULL)
1679 gchar *msg = g_strdup(error->message);
1680 g_error_free(error);
1681 /* geany will warn about file truncation for unsafe saving below */
1682 return msg;
1684 return NULL;
1688 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1689 const gchar *data, gint len)
1691 gchar *err;
1693 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1694 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1696 err = write_data_to_disk(locale_filename, data, len);
1697 if (err)
1698 return err;
1700 /* now the file is on disk, set real_path */
1701 if (doc->real_path == NULL)
1703 doc->real_path = tm_get_real_path(locale_filename);
1704 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1705 monitor_file_setup(doc);
1707 return NULL;
1712 * Saves the document. Saving may include replacing tabs by spaces,
1713 * stripping trailing spaces and adding a final new line at the end of the file, depending
1714 * on user preferences. Then the @c "document-before-save" signal is emitted,
1715 * allowing plugins to modify the document before it is saved, and data is
1716 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1717 * Afterwards, the @c "document-save" signal is emitted for plugins.
1719 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1721 * @note You should ensure @c doc->file_name is not @c NULL before calling this; otherwise
1722 * call dialogs_show_save_as().
1724 * @param doc The document to save.
1725 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1727 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1729 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1731 gchar *errmsg;
1732 gchar *data;
1733 gsize len;
1734 gchar *locale_filename;
1736 g_return_val_if_fail(doc != NULL, FALSE);
1738 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1739 if (! force && ! ui_prefs.allow_always_save && (! doc->changed || doc->readonly))
1740 return FALSE;
1742 if (G_UNLIKELY(doc->file_name == NULL))
1744 ui_set_statusbar(TRUE, _("Error saving file (%s)."), _("Invalid filename"));
1745 utils_beep();
1746 return FALSE;
1749 /* replaces tabs by spaces but only if the current file is not a Makefile */
1750 if (file_prefs.replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1751 editor_replace_tabs(doc->editor);
1752 /* strip trailing spaces */
1753 if (file_prefs.strip_trailing_spaces)
1754 editor_strip_trailing_spaces(doc->editor);
1755 /* ensure the file has a newline at the end */
1756 if (file_prefs.final_new_line)
1757 editor_ensure_final_newline(doc->editor);
1758 /* ensure newlines are consistent */
1759 if (file_prefs.ensure_convert_new_lines)
1760 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1762 /* notify plugins which may wish to modify the document before it's saved */
1763 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1765 len = sci_get_length(doc->editor->sci) + 1;
1766 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1767 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1768 * encoding, it will be converted to doc->encoding below and this conversion
1769 * also changes the BOM */
1770 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1771 data[0] = (gchar) 0xef;
1772 data[1] = (gchar) 0xbb;
1773 data[2] = (gchar) 0xbf;
1774 sci_get_text(doc->editor->sci, len, data + 3);
1775 len += 3;
1777 else
1779 data = (gchar*) g_malloc(len);
1780 sci_get_text(doc->editor->sci, len, data);
1783 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1784 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1785 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1787 if (! save_convert_to_encoding(doc, &data, &len))
1789 g_free(data);
1790 return FALSE;
1793 else
1795 len = strlen(data);
1798 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1800 /* ignore file changed notification when the file is written */
1801 doc->priv->file_disk_status = FILE_IGNORE;
1803 /* actually write the content of data to the file on disk */
1804 errmsg = save_doc(doc, locale_filename, data, len);
1805 g_free(data);
1807 if (errmsg != NULL)
1809 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1811 if (!file_prefs.use_safe_file_saving)
1813 setptr(errmsg,
1814 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1816 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1817 doc->priv->file_disk_status = FILE_OK;
1818 utils_beep();
1819 g_free(locale_filename);
1820 g_free(errmsg);
1821 return FALSE;
1824 /* store the opened encoding for undo/redo */
1825 store_saved_encoding(doc);
1827 /* ignore the following things if we are quitting */
1828 if (! main_status.quitting)
1830 sci_set_savepoint(doc->editor->sci);
1832 if (file_prefs.disk_check_timeout > 0)
1833 document_update_timestamp(doc, locale_filename);
1835 /* update filetype-related things */
1836 document_set_filetype(doc, doc->file_type);
1838 document_update_tab_label(doc);
1840 msgwin_status_add(_("File %s saved."), doc->file_name);
1841 ui_update_statusbar(doc, -1);
1842 #ifdef HAVE_VTE
1843 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1844 #endif
1846 g_free(locale_filename);
1848 g_signal_emit_by_name(geany_object, "document-save", doc);
1850 return TRUE;
1854 /* special search function, used from the find entry in the toolbar
1855 * return TRUE if text was found otherwise FALSE
1856 * return also TRUE if text is empty */
1857 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1858 gboolean backwards)
1860 gint start_pos, search_pos;
1861 struct Sci_TextToFind ttf;
1863 g_return_val_if_fail(text != NULL, FALSE);
1864 g_return_val_if_fail(doc != NULL, FALSE);
1865 if (! *text)
1866 return TRUE;
1868 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1869 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1871 /* search cursor to end or start */
1872 ttf.chrg.cpMin = start_pos;
1873 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1874 ttf.lpstrText = (gchar *)text;
1875 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1877 /* if no match, search start (or end) to cursor */
1878 if (search_pos == -1)
1880 if (backwards)
1882 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1883 ttf.chrg.cpMax = start_pos;
1885 else
1887 ttf.chrg.cpMin = 0;
1888 ttf.chrg.cpMax = start_pos + strlen(text);
1890 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1893 if (search_pos != -1)
1895 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1897 /* unfold maybe folded results */
1898 sci_ensure_line_is_visible(doc->editor->sci, line);
1900 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1901 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1903 if (! editor_line_in_view(doc->editor, line))
1904 { /* we need to force scrolling in case the cursor is outside of the current visible area
1905 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1906 * while searching */
1907 editor_scroll_to_line(doc->editor, -1, 0.3F);
1909 else
1910 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1911 return TRUE;
1913 else
1915 if (! inc)
1917 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1919 utils_beep();
1920 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1921 return FALSE;
1926 /* General search function, used from the find dialog.
1927 * Returns -1 on failure or the start position of the matching text.
1928 * Will skip past any selection, ignoring it.
1930 * @param text Text to find.
1931 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1933 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
1934 gint flags, gboolean search_backwards, gboolean scroll, GtkWidget *parent)
1936 gint selection_end, selection_start, search_pos;
1938 g_return_val_if_fail(doc != NULL && text != NULL, -1);
1939 if (! *text)
1940 return -1;
1942 /* Sci doesn't support searching backwards with a regex */
1943 if (flags & SCFIND_REGEXP)
1944 search_backwards = FALSE;
1946 if (!original_text)
1947 original_text = text;
1949 selection_start = sci_get_selection_start(doc->editor->sci);
1950 selection_end = sci_get_selection_end(doc->editor->sci);
1951 if ((selection_end - selection_start) > 0)
1952 { /* there's a selection so go to the end */
1953 if (search_backwards)
1954 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
1955 else
1956 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
1959 sci_set_search_anchor(doc->editor->sci);
1960 if (search_backwards)
1961 search_pos = sci_search_prev(doc->editor->sci, flags, text);
1962 else
1963 search_pos = search_find_next(doc->editor->sci, text, flags);
1965 if (search_pos != -1)
1967 /* unfold maybe folded results */
1968 sci_ensure_line_is_visible(doc->editor->sci,
1969 sci_get_line_from_position(doc->editor->sci, search_pos));
1970 if (scroll)
1971 doc->editor->scroll_percent = 0.3F;
1973 else
1975 gint sci_len = sci_get_length(doc->editor->sci);
1977 /* if we just searched the whole text, give up searching. */
1978 if ((selection_end == 0 && ! search_backwards) ||
1979 (selection_end == sci_len && search_backwards))
1981 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
1982 utils_beep();
1983 return -1;
1986 /* we searched only part of the document, so ask whether to wraparound. */
1987 if (search_prefs.suppress_dialogs ||
1988 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
1989 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
1991 gint ret;
1993 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
1994 ret = document_find_text(doc, text, original_text, flags, search_backwards, scroll, parent);
1995 if (ret == -1)
1996 { /* return to original cursor position if not found */
1997 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
1999 return ret;
2002 return search_pos;
2006 /* Replaces the selection if it matches, otherwise just finds the next match.
2007 * Returns: start of replaced text, or -1 if no replacement was made
2009 * @param find_text Text to find.
2010 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2012 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2013 const gchar *replace_text, gint flags, gboolean search_backwards)
2015 gint selection_end, selection_start, search_pos;
2017 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2019 if (! *find_text)
2020 return -1;
2022 /* Sci doesn't support searching backwards with a regex */
2023 if (flags & SCFIND_REGEXP)
2024 search_backwards = FALSE;
2026 if (!original_find_text)
2027 original_find_text = find_text;
2029 selection_start = sci_get_selection_start(doc->editor->sci);
2030 selection_end = sci_get_selection_end(doc->editor->sci);
2031 if (selection_end == selection_start)
2033 /* no selection so just find the next match */
2034 document_find_text(doc, find_text, original_find_text, flags, search_backwards, TRUE, NULL);
2035 return -1;
2037 /* there's a selection so go to the start before finding to search through it
2038 * this ensures there is a match */
2039 if (search_backwards)
2040 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2041 else
2042 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2044 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, TRUE, NULL);
2045 /* return if the original selected text did not match (at the start of the selection) */
2046 if (search_pos != selection_start)
2047 return -1;
2049 if (search_pos != -1)
2051 gint replace_len;
2052 /* search next/prev will select matching text, which we use to set the replace target */
2053 sci_target_from_selection(doc->editor->sci);
2054 replace_len = search_replace_target(doc->editor->sci, replace_text, flags & SCFIND_REGEXP);
2055 /* select the replacement - find text will skip past the selected text */
2056 sci_set_selection_start(doc->editor->sci, search_pos);
2057 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2059 else
2061 /* no match in the selection */
2062 utils_beep();
2064 return search_pos;
2068 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2069 const gchar *original_replace_text)
2071 gchar *filename;
2073 if (count == 0)
2075 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2076 return;
2079 filename = g_path_get_basename(DOC_FILENAME(doc));
2080 ui_set_statusbar(TRUE, ngettext(
2081 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2082 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2083 count), filename, count, original_find_text, original_replace_text);
2084 g_free(filename);
2088 /* Replace all text matches in a certain range within document.
2089 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2090 * or -1 if no text was found.
2091 * scroll_to_match is whether to scroll the last replacement in view (which also
2092 * clears the selection).
2093 * Returns: the number of replacements made. */
2094 static guint
2095 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2096 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2098 gint count = 0;
2099 struct Sci_TextToFind ttf;
2100 ScintillaObject *sci;
2102 if (new_range_end != NULL)
2103 *new_range_end = -1;
2105 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2107 if (! *find_text || doc->readonly)
2108 return 0;
2110 sci = doc->editor->sci;
2112 ttf.chrg.cpMin = start;
2113 ttf.chrg.cpMax = end;
2114 ttf.lpstrText = (gchar*)find_text;
2116 sci_start_undo_action(sci);
2117 count = search_replace_range(sci, &ttf, flags, replace_text);
2118 sci_end_undo_action(sci);
2120 if (count > 0)
2121 { /* scroll last match in view, will destroy the existing selection */
2122 if (scroll_to_match)
2123 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2125 if (new_range_end != NULL)
2126 *new_range_end = ttf.chrg.cpMax;
2128 return count;
2132 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2133 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2135 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2136 gint max_column = 0, count = 0;
2137 gboolean replaced = FALSE;
2139 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2141 if (! *find_text)
2142 return;
2144 selection_start = sci_get_selection_start(doc->editor->sci);
2145 selection_end = sci_get_selection_end(doc->editor->sci);
2146 /* do we have a selection? */
2147 if ((selection_end - selection_start) == 0)
2149 utils_beep();
2150 return;
2153 selection_mode = sci_get_selection_mode(doc->editor->sci);
2154 selected_lines = sci_get_lines_selected(doc->editor->sci);
2155 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2156 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2158 gint first_line, line;
2160 sci_start_undo_action(doc->editor->sci);
2162 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2163 /* Find the last line with chars selected (not EOL char) */
2164 last_line = sci_get_line_from_position(doc->editor->sci,
2165 selection_end - editor_get_eol_char_len(doc->editor));
2166 last_line = MAX(first_line, last_line);
2167 for (line = first_line; line < (first_line + selected_lines); line++)
2169 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2170 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2172 /* skip line if there is no selection */
2173 if (line_start != INVALID_POSITION)
2175 /* don't let document_replace_range() scroll to match to keep our selection */
2176 gint new_sel_end;
2178 count += document_replace_range(doc, find_text, replace_text, flags,
2179 line_start, line_end, FALSE, &new_sel_end);
2180 if (new_sel_end != -1)
2182 replaced = TRUE;
2183 /* this gets the greatest column within the selection after replacing */
2184 max_column = MAX(max_column,
2185 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2189 sci_end_undo_action(doc->editor->sci);
2191 else /* handle normal line selection */
2193 count += document_replace_range(doc, find_text, replace_text, flags,
2194 selection_start, selection_end, TRUE, &selection_end);
2195 if (selection_end != -1)
2196 replaced = TRUE;
2199 if (replaced)
2200 { /* update the selection for the new endpoint */
2202 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2204 /* now we can scroll to the selection and destroy it because we rebuild it later */
2205 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2207 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2208 * the highest column on the last line. The wrapped selection is completely different
2209 * from the original one, so skip the selection at all */
2210 /* TODO is there a better way to handle the wrapped selection? */
2211 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2212 { /* for keeping and adjusting the selection in multi line rectangle selection we
2213 * need the last line of the original selection and the greatest column number after
2214 * replacing and set the selection end to the last line at the greatest column */
2215 sci_set_selection_start(doc->editor->sci, selection_start);
2216 sci_set_selection_end(doc->editor->sci,
2217 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2218 sci_set_selection_mode(doc->editor->sci, selection_mode);
2221 else
2223 sci_set_selection_start(doc->editor->sci, selection_start);
2224 sci_set_selection_end(doc->editor->sci, selection_end);
2227 else /* no replacements */
2228 utils_beep();
2230 show_replace_summary(doc, count, original_find_text, original_replace_text);
2234 /* returns number of replacements made. */
2235 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2236 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2238 gint len, count;
2239 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2241 if (! *find_text)
2242 return FALSE;
2244 len = sci_get_length(doc->editor->sci);
2245 count = document_replace_range(
2246 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2248 show_replace_summary(doc, count, original_find_text, original_replace_text);
2249 return count;
2253 static gboolean update_tags_from_buffer(GeanyDocument *doc)
2255 gboolean result;
2256 #if 0
2257 /* old code */
2258 result = tm_source_file_update(doc->tm_file, TRUE, FALSE, TRUE);
2259 #else
2260 gsize len = sci_get_length(doc->editor->sci) + 1;
2261 gchar *text = g_malloc(len);
2263 /* we copy the whole text into memory instead using a direct char pointer from
2264 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2265 sci_get_text(doc->editor->sci, len, text);
2266 result = tm_source_file_buffer_update(doc->tm_file, (guchar*) text, len, TRUE);
2267 g_free(text);
2268 #endif
2269 return result;
2273 void document_update_tag_list(GeanyDocument *doc, gboolean update)
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 gboolean success = FALSE;
2280 /* if the filetype doesn't have a tag parser or it is a new file */
2281 if (doc == NULL || doc->file_type == NULL || app->tm_workspace == NULL ||
2282 ! filetype_has_tags(doc->file_type) || ! doc->file_name)
2284 /* set the default (empty) tag list */
2285 sidebar_update_tag_list(doc, FALSE);
2286 return;
2289 if (doc->tm_file == NULL)
2291 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2292 const gchar *name;
2294 /* lookup the name rather than using filetype name to support custom filetypes */
2295 name = tm_source_file_get_lang_name(doc->file_type->lang);
2296 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2297 g_free(locale_filename);
2299 if (doc->tm_file)
2301 if (!tm_workspace_add_object(doc->tm_file))
2303 tm_work_object_free(doc->tm_file);
2304 doc->tm_file = NULL;
2306 else
2308 if (update)
2309 update_tags_from_buffer(doc);
2310 success = TRUE;
2314 else
2316 success = update_tags_from_buffer(doc);
2317 if (G_UNLIKELY(! success))
2318 geany_debug("tag list updating failed");
2320 sidebar_update_tag_list(doc, success);
2324 static gboolean on_document_update_tag_list_idle(gpointer data)
2326 GeanyDocument *doc = data;
2328 if (! DOC_VALID(doc))
2329 return FALSE;
2331 if (! main_status.quitting)
2332 document_update_tag_list(doc, TRUE);
2334 doc->priv->tag_list_update_source = 0;
2335 return FALSE;
2339 void document_update_tag_list_in_idle(GeanyDocument *doc)
2341 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2342 return;
2344 if (doc->priv->tag_list_update_source != 0)
2345 g_source_remove(doc->priv->tag_list_update_source);
2346 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2347 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2351 /* Caches the list of project typenames, as a space separated GString.
2352 * Returns: TRUE if typenames have changed.
2353 * (*types) is set to the list of typenames, or NULL if there are none. */
2354 static gboolean get_project_typenames(const GString **types, gint lang)
2356 static GString *last_typenames = NULL;
2357 GString *s = NULL;
2359 if (app->tm_workspace)
2361 GPtrArray *tags_array = app->tm_workspace->work_object.tags_array;
2363 if (tags_array)
2365 s = symbols_find_tags_as_string(tags_array, TM_GLOBAL_TYPE_MASK, lang);
2369 if (s && last_typenames && g_string_equal(s, last_typenames))
2371 g_string_free(s, TRUE);
2372 *types = last_typenames;
2373 return FALSE; /* project typenames haven't changed */
2375 /* cache typename list for next time */
2376 if (last_typenames)
2377 g_string_free(last_typenames, TRUE);
2378 last_typenames = s;
2380 *types = s;
2381 if (s == NULL)
2382 return FALSE;
2383 return TRUE;
2387 /* If sci is NULL, update project typenames for all documents that support typenames,
2388 * if typenames have changed.
2389 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2390 * if necessary, and typename keywords are set for sci.
2391 * Returns: TRUE if any scintilla type keywords were updated. */
2392 static gboolean update_type_keywords(GeanyDocument *doc, gint lang)
2394 gboolean ret = FALSE;
2395 guint n;
2396 const GString *s;
2397 ScintillaObject *sci;
2399 g_return_val_if_fail(doc != NULL, FALSE);
2400 sci = doc->editor->sci;
2402 switch (doc->file_type->id)
2403 { /* continue working with the following languages, skip on all others */
2404 case GEANY_FILETYPES_C:
2405 case GEANY_FILETYPES_CPP:
2406 case GEANY_FILETYPES_CS:
2407 case GEANY_FILETYPES_D:
2408 case GEANY_FILETYPES_JAVA:
2409 case GEANY_FILETYPES_VALA:
2410 break;
2411 default:
2412 return FALSE;
2415 sci = doc->editor->sci;
2416 if (sci != NULL && editor_lexer_get_type_keyword_idx(sci_get_lexer(sci)) == -1)
2417 return FALSE;
2419 if (! get_project_typenames(&s, lang))
2420 { /* typenames have not changed */
2421 if (s != NULL && sci != NULL)
2423 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(sci));
2425 sci_set_keywords(sci, keyword_idx, s->str);
2426 queue_colourise(doc);
2428 return FALSE;
2430 g_return_val_if_fail(s != NULL, FALSE);
2432 for (n = 0; n < documents_array->len; n++)
2434 if (documents[n]->is_valid)
2436 ScintillaObject *wid = documents[n]->editor->sci;
2437 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(wid));
2439 if (keyword_idx > 0)
2441 sci_set_keywords(wid, keyword_idx, s->str);
2442 queue_colourise(documents[n]);
2443 ret = TRUE;
2447 return ret;
2452 * Updates the keywords in a document and re-colourizes it.
2454 * @param doc The document
2456 void document_update_highlighting(GeanyDocument *doc)
2458 const GString *s = NULL;
2459 ScintillaObject *sci;
2460 gint keyword_idx;
2462 g_return_if_fail(DOC_VALID(doc));
2463 g_return_if_fail(IS_SCINTILLA(doc->editor->sci));
2465 sci = doc->editor->sci;
2467 /* get possibly cached list of keywords for the current language.
2468 * we don't care whether the cached keywords have changed. */
2469 get_project_typenames(&s, doc->file_type->lang);
2471 if (s)
2473 keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(sci));
2475 if (keyword_idx > 0)
2477 sci_set_keywords(sci, keyword_idx, s->str);
2478 queue_colourise(doc);
2484 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2485 gboolean filetype_changed)
2487 g_return_if_fail(doc);
2488 if (type == NULL)
2489 type = filetypes[GEANY_FILETYPES_NONE];
2491 if (filetype_changed)
2493 doc->file_type = type;
2495 /* delete tm file object to force creation of a new one */
2496 if (doc->tm_file != NULL)
2498 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2499 doc->tm_file = NULL;
2501 /* load tags files before highlighting (some lexers highlight global typenames) */
2502 if (type->id != GEANY_FILETYPES_NONE)
2503 symbols_global_tags_loaded(type->id);
2505 highlighting_set_styles(doc->editor->sci, type);
2506 editor_set_indentation_guides(doc->editor);
2507 build_menu_update(doc);
2508 queue_colourise(doc);
2509 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2512 document_update_tag_list(doc, TRUE);
2514 /* Update session typename keywords. */
2515 update_type_keywords(doc, type->lang);
2519 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2520 * @param doc The document to use.
2521 * @param type The filetype. */
2522 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2524 gboolean ft_changed;
2525 GeanyFiletype *old_ft;
2527 g_return_if_fail(doc);
2528 if (type == NULL)
2529 type = filetypes[GEANY_FILETYPES_NONE];
2531 old_ft = doc->file_type;
2532 geany_debug("%s : %s (%s)",
2533 (doc->file_name != NULL) ? doc->file_name : "unknown",
2534 type->name,
2535 (doc->encoding != NULL) ? doc->encoding : "unknown");
2537 ft_changed = (doc->file_type != type); /* filetype has changed */
2538 document_load_config(doc, type, ft_changed);
2540 if (ft_changed)
2542 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2544 /* assume that if previous filetype was none and the settings are the default ones, this
2545 * is the first time the filetype is carefully set, so we should apply indent settings */
2546 if (old_ft && old_ft->id == GEANY_FILETYPES_NONE &&
2547 doc->editor->indent_type == iprefs->type &&
2548 doc->editor->indent_width == iprefs->width)
2550 document_apply_indent_settings(doc);
2551 ui_document_show_hide(doc);
2554 sidebar_openfiles_update(doc); /* to update the icon */
2555 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2560 void document_reload_config(GeanyDocument *doc)
2562 document_load_config(doc, doc->file_type, TRUE);
2567 * Sets the encoding of a document.
2568 * This function only set the encoding of the %document, it does not any conversions. The new
2569 * encoding is used when e.g. saving the file.
2571 * @param doc The document to use.
2572 * @param new_encoding The encoding to be set for the document.
2574 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2576 if (doc == NULL || new_encoding == NULL ||
2577 utils_str_equal(new_encoding, doc->encoding))
2578 return;
2580 g_free(doc->encoding);
2581 doc->encoding = g_strdup(new_encoding);
2583 ui_update_statusbar(doc, -1);
2584 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2585 encodings_is_unicode_charset(doc->encoding));
2589 /* own Undo / Redo implementation to be able to undo / redo changes
2590 * to the encoding or the Unicode BOM (which are Scintilla independet).
2591 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2593 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2594 void document_undo_clear(GeanyDocument *doc)
2596 undo_action *a;
2598 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2600 a = g_trash_stack_pop(&doc->priv->undo_actions);
2601 if (G_LIKELY(a != NULL))
2603 switch (a->type)
2605 case UNDO_ENCODING: g_free(a->data); break;
2606 default: break;
2608 g_free(a);
2611 doc->priv->undo_actions = NULL;
2613 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2615 a = g_trash_stack_pop(&doc->priv->redo_actions);
2616 if (G_LIKELY(a != NULL))
2618 switch (a->type)
2620 case UNDO_ENCODING: g_free(a->data); break;
2621 default: break;
2623 g_free(a);
2626 doc->priv->redo_actions = NULL;
2628 if (! main_status.quitting && doc->editor != NULL)
2629 document_set_text_changed(doc, FALSE);
2633 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2635 undo_action *action;
2637 g_return_if_fail(doc != NULL);
2639 action = g_new0(undo_action, 1);
2640 action->type = type;
2641 action->data = data;
2643 g_trash_stack_push(&doc->priv->undo_actions, action);
2645 document_set_text_changed(doc, TRUE);
2646 ui_update_popup_reundo_items(doc);
2650 gboolean document_can_undo(GeanyDocument *doc)
2652 g_return_val_if_fail(doc != NULL, FALSE);
2654 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2655 return TRUE;
2656 else
2657 return FALSE;
2661 static void update_changed_state(GeanyDocument *doc)
2663 doc->changed =
2664 (sci_is_modified(doc->editor->sci) ||
2665 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2666 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2667 document_set_text_changed(doc, doc->changed);
2671 void document_undo(GeanyDocument *doc)
2673 undo_action *action;
2675 g_return_if_fail(doc != NULL);
2677 action = g_trash_stack_pop(&doc->priv->undo_actions);
2679 if (G_UNLIKELY(action == NULL))
2681 /* fallback, should not be necessary */
2682 geany_debug("%s: fallback used", G_STRFUNC);
2683 sci_undo(doc->editor->sci);
2685 else
2687 switch (action->type)
2689 case UNDO_SCINTILLA:
2691 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2693 sci_undo(doc->editor->sci);
2694 break;
2696 case UNDO_BOM:
2698 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2700 doc->has_bom = GPOINTER_TO_INT(action->data);
2701 ui_update_statusbar(doc, -1);
2702 ui_document_show_hide(doc);
2703 break;
2705 case UNDO_ENCODING:
2707 /* use the "old" encoding */
2708 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2710 document_set_encoding(doc, (const gchar*)action->data);
2712 ignore_callback = TRUE;
2713 encodings_select_radio_item((const gchar*)action->data);
2714 ignore_callback = FALSE;
2716 g_free(action->data);
2717 break;
2719 default: break;
2722 g_free(action); /* free the action which was taken from the stack */
2724 update_changed_state(doc);
2725 ui_update_popup_reundo_items(doc);
2729 gboolean document_can_redo(GeanyDocument *doc)
2731 g_return_val_if_fail(doc != NULL, FALSE);
2733 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2734 return TRUE;
2735 else
2736 return FALSE;
2740 void document_redo(GeanyDocument *doc)
2742 undo_action *action;
2744 g_return_if_fail(doc != NULL);
2746 action = g_trash_stack_pop(&doc->priv->redo_actions);
2748 if (G_UNLIKELY(action == NULL))
2750 /* fallback, should not be necessary */
2751 geany_debug("%s: fallback used", G_STRFUNC);
2752 sci_redo(doc->editor->sci);
2754 else
2756 switch (action->type)
2758 case UNDO_SCINTILLA:
2760 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2762 sci_redo(doc->editor->sci);
2763 break;
2765 case UNDO_BOM:
2767 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2769 doc->has_bom = GPOINTER_TO_INT(action->data);
2770 ui_update_statusbar(doc, -1);
2771 ui_document_show_hide(doc);
2772 break;
2774 case UNDO_ENCODING:
2776 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2778 document_set_encoding(doc, (const gchar*)action->data);
2780 ignore_callback = TRUE;
2781 encodings_select_radio_item((const gchar*)action->data);
2782 ignore_callback = FALSE;
2784 g_free(action->data);
2785 break;
2787 default: break;
2790 g_free(action); /* free the action which was taken from the stack */
2792 update_changed_state(doc);
2793 ui_update_popup_reundo_items(doc);
2797 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2799 undo_action *action;
2801 g_return_if_fail(doc != NULL);
2803 action = g_new0(undo_action, 1);
2804 action->type = type;
2805 action->data = data;
2807 g_trash_stack_push(&doc->priv->redo_actions, action);
2809 document_set_text_changed(doc, TRUE);
2810 ui_update_popup_reundo_items(doc);
2815 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2816 * Returned colors are red if the document has changes, green if the document is read-only
2817 * or simply @c NULL if the document is unmodified but writable.
2819 * @param doc The document to use.
2821 * @return The color for the document or @c NULL if the default color should be used. The color
2822 * object is owned by Geany and should not be modified or freed.
2824 * @since 0.16
2826 const GdkColor *document_get_status_color(GeanyDocument *doc)
2828 static GdkColor red = {0, 0xFFFF, 0, 0};
2829 static GdkColor green = {0, 0, 0x7FFF, 0};
2830 #ifdef USE_GIO_FILEMON
2831 static GdkColor orange = {0, 0xFFFF, 0x7FFF, 0};
2832 #endif
2833 GdkColor *color = NULL;
2835 g_return_val_if_fail(doc != NULL, NULL);
2837 if (doc->changed)
2838 color = &red;
2839 #ifdef USE_GIO_FILEMON
2840 else if (doc->priv->file_disk_status == FILE_CHANGED)
2841 color = &orange;
2842 #endif
2843 else if (doc->readonly)
2844 color = &green;
2846 return color; /* return pointer to static GdkColor. */
2850 /** Accessor function for @ref GeanyData::documents_array items.
2851 * @warning Always check the returned document is valid (@c doc->is_valid).
2852 * @param idx @c documents_array index.
2853 * @return The document, or @c NULL if @a idx is out of range.
2855 * @since 0.16
2857 GeanyDocument *document_index(gint idx)
2859 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2863 /* create a new file and copy file content and properties */
2864 GeanyDocument *document_clone(GeanyDocument *old_doc, const gchar *utf8_filename)
2866 gint len;
2867 gchar *text;
2868 GeanyDocument *doc;
2870 g_return_val_if_fail(old_doc != NULL, NULL);
2872 len = sci_get_length(old_doc->editor->sci) + 1;
2873 text = (gchar*) g_malloc(len);
2874 sci_get_text(old_doc->editor->sci, len, text);
2875 /* use old file type (or maybe NULL for auto detect would be better?) */
2876 doc = document_new_file(utf8_filename, old_doc->file_type, text);
2877 g_free(text);
2879 /* copy file properties */
2880 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2881 doc->readonly = old_doc->readonly;
2882 doc->has_bom = old_doc->has_bom;
2883 document_set_encoding(doc, old_doc->encoding);
2884 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2885 sci_set_readonly(doc->editor->sci, doc->readonly);
2887 ui_document_show_hide(doc);
2888 return doc;
2892 /* @note If successful, this should always be followed up with a call to
2893 * document_close_all().
2894 * @return TRUE if all files were saved or had their changes discarded. */
2895 gboolean document_account_for_unsaved(void)
2897 guint i, p, page_count, len = documents_array->len;
2898 GeanyDocument *doc;
2900 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2901 for (p = 0; p < page_count; p++)
2903 doc = document_get_from_page(p);
2904 if (DOC_VALID(doc) && doc->changed)
2906 if (! dialogs_show_unsaved_file(doc))
2907 return FALSE;
2910 /* all documents should now be accounted for, so ignore any changes */
2911 for (i = 0; i < len; i++)
2913 doc = documents[i];
2914 if (doc->is_valid && doc->changed)
2916 doc->changed = FALSE;
2919 return TRUE;
2923 static void force_close_all(void)
2925 guint i, len = documents_array->len;
2927 /* check all documents have been accounted for */
2928 for (i = 0; i < len; i++)
2930 if (documents[i]->is_valid)
2932 g_return_if_fail(!documents[i]->changed);
2935 main_status.closing_all = TRUE;
2937 foreach_document(i)
2939 document_close(documents[i]);
2942 main_status.closing_all = FALSE;
2946 gboolean document_close_all(void)
2948 if (! document_account_for_unsaved())
2949 return FALSE;
2951 force_close_all();
2953 return TRUE;
2957 static void monitor_reload_file(GeanyDocument *doc)
2959 gchar *base_name = g_path_get_basename(doc->file_name);
2960 gint ret;
2962 ret = dialogs_show_prompt(NULL,
2963 GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
2964 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2965 _("_Reload"), GTK_RESPONSE_ACCEPT,
2966 _("Do you want to reload it?"),
2967 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2968 base_name);
2969 g_free(base_name);
2971 if (ret == GTK_RESPONSE_ACCEPT)
2972 document_reload_file(doc, doc->encoding);
2973 else if (ret == GTK_RESPONSE_CLOSE)
2974 document_close(doc);
2978 static gboolean monitor_resave_missing_file(GeanyDocument *doc)
2980 gboolean want_reload = FALSE;
2981 gboolean file_saved = FALSE;
2982 gint ret;
2984 ret = dialogs_show_prompt(NULL,
2985 _("Close _without saving"), GTK_RESPONSE_CLOSE,
2986 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2987 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
2988 _("Try to resave the file?"),
2989 _("File \"%s\" was not found on disk!"),
2990 doc->file_name);
2991 if (ret == GTK_RESPONSE_ACCEPT)
2993 file_saved = dialogs_show_save_as();
2994 want_reload = TRUE;
2996 else if (ret == GTK_RESPONSE_CLOSE)
2998 document_close(doc);
3000 if (ret != GTK_RESPONSE_CLOSE && ! file_saved)
3002 /* file is missing - set unsaved state */
3003 document_set_text_changed(doc, TRUE);
3004 /* don't prompt more than once */
3005 setptr(doc->real_path, NULL);
3008 return want_reload;
3012 /* Set force to force a disk check, otherwise it is ignored if there was a check
3013 * in the last file_prefs.disk_check_timeout seconds.
3014 * @return @c TRUE if the file has changed. */
3015 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3017 gboolean ret = FALSE;
3018 gboolean use_gio_filemon;
3019 time_t cur_time = 0;
3020 struct stat st;
3021 gchar *locale_filename;
3022 FileDiskStatus old_status;
3024 g_return_val_if_fail(doc != NULL, FALSE);
3026 /* ignore remote files and documents that have never been saved to disk */
3027 if (file_prefs.disk_check_timeout == 0 || doc->real_path == NULL || doc->priv->is_remote)
3028 return FALSE;
3030 use_gio_filemon = (doc->priv->monitor != NULL);
3032 if (use_gio_filemon)
3034 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3035 return FALSE;
3037 else
3039 cur_time = time(NULL);
3040 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3041 return FALSE;
3043 doc->priv->last_check = cur_time;
3046 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3047 if (g_stat(locale_filename, &st) != 0)
3049 monitor_resave_missing_file(doc);
3050 /* doc may be closed now */
3051 ret = TRUE;
3053 else if (! use_gio_filemon && /* ignore check when using GIO */
3054 doc->priv->mtime > cur_time)
3056 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3057 /* Note: on Windows st.st_mtime can be newer than cur_time */
3059 else if (doc->priv->mtime < st.st_mtime)
3061 doc->priv->mtime = st.st_mtime;
3062 monitor_reload_file(doc);
3063 /* doc may be closed now */
3064 ret = TRUE;
3066 g_free(locale_filename);
3068 if (DOC_VALID(doc))
3069 { /* doc can get invalid when a document was closed */
3070 old_status = doc->priv->file_disk_status;
3071 doc->priv->file_disk_status = FILE_OK;
3072 if (old_status != doc->priv->file_disk_status)
3073 ui_update_tab_status(doc);
3075 return ret;
3079 /** Compares documents by their display names.
3080 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3081 * @note 'Display name' means the base name of the document's filename.
3083 * @param a @c GeanyDocument**.
3084 * @param b @c GeanyDocument**.
3085 * @warning The arguments take the address of each document pointer.
3086 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3088 * @since 0.21
3090 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3092 GeanyDocument *doc_a = *((GeanyDocument**) a);
3093 GeanyDocument *doc_b = *((GeanyDocument**) b);
3094 gchar *base_name_a, *base_name_b;
3095 gint result;
3097 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3098 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3100 result = strcmp(base_name_a, base_name_b);
3102 g_free(base_name_a);
3103 g_free(base_name_b);
3105 return result;
3109 /** Compares documents by their tab order.
3110 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3112 * @param a @c GeanyDocument**.
3113 * @param b @c GeanyDocument**.
3114 * @warning The arguments take the address of each document pointer.
3115 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3117 * @since 0.21 (GEANY_API_VERSION 209)
3119 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3121 GeanyDocument *doc_a = *((GeanyDocument**) a);
3122 GeanyDocument *doc_b = *((GeanyDocument**) b);
3123 gint notebook_position_doc_a;
3124 gint notebook_position_doc_b;
3126 notebook_position_doc_a = document_get_notebook_page(doc_a);
3127 notebook_position_doc_b = document_get_notebook_page(doc_b);
3129 if (notebook_position_doc_a < notebook_position_doc_b)
3130 return -1;
3131 if (notebook_position_doc_a > notebook_position_doc_b)
3132 return 1;
3133 /* equality */
3134 return 0;
3138 /** Compares documents by their tab order, in reverse order.
3139 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3141 * @param a @c GeanyDocument**.
3142 * @param b @c GeanyDocument**.
3143 * @warning The arguments take the address of each document pointer.
3144 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3146 * @since 0.21 (GEANY_API_VERSION 209)
3148 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3150 GeanyDocument *doc_a = *((GeanyDocument**) a);
3151 GeanyDocument *doc_b = *((GeanyDocument**) b);
3152 gint notebook_position_doc_a;
3153 gint notebook_position_doc_b;
3155 notebook_position_doc_a = document_get_notebook_page(doc_a);
3156 notebook_position_doc_b = document_get_notebook_page(doc_b);
3158 if (notebook_position_doc_a < notebook_position_doc_b)
3159 return 1;
3160 if (notebook_position_doc_a > notebook_position_doc_b)
3161 return -1;
3162 /* equality */
3163 return 0;
3167 void document_grab_focus(GeanyDocument *doc)
3169 g_return_if_fail(doc != NULL);
3171 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));