infobars: Cancel "reload file" dialog when spawning the "resave file" one.
[geany-mirror.git] / src / document.c
blob8c7b13db1d79937219cd97185320b48fe82732b7
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 * Document related actions: new, save, open, etc.
24 * Also Scintilla search actions.
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #include "document.h"
33 #include "app.h"
34 #include "callbacks.h" /* for ignore_callback */
35 #include "dialogs.h"
36 #include "documentprivate.h"
37 #include "encodings.h"
38 #include "filetypesprivate.h"
39 #include "geany.h" /* FIXME: why is this needed for DOC_FILENAME()? should come from documentprivate.h/document.h */
40 #include "geanyobject.h"
41 #include "geanywraplabel.h" /* for document_show_message() using GtkInfoBar */
42 #include "highlighting.h"
43 #include "main.h"
44 #include "msgwindow.h"
45 #include "navqueue.h"
46 #include "notebook.h"
47 #include "project.h"
48 #include "sciwrappers.h"
49 #include "sidebar.h"
50 #include "support.h"
51 #include "symbols.h"
52 #include "ui_utils.h"
53 #include "utils.h"
54 #include "vte.h"
56 #ifdef HAVE_SYS_TIME_H
57 # include <sys/time.h>
58 #endif
59 #include <time.h>
61 #include <unistd.h>
62 #include <string.h>
63 #include <errno.h>
65 #ifdef HAVE_SYS_TYPES_H
66 # include <sys/types.h>
67 #endif
69 #include <stdlib.h>
71 /* gstdio.h also includes sys/stat.h */
72 #include <glib/gstdio.h>
74 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
75 /*#define USE_GIO_FILEMON 1*/
76 #include <gio/gio.h>
78 GeanyFilePrefs file_prefs;
81 /** Dynamic array of GeanyDocument pointers.
82 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
83 * to a document over time, but it may represent a different
84 * document later on, or may have been closed and become invalid.
86 * @warning You must check @c GeanyDocument::is_valid when iterating over this array.
87 * This is done automatically if you use the foreach_document() macro.
89 * @note
90 * Never assume that the order of document pointers is the same as the order of notebook tabs.
91 * One reason is that notebook tabs can be reordered.
92 * Use @c document_get_from_page() to lookup a document from a notebook tab number.
94 * @see documents. */
95 GPtrArray *documents_array = NULL;
98 /* an undo action, also used for redo actions */
99 typedef struct
101 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
102 guint type; /* to identify the action */
103 gpointer *data; /* the old value (before the change), in case of a redo action
104 * it contains the new value */
105 } undo_action;
108 static void document_undo_clear(GeanyDocument *doc);
109 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
110 static gboolean remove_page(guint page_num);
114 * Finds a document whose @c real_path field matches the given filename.
116 * @param realname The filename to search, which should be identical to the
117 * string returned by @c tm_get_real_path().
119 * @return The matching document, or @c NULL.
120 * @note This is only really useful when passing a @c TMWorkObject::file_name.
121 * @see GeanyDocument::real_path.
122 * @see document_find_by_filename().
124 * @since 0.15
126 GeanyDocument* document_find_by_real_path(const gchar *realname)
128 guint i;
130 if (! realname)
131 return NULL; /* file doesn't exist on disk */
133 for (i = 0; i < documents_array->len; i++)
135 GeanyDocument *doc = documents[i];
137 if (! doc->is_valid || ! doc->real_path)
138 continue;
140 if (utils_filenamecmp(realname, doc->real_path) == 0)
142 return doc;
145 return NULL;
149 /* dereference symlinks, /../ junk in path and return locale encoding */
150 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
152 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
153 gchar *realname = tm_get_real_path(locale_name);
155 g_free(locale_name);
156 return realname;
161 * Finds a document with the given filename.
162 * This matches either an exact GeanyDocument::file_name string, or variant
163 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
164 * match @c "/name").
166 * @param utf8_filename The filename to search (in UTF-8 encoding).
168 * @return The matching document, or @c NULL.
169 * @see document_find_by_real_path().
171 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
173 guint i;
174 GeanyDocument *doc;
175 gchar *realname;
177 g_return_val_if_fail(utf8_filename != NULL, NULL);
179 /* First search GeanyDocument::file_name, so we can find documents with a
180 * filename set but not saved on disk, like vcdiff produces */
181 for (i = 0; i < documents_array->len; i++)
183 doc = documents[i];
185 if (! doc->is_valid || doc->file_name == NULL)
186 continue;
188 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
190 return doc;
193 /* Now try matching based on the realpath(), which is unique per file on disk */
194 realname = get_real_path_from_utf8(utf8_filename);
195 doc = document_find_by_real_path(realname);
196 g_free(realname);
197 return doc;
201 /* returns the document which has sci, or NULL. */
202 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
204 guint i;
206 g_return_val_if_fail(sci != NULL, NULL);
208 for (i = 0; i < documents_array->len; i++)
210 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
211 return documents[i];
213 return NULL;
217 /** Gets the notebook page index for a document.
218 * @param doc The document.
219 * @return The index.
220 * @since 0.19 */
221 gint document_get_notebook_page(GeanyDocument *doc)
223 GtkWidget *parent;
225 g_return_val_if_fail(doc != NULL, -1);
227 parent = gtk_widget_get_parent(GTK_WIDGET(doc->editor->sci));
228 g_return_val_if_fail(GTK_IS_BOX(parent), -1);
230 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), parent);
235 * Recursively searches a containers children until it finds a
236 * Scintilla widget, or NULL if one was not found.
238 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
240 ScintillaObject *sci = NULL;
241 GList *children, *iter;
243 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
245 children = gtk_container_get_children(GTK_CONTAINER(container));
246 for (iter = children; iter != NULL; iter = g_list_next(iter))
248 if (IS_SCINTILLA(iter->data))
250 sci = SCINTILLA(iter->data);
251 break;
253 else if (GTK_IS_CONTAINER(iter->data))
255 sci = locate_sci_in_container(iter->data);
256 if (IS_SCINTILLA(sci))
257 break;
258 sci = NULL;
261 g_list_free(children);
263 return sci;
268 * Finds the document for the given notebook page @a page_num.
270 * @param page_num The notebook page number to search.
272 * @return The corresponding document for the given notebook page, or @c NULL.
274 GeanyDocument *document_get_from_page(guint page_num)
276 GtkWidget *parent;
277 ScintillaObject *sci;
279 if (page_num >= documents_array->len)
280 return NULL;
282 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
283 g_return_val_if_fail(GTK_IS_BOX(parent), NULL);
285 sci = locate_sci_in_container(parent);
286 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
288 return document_find_by_sci(sci);
293 * Finds the current document.
295 * @return A pointer to the current document or @c NULL if there are no opened documents.
297 GeanyDocument *document_get_current(void)
299 gint cur_page;
300 GtkWidget *parent;
301 ScintillaObject *sci;
303 cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
305 if (cur_page == -1)
306 return NULL;
307 else
309 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
310 g_return_val_if_fail(GTK_IS_BOX(parent), NULL);
312 sci = locate_sci_in_container(parent);
313 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
315 return document_find_by_sci(sci);
320 void document_init_doclist(void)
322 documents_array = g_ptr_array_new();
326 void document_finalize(void)
328 guint i;
330 for (i = 0; i < documents_array->len; i++)
331 g_free(documents[i]);
332 g_ptr_array_free(documents_array, TRUE);
337 * Returns the last part of the filename of the given GeanyDocument. The result is also
338 * truncated to a maximum of @a length characters in case the filename is very long.
340 * @param doc The document to use.
341 * @param length The length of the resulting string or -1 to use a default value.
343 * @return The ellipsized last part of the filename of @a doc, should be freed when no
344 * longer needed.
346 * @since 0.17
348 /* TODO make more use of this */
349 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
351 gchar *base_name, *short_name;
353 g_return_val_if_fail(doc != NULL, NULL);
355 if (length < 0)
356 length = 30;
358 base_name = g_path_get_basename(DOC_FILENAME(doc));
359 short_name = utils_str_middle_truncate(base_name, (guint)length);
361 g_free(base_name);
363 return short_name;
367 void document_update_tab_label(GeanyDocument *doc)
369 gchar *short_name;
370 GtkWidget *parent;
372 g_return_if_fail(doc != NULL);
374 short_name = document_get_basename_for_display(doc, -1);
376 /* we need to use the event box for the tooltip, labels don't get the necessary events */
377 parent = gtk_widget_get_parent(doc->priv->tab_label);
378 parent = gtk_widget_get_parent(parent);
380 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
382 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
384 g_free(short_name);
389 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
390 * according to the document's save state.
391 * This is called by Geany mostly when opening or saving files.
393 * @param doc The document to use.
394 * @param changed Whether the document state should indicate changes have been made.
396 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
398 g_return_if_fail(doc != NULL);
400 doc->changed = changed;
402 if (! main_status.quitting)
404 ui_update_tab_status(doc);
405 ui_save_buttons_toggle(changed);
406 ui_set_window_title(doc);
407 ui_update_statusbar(doc, -1);
412 /* returns the next free place in the document list,
413 * or -1 if the documents_array is full */
414 static gint document_get_new_idx(void)
416 guint i;
418 for (i = 0; i < documents_array->len; i++)
420 if (documents[i]->editor == NULL)
422 return (gint) i;
425 return -1;
429 static void queue_colourise(GeanyDocument *doc)
431 /* Colourise the editor before it is next drawn */
432 doc->priv->colourise_needed = TRUE;
434 /* If the editor doesn't need drawing (e.g. after saving the current
435 * document), we need to force a redraw, so the expose event is triggered.
436 * This ensures we don't start colourising before all documents are opened/saved,
437 * only once the editor is drawn. */
438 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
442 #ifdef USE_GIO_FILEMON
443 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
444 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
445 GeanyDocument *doc)
447 g_return_if_fail(doc != NULL);
449 if (file_prefs.disk_check_timeout == 0)
450 return;
452 geany_debug("%s: event: %d previous file status: %d",
453 G_STRFUNC, event, doc->priv->file_disk_status);
454 switch (event)
456 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
458 if (doc->priv->file_disk_status == FILE_IGNORE)
459 doc->priv->file_disk_status = FILE_OK;
460 else
461 doc->priv->file_disk_status = FILE_CHANGED;
462 g_message("%s: FILE_CHANGED", G_STRFUNC);
463 break;
465 case G_FILE_MONITOR_EVENT_DELETED:
467 doc->priv->file_disk_status = FILE_CHANGED;
468 g_message("%s: FILE_MISSING", G_STRFUNC);
469 break;
471 default:
472 break;
474 if (doc->priv->file_disk_status != FILE_OK)
476 ui_update_tab_status(doc);
479 #endif
482 static void document_stop_file_monitoring(GeanyDocument *doc)
484 g_return_if_fail(doc != NULL);
486 if (doc->priv->monitor != NULL)
488 g_object_unref(doc->priv->monitor);
489 doc->priv->monitor = NULL;
494 static void monitor_file_setup(GeanyDocument *doc)
496 g_return_if_fail(doc != NULL);
497 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
498 * doesn't work at all for remote files and legacy polling is too slow. */
499 if (! doc->priv->is_remote)
501 #ifdef USE_GIO_FILEMON
502 gchar *locale_filename;
504 /* stop any previous monitoring */
505 document_stop_file_monitoring(doc);
507 locale_filename = utils_get_locale_from_utf8(doc->file_name);
508 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
510 /* get a file monitor and connect to the 'changed' signal */
511 GFile *file = g_file_new_for_path(locale_filename);
512 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
513 g_signal_connect(doc->priv->monitor, "changed",
514 G_CALLBACK(monitor_file_changed_cb), doc);
516 /* we set the rate limit according to the GUI pref but it's most probably not used */
517 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
519 g_object_unref(file);
521 g_free(locale_filename);
522 #endif
524 doc->priv->file_disk_status = FILE_OK;
528 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
530 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
531 if (DOC_VALID(doc))
533 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
534 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
536 if (source_widget == NULL)
537 source_widget = doc->priv->tag_tree;
539 if (focusw == source_widget)
540 gtk_widget_grab_focus(sci);
545 static gboolean on_idle_focus(gpointer doc)
547 document_try_focus(doc, NULL);
548 return FALSE;
552 /* Creates a new document and editor, adding a tab in the notebook.
553 * @return The created document */
554 static GeanyDocument *document_create(const gchar *utf8_filename)
556 GeanyDocument *doc;
557 gint new_idx;
558 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
560 if (cur_pages == 1)
562 doc = document_get_current();
563 /* remove the empty document first */
564 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
565 /* prevent immediately opening another new doc with
566 * new_document_after_close pref */
567 remove_page(0);
570 new_idx = document_get_new_idx();
571 if (new_idx == -1) /* expand the array, no free places */
573 doc = g_new0(GeanyDocument, 1);
575 new_idx = documents_array->len;
576 g_ptr_array_add(documents_array, doc);
579 doc = documents[new_idx];
581 /* initialize default document settings */
582 doc->priv = g_new0(GeanyDocumentPrivate, 1);
583 doc->index = new_idx;
584 doc->file_name = g_strdup(utf8_filename);
585 doc->editor = editor_create(doc);
586 #ifndef USE_GIO_FILEMON
587 doc->priv->last_check = time(NULL);
588 #endif
590 sidebar_openfiles_add(doc); /* sets doc->iter */
592 notebook_new_tab(doc);
594 /* select document in sidebar */
596 GtkTreeSelection *sel;
598 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
599 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
602 ui_document_buttons_update();
604 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
605 return doc;
610 * Closes the given document.
612 * @param doc The document to remove.
614 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
616 * @since 0.15
618 gboolean document_close(GeanyDocument *doc)
620 g_return_val_if_fail(doc, FALSE);
622 return document_remove_page(document_get_notebook_page(doc));
626 /* Call document_remove_page() instead, this is only needed for document_create()
627 * to prevent re-opening a new document when the last document is closed (if enabled). */
628 static gboolean remove_page(guint page_num)
630 GeanyDocument *doc = document_get_from_page(page_num);
632 g_return_val_if_fail(doc != NULL, FALSE);
634 if (doc->changed && ! dialogs_show_unsaved_file(doc))
635 return FALSE;
637 /* tell any plugins that the document is about to be closed */
638 g_signal_emit_by_name(geany_object, "document-close", doc);
640 /* Checking real_path makes it likely the file exists on disk */
641 if (! main_status.closing_all && doc->real_path != NULL)
642 ui_add_recent_document(doc);
644 doc->is_valid = FALSE;
646 if (main_status.quitting)
648 /* we need to destroy the ScintillaWidget so our handlers on it are
649 * disconnected before we free any data they may use (like the editor).
650 * when not quitting, this is handled by removing the notebook page. */
651 gtk_widget_destroy(GTK_WIDGET(doc->editor->sci));
653 else
655 notebook_remove_page(page_num);
656 sidebar_remove_document(doc);
657 navqueue_remove_file(doc->file_name);
658 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
660 g_free(doc->encoding);
661 g_free(doc->priv->saved_encoding.encoding);
662 g_free(doc->file_name);
663 g_free(doc->real_path);
664 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
666 if (doc->priv->tag_tree)
667 gtk_widget_destroy(doc->priv->tag_tree);
669 editor_destroy(doc->editor);
670 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
672 document_stop_file_monitoring(doc);
674 document_undo_clear(doc);
676 g_free(doc->priv);
678 /* reset document settings to defaults for re-use */
679 memset(doc, 0, sizeof(GeanyDocument));
681 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
683 sidebar_update_tag_list(NULL, FALSE);
684 ui_set_window_title(NULL);
685 ui_save_buttons_toggle(FALSE);
686 ui_update_popup_reundo_items(NULL);
687 ui_document_buttons_update();
688 build_menu_update(NULL);
690 return TRUE;
695 * Removes the given notebook tab at @a page_num and clears all related information
696 * in the document list.
698 * @param page_num The notebook page number to remove.
700 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
702 gboolean document_remove_page(guint page_num)
704 gboolean done = remove_page(page_num);
706 if (done && ui_prefs.new_document_after_close)
707 document_new_file_if_non_open();
709 return done;
713 /* used to keep a record of the unchanged document state encoding */
714 static void store_saved_encoding(GeanyDocument *doc)
716 g_free(doc->priv->saved_encoding.encoding);
717 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
718 doc->priv->saved_encoding.has_bom = doc->has_bom;
722 /* Opens a new empty document only if there are no other documents open */
723 GeanyDocument *document_new_file_if_non_open(void)
725 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
726 return document_new_file(NULL, NULL, NULL);
728 return NULL;
733 * Creates a new document.
734 * Line endings in @a text will be converted to the default setting.
735 * Afterwards, the @c "document-new" signal is emitted for plugins.
737 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
738 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
739 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
741 * @return The new document.
743 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
745 GeanyDocument *doc;
747 if (utf8_filename && g_path_is_absolute(utf8_filename))
749 gchar *tmp;
750 tmp = utils_strdupa(utf8_filename); /* work around const */
751 utils_tidy_path(tmp);
752 utf8_filename = tmp;
754 doc = document_create(utf8_filename);
756 g_assert(doc != NULL);
758 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
759 if (text)
761 GString *template = g_string_new(text);
762 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
764 sci_set_text(doc->editor->sci, template->str);
765 g_string_free(template, TRUE);
767 else
768 sci_clear_all(doc->editor->sci);
770 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
772 sci_set_undo_collection(doc->editor->sci, TRUE);
773 sci_empty_undo_buffer(doc->editor->sci);
775 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
776 /* store the opened encoding for undo/redo */
777 store_saved_encoding(doc);
779 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
780 ft = filetypes_detect_from_document(doc);
782 document_set_filetype(doc, ft); /* also re-parses tags */
784 ui_set_window_title(doc);
785 build_menu_update(doc);
786 document_set_text_changed(doc, FALSE);
787 ui_document_show_hide(doc); /* update the document menu */
789 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
790 /* bring it in front, jump to the start and grab the focus */
791 editor_goto_pos(doc->editor, 0, FALSE);
792 document_try_focus(doc, NULL);
794 #ifdef USE_GIO_FILEMON
795 monitor_file_setup(doc);
796 #else
797 doc->priv->mtime = time(NULL);
798 #endif
800 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
801 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
803 g_signal_emit_by_name(geany_object, "document-new", doc);
805 msgwin_status_add(_("New file \"%s\" opened."),
806 DOC_FILENAME(doc));
808 return doc;
813 * Opens a document specified by @a locale_filename.
814 * Afterwards, the @c "document-open" signal is emitted for plugins.
816 * @param locale_filename The filename of the document to load, in locale encoding.
817 * @param readonly Whether to open the document in read-only mode.
818 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
819 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
821 * @return The document opened or @c NULL.
823 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
824 GeanyFiletype *ft, const gchar *forced_enc)
826 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
830 typedef struct
832 gchar *data; /* null-terminated file data */
833 gsize len; /* string length of data */
834 gchar *enc;
835 gboolean bom;
836 time_t mtime; /* modification time, read by stat::st_mtime */
837 gboolean readonly;
838 } FileData;
841 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
842 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
843 FileData *filedata, const gchar *forced_enc)
845 GError *err = NULL;
846 struct stat st;
848 filedata->data = NULL;
849 filedata->len = 0;
850 filedata->enc = NULL;
851 filedata->bom = FALSE;
852 filedata->readonly = FALSE;
854 if (g_stat(locale_filename, &st) != 0)
856 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
857 display_filename, g_strerror(errno));
858 return FALSE;
861 filedata->mtime = st.st_mtime;
863 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
865 ui_set_statusbar(TRUE, "%s", err->message);
866 g_error_free(err);
867 return FALSE;
870 filedata->len = (gsize) st.st_size;
871 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
872 &filedata->enc, &filedata->bom, &filedata->readonly))
874 if (forced_enc)
876 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
877 display_filename, forced_enc);
879 else
881 ui_set_statusbar(TRUE,
882 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
883 display_filename);
885 g_free(filedata->data);
886 return FALSE;
889 if (filedata->readonly)
891 const gchar *warn_msg = _(
892 "The file \"%s\" could not be opened properly and has been truncated. " \
893 "This can occur if the file contains a NULL byte. " \
894 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
896 if (main_status.main_window_realized)
897 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
899 ui_set_statusbar(TRUE, warn_msg, display_filename);
902 return TRUE;
906 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
907 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
908 * if cl_options.goto_column is set.
910 * returns the new position which may have changed */
911 static gint set_cursor_position(GeanyEditor *editor, gint pos)
913 if (cl_options.goto_line >= 0)
914 { /* goto line which was specified on command line and then undefine the line */
915 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
916 editor->scroll_percent = 0.5F;
917 cl_options.goto_line = -1;
919 else if (pos > 0)
921 sci_set_current_position(editor->sci, pos, FALSE);
922 editor->scroll_percent = 0.5F;
925 if (cl_options.goto_column >= 0)
926 { /* goto column which was specified on command line and then undefine the column */
928 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
929 sci_set_current_position(editor->sci, new_pos, FALSE);
930 editor->scroll_percent = 0.5F;
931 cl_options.goto_column = -1;
932 return new_pos;
934 return sci_get_current_position(editor->sci);
938 /* Count lines that start with some hard tabs then a soft tab. */
939 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
941 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
942 ScintillaObject *sci = editor->sci;
943 gsize count = 0;
944 struct Sci_TextToFind ttf;
945 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
946 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
948 g_free(soft_tab);
950 ttf.chrg.cpMin = 0;
951 ttf.chrg.cpMax = sci_get_length(sci);
952 ttf.lpstrText = regex;
953 while (1)
955 gint pos;
957 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
958 if (pos == -1)
959 break; /* no more matches */
960 count++;
961 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
963 g_free(regex);
964 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
965 return count > sci_get_line_count(sci) * 0.02;
969 /* Detect the indent type based on counting the leading indent characters for each line.
970 * Returns whether detection succeeded, and the detected type in *type_ upon success */
971 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
973 GeanyEditor *editor = doc->editor;
974 ScintillaObject *sci = editor->sci;
975 gint line, line_count;
976 gsize tabs = 0, spaces = 0;
978 if (detect_tabs_and_spaces(editor))
980 *type_ = GEANY_INDENT_TYPE_BOTH;
981 return TRUE;
984 line_count = sci_get_line_count(sci);
985 for (line = 0; line < line_count; line++)
987 gint pos = sci_get_position_from_line(sci, line);
988 gchar c;
990 /* most code will have indent total <= 24, otherwise it's more likely to be
991 * alignment than indentation */
992 if (sci_get_line_indentation(sci, line) > 24)
993 continue;
995 c = sci_get_char_at(sci, pos);
996 if (c == '\t')
997 tabs++;
998 /* check for at least 2 spaces */
999 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1000 spaces++;
1002 if (spaces == 0 && tabs == 0)
1003 return FALSE;
1005 /* the factors may need to be tweaked */
1006 if (spaces > tabs * 4)
1007 *type_ = GEANY_INDENT_TYPE_SPACES;
1008 else if (tabs > spaces * 4)
1009 *type_ = GEANY_INDENT_TYPE_TABS;
1010 else
1011 *type_ = GEANY_INDENT_TYPE_BOTH;
1013 return TRUE;
1017 /* Detect the indent width based on counting the leading indent characters for each line.
1018 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1019 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1021 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1022 ScintillaObject *sci = editor->sci;
1023 gint line, line_count;
1024 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1025 gint count, width, i;
1027 /* can't easily detect the supposed width of a tab, guess the default is OK */
1028 if (type == GEANY_INDENT_TYPE_TABS)
1029 return FALSE;
1031 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1032 sci_set_tab_width(sci, 8);
1034 line_count = sci_get_line_count(sci);
1035 for (line = 0; line < line_count; line++)
1037 gint pos = sci_get_line_indent_position(sci, line);
1039 /* We probably don't have style info yet, because we're generally called just after
1040 * the document got created, so we can't use highlighting_is_code_style().
1041 * That's not good, but the assumption below that concerning lines start with an
1042 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1043 * without removing too much legitimate lines. */
1044 if (sci_get_char_at(sci, pos) == '*')
1045 continue;
1047 width = sci_get_line_indentation(sci, line);
1048 /* most code will have indent total <= 24, otherwise it's more likely to be
1049 * alignment than indentation */
1050 if (width > 24)
1051 continue;
1052 /* < 2 is no indentation */
1053 if (width < 2)
1054 continue;
1056 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1058 if ((width % (i + 2)) == 0)
1059 widths[i]++;
1062 count = 0;
1063 width = iprefs->width;
1064 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1066 /* give large indents higher weight not to be fooled by spurious indents */
1067 if (widths[i] >= count * 1.5)
1069 width = i + 2;
1070 count = widths[i];
1074 if (count == 0)
1075 return FALSE;
1077 *width_ = width;
1078 return TRUE;
1082 /* same as detect_indent_width() but uses editor's indent type */
1083 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1085 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1089 void document_apply_indent_settings(GeanyDocument *doc)
1091 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1092 GeanyIndentType type = iprefs->type;
1093 gint width = iprefs->width;
1095 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1097 if (type != iprefs->type)
1099 const gchar *name = NULL;
1101 switch (type)
1103 case GEANY_INDENT_TYPE_SPACES:
1104 name = _("Spaces");
1105 break;
1106 case GEANY_INDENT_TYPE_TABS:
1107 name = _("Tabs");
1108 break;
1109 case GEANY_INDENT_TYPE_BOTH:
1110 name = _("Tabs and Spaces");
1111 break;
1113 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1114 * and Spaces), the second one is the filename */
1115 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1116 DOC_FILENAME(doc));
1119 else if (doc->file_type->indent_type > -1)
1120 type = doc->file_type->indent_type;
1122 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1124 if (width != iprefs->width)
1126 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1127 DOC_FILENAME(doc));
1130 else if (doc->file_type->indent_width > -1)
1131 width = doc->file_type->indent_width;
1133 editor_set_indent(doc->editor, type, width);
1137 void document_show_tab(GeanyDocument *doc)
1139 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1140 document_get_notebook_page(doc));
1144 /* To open a new file, set doc to NULL; filename should be locale encoded.
1145 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1146 * pos is the cursor position, which can be overridden by --line and --column.
1147 * forced_enc can be NULL to detect the file encoding.
1148 * Returns: doc of the opened file or NULL if an error occurred. */
1149 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1150 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1152 gint editor_mode;
1153 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1154 gchar *utf8_filename = NULL;
1155 gchar *display_filename = NULL;
1156 gchar *locale_filename = NULL;
1157 GeanyFiletype *use_ft;
1158 FileData filedata;
1160 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1162 if (reload)
1164 utf8_filename = g_strdup(doc->file_name);
1165 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1167 else
1169 /* filename must not be NULL when opening a file */
1170 g_return_val_if_fail(filename, NULL);
1172 #ifdef G_OS_WIN32
1173 /* if filename is a shortcut, try to resolve it */
1174 locale_filename = win32_get_shortcut_target(filename);
1175 #else
1176 locale_filename = g_strdup(filename);
1177 #endif
1178 /* remove relative junk */
1179 utils_tidy_path(locale_filename);
1181 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1182 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1184 /* if file is already open, switch to it and go */
1185 doc = document_find_by_filename(utf8_filename);
1186 if (doc != NULL)
1188 ui_add_recent_document(doc); /* either add or reorder recent item */
1189 /* show the doc before reload dialog */
1190 document_show_tab(doc);
1191 document_check_disk_status(doc, TRUE); /* force a file changed check */
1194 if (reload || doc == NULL)
1195 { /* doc possibly changed */
1196 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1198 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1200 g_free(display_filename);
1201 g_free(utf8_filename);
1202 g_free(locale_filename);
1203 return NULL;
1206 if (! reload)
1208 doc = document_create(utf8_filename);
1209 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1211 /* file exists on disk, set real_path */
1212 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1214 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1215 monitor_file_setup(doc);
1218 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1219 sci_empty_undo_buffer(doc->editor->sci);
1221 /* add the text to the ScintillaObject */
1222 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1223 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1224 queue_colourise(doc); /* Ensure the document gets colourised. */
1226 /* detect & set line endings */
1227 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1228 sci_set_eol_mode(doc->editor->sci, editor_mode);
1229 g_free(filedata.data);
1231 sci_set_undo_collection(doc->editor->sci, TRUE);
1233 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1234 g_free(doc->encoding); /* if reloading, free old encoding */
1235 doc->encoding = filedata.enc;
1236 doc->has_bom = filedata.bom;
1237 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1239 doc->readonly = readonly || filedata.readonly;
1240 sci_set_readonly(doc->editor->sci, doc->readonly);
1241 doc->priv->protected = 0;
1243 /* update line number margin width */
1244 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1245 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1247 if (! reload)
1250 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1251 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1252 doc->editor);
1254 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1256 else
1257 { /* reloading */
1258 document_undo_clear(doc);
1260 use_ft = ft;
1262 /* update taglist, typedef keywords and build menu if necessary */
1263 document_set_filetype(doc, use_ft);
1265 /* set indentation settings after setting the filetype */
1266 if (reload)
1267 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1268 else
1269 document_apply_indent_settings(doc);
1271 document_set_text_changed(doc, FALSE); /* also updates tab state */
1272 ui_document_show_hide(doc); /* update the document menu */
1274 /* finally add current file to recent files menu, but not the files from the last session */
1275 if (! main_status.opening_session_files)
1276 ui_add_recent_document(doc);
1278 if (reload)
1280 g_signal_emit_by_name(geany_object, "document-reload", doc);
1281 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1283 else
1285 g_signal_emit_by_name(geany_object, "document-open", doc);
1286 /* For translators: this is the status window message for opening a file. %d is the number
1287 * of the newly opened file, %s indicates whether the file is opened read-only
1288 * (it is replaced with the string ", read-only"). */
1289 msgwin_status_add(_("File %s opened(%d%s)."),
1290 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1291 (readonly) ? _(", read-only") : "");
1295 g_free(display_filename);
1296 g_free(utf8_filename);
1297 g_free(locale_filename);
1299 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1300 pos = set_cursor_position(doc->editor, pos);
1301 /* now bring the file in front */
1302 editor_goto_pos(doc->editor, pos, FALSE);
1304 /* finally, let the editor widget grab the focus so you can start coding
1305 * right away */
1306 g_idle_add(on_idle_focus, doc);
1307 return doc;
1311 /* Takes a new line separated list of filename URIs and opens each file.
1312 * length is the length of the string */
1313 void document_open_file_list(const gchar *data, gsize length)
1315 guint i;
1316 gchar *filename;
1317 gchar **list;
1319 g_return_if_fail(data != NULL);
1321 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1323 /* stop at the end or first empty item, because last item is empty but not null */
1324 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1326 filename = utils_get_path_from_uri(list[i]);
1327 if (filename == NULL)
1328 continue;
1329 document_open_file(filename, FALSE, NULL, NULL);
1330 g_free(filename);
1333 g_strfreev(list);
1338 * Opens each file in the list @a filenames.
1339 * Internally, document_open_file() is called for every list item.
1341 * @param filenames A list of filenames to load, in locale encoding.
1342 * @param readonly Whether to open the document in read-only mode.
1343 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1344 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1346 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1347 const gchar *forced_enc)
1349 const GSList *item;
1351 for (item = filenames; item != NULL; item = g_slist_next(item))
1353 document_open_file(item->data, readonly, ft, forced_enc);
1359 * Reloads the document with the specified file encoding
1360 * @a forced_enc or @c NULL to auto-detect the file encoding.
1362 * @param doc The document to reload.
1363 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1365 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1367 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1369 gint pos = 0;
1370 GeanyDocument *new_doc;
1372 g_return_val_if_fail(doc != NULL, FALSE);
1374 /* try to set the cursor to the position before reloading */
1375 pos = sci_get_current_position(doc->editor->sci);
1376 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1378 return (new_doc != NULL);
1382 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1384 #ifndef USE_GIO_FILEMON
1385 struct stat st;
1387 g_return_val_if_fail(doc != NULL, FALSE);
1389 /* stat the file to get the timestamp, otherwise on Windows the actual
1390 * timestamp can be ahead of time(NULL) */
1391 if (g_stat(locale_filename, &st) != 0)
1393 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1394 g_strerror(errno));
1395 return FALSE;
1398 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1399 #endif
1400 return TRUE;
1404 /* Sets line and column to the given position byte_pos in the document.
1405 * byte_pos is the position counted in bytes, not characters */
1406 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1408 gint i;
1409 gint line_start;
1411 /* for some reason we can use byte count instead of character count here */
1412 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1413 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1414 /* get the column in the line */
1415 *column = byte_pos - line_start;
1417 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1418 * skip one byte(i++) and decrease the column number which is based on byte count */
1419 for (i = line_start; i < (line_start + *column); i++)
1421 if (sci_get_char_at(doc->editor->sci, i) < 0)
1423 (*column)--;
1424 i++;
1430 static void replace_header_filename(GeanyDocument *doc)
1432 gchar *filebase;
1433 gchar *filename;
1434 struct Sci_TextToFind ttf;
1436 g_return_if_fail(doc != NULL);
1437 g_return_if_fail(doc->file_type != NULL);
1439 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1440 if (doc->file_type->extension)
1441 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1442 else
1443 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1445 filename = g_path_get_basename(doc->file_name);
1447 /* only search the first 3 lines */
1448 ttf.chrg.cpMin = 0;
1449 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1450 ttf.lpstrText = filebase;
1452 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf, NULL) != -1)
1454 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1455 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1456 sci_replace_target(doc->editor->sci, filename, FALSE);
1458 g_free(filebase);
1459 g_free(filename);
1464 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1465 * you still have to call @ref document_save_file_as() to change the @a doc object.
1466 * It also stops monitoring for file changes to prevent receiving too many file change events
1467 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1469 * @param doc The current document which should be renamed.
1470 * @param new_filename The new filename in UTF-8 encoding.
1472 * @since 0.16
1474 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1476 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1477 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1478 gint result;
1480 /* stop file monitoring to avoid getting events for deleting/creating files,
1481 * it's re-setup in document_save_file_as() */
1482 document_stop_file_monitoring(doc);
1484 result = g_rename(old_locale_filename, new_locale_filename);
1485 if (result != 0)
1487 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1488 _("Error renaming file."), g_strerror(errno));
1490 g_free(old_locale_filename);
1491 g_free(new_locale_filename);
1495 static void protect_document(GeanyDocument *doc)
1497 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1498 if (!doc->priv->protected++)
1499 sci_set_readonly(doc->editor->sci, TRUE);
1502 static void unprotect_document(GeanyDocument *doc)
1504 g_return_if_fail(doc->priv->protected > 0);
1506 if (!--doc->priv->protected && doc->readonly == FALSE)
1507 sci_set_readonly(doc->editor->sci, FALSE);
1511 /* Return TRUE if the document doesn't have a full filename set.
1512 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1513 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1514 * new files. */
1515 gboolean document_need_save_as(GeanyDocument *doc)
1517 g_return_val_if_fail(doc != NULL, FALSE);
1519 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1524 * Saves the document, detecting the filetype.
1526 * @param doc The document for the file to save.
1527 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1528 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1530 * @see document_save_file().
1532 * @since 0.16
1534 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1536 gboolean ret;
1537 gboolean new_file;
1539 g_return_val_if_fail(doc != NULL, FALSE);
1541 new_file = document_need_save_as(doc) || (utf8_fname != NULL && !strcmp(doc->file_name, utf8_fname));
1542 if (utf8_fname != NULL)
1543 SETPTR(doc->file_name, g_strdup(utf8_fname));
1545 /* reset real path, it's retrieved again in document_save() */
1546 SETPTR(doc->real_path, NULL);
1548 /* detect filetype */
1549 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1551 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1553 document_set_filetype(doc, ft);
1554 if (document_get_current() == doc)
1556 ignore_callback = TRUE;
1557 filetypes_select_radio_item(doc->file_type);
1558 ignore_callback = FALSE;
1562 if (new_file)
1564 sci_set_readonly(doc->editor->sci, FALSE);
1565 doc->readonly = FALSE;
1566 if (doc->priv->protected > 0)
1567 unprotect_document(doc);
1570 replace_header_filename(doc);
1572 ret = document_save_file(doc, TRUE);
1574 /* file monitoring support, add file monitoring after the file has been saved
1575 * to ignore any earlier events */
1576 monitor_file_setup(doc);
1577 doc->priv->file_disk_status = FILE_IGNORE;
1579 if (ret)
1580 ui_add_recent_document(doc);
1581 return ret;
1585 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1587 GError *conv_error = NULL;
1588 gchar* conv_file_contents = NULL;
1589 gsize bytes_read;
1590 gsize conv_len;
1592 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1593 g_return_val_if_fail(len != NULL, FALSE);
1595 /* try to convert it from UTF-8 to original encoding */
1596 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1597 &bytes_read, &conv_len, &conv_error);
1599 if (conv_error != NULL)
1601 gchar *text = g_strdup_printf(
1602 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1603 doc->encoding);
1604 gchar *error_text;
1606 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1608 gint line, column;
1609 gint context_len;
1610 gunichar unic;
1611 /* don't read over the doc length */
1612 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1613 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1614 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1616 /* take only one valid Unicode character from the context and discard the leftover */
1617 unic = g_utf8_get_char_validated(context, -1);
1618 context_len = g_unichar_to_utf8(unic, context);
1619 context[context_len] = '\0';
1620 get_line_column_from_pos(doc, bytes_read, &line, &column);
1622 error_text = g_strdup_printf(
1623 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1624 conv_error->message, context, line + 1, column);
1626 else
1627 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1629 geany_debug("encoding error: %s", conv_error->message);
1630 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1631 g_error_free(conv_error);
1632 g_free(text);
1633 g_free(error_text);
1634 return FALSE;
1636 else
1638 g_free(*data);
1639 *data = conv_file_contents;
1640 *len = conv_len;
1642 return TRUE;
1646 static gchar *write_data_to_disk(const gchar *locale_filename,
1647 const gchar *data, gsize len)
1649 GError *error = NULL;
1651 if (file_prefs.use_safe_file_saving)
1653 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1654 * This is the only option that handles disk space exhaustion. */
1655 if (g_file_set_contents(locale_filename, data, len, &error))
1656 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1658 else if (file_prefs.use_gio_unsafe_file_saving)
1660 GFile *fp;
1662 /* Use GIO API to save file (GVFS-safe)
1663 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1664 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1665 fp = g_file_new_for_path(locale_filename);
1666 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1667 G_FILE_CREATE_NONE, NULL, NULL, &error);
1668 g_object_unref(fp);
1670 else
1672 FILE *fp;
1673 int save_errno;
1674 gchar *display_name = g_filename_display_name(locale_filename);
1676 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1677 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1678 errno = 0;
1679 fp = g_fopen(locale_filename, "wb");
1680 if (fp == NULL)
1682 save_errno = errno;
1684 g_set_error(&error,
1685 G_FILE_ERROR,
1686 g_file_error_from_errno(save_errno),
1687 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1688 display_name,
1689 g_strerror(save_errno));
1691 else
1693 gsize bytes_written;
1695 errno = 0;
1696 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1698 if (len != bytes_written)
1700 save_errno = errno;
1702 g_set_error(&error,
1703 G_FILE_ERROR,
1704 g_file_error_from_errno(save_errno),
1705 _("Failed to write file '%s': fwrite() failed: %s"),
1706 display_name,
1707 g_strerror(save_errno));
1710 errno = 0;
1711 /* preserve the fwrite() error if any */
1712 if (fclose(fp) != 0 && error == NULL)
1714 save_errno = errno;
1716 g_set_error(&error,
1717 G_FILE_ERROR,
1718 g_file_error_from_errno(save_errno),
1719 _("Failed to close file '%s': fclose() failed: %s"),
1720 display_name,
1721 g_strerror(save_errno));
1725 g_free(display_name);
1727 if (error != NULL)
1729 gchar *msg = g_strdup(error->message);
1730 g_error_free(error);
1731 /* geany will warn about file truncation for unsafe saving below */
1732 return msg;
1734 return NULL;
1738 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1739 const gchar *data, gsize len)
1741 gchar *err;
1743 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1744 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1746 err = write_data_to_disk(locale_filename, data, len);
1747 if (err)
1748 return err;
1750 /* now the file is on disk, set real_path */
1751 if (doc->real_path == NULL)
1753 doc->real_path = tm_get_real_path(locale_filename);
1754 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1755 monitor_file_setup(doc);
1757 return NULL;
1761 * Saves the document.
1762 * Also shows the Save As dialog if necessary.
1763 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1765 * Saving may include replacing tabs with spaces,
1766 * stripping trailing spaces and adding a final new line at the end of the file, depending
1767 * on user preferences. Then the @c "document-before-save" signal is emitted,
1768 * allowing plugins to modify the document before it is saved, and data is
1769 * actually written to disk.
1771 * On successful saving:
1772 * - GeanyDocument::real_path is set.
1773 * - The filetype is set again or auto-detected if it wasn't set yet.
1774 * - The @c "document-save" signal is emitted for plugins.
1776 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1777 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1778 * added in Geany 1.22.
1780 * @param doc The document to save.
1781 * @param force Whether to save the file even if it is not modified.
1783 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1785 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1787 gchar *errmsg;
1788 gchar *data;
1789 gsize len;
1790 gchar *locale_filename;
1791 const GeanyFilePrefs *fp;
1793 g_return_val_if_fail(doc != NULL, FALSE);
1795 if (document_need_save_as(doc))
1797 /* ensure doc is the current tab before showing the dialog */
1798 document_show_tab(doc);
1799 return dialogs_show_save_as();
1802 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1803 if (doc->readonly || doc->priv->protected)
1804 return FALSE;
1805 if (!force && !doc->changed)
1806 return FALSE;
1808 fp = project_get_file_prefs();
1809 /* replaces tabs with spaces but only if the current file is not a Makefile */
1810 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1811 editor_replace_tabs(doc->editor);
1812 /* strip trailing spaces */
1813 if (fp->strip_trailing_spaces)
1814 editor_strip_trailing_spaces(doc->editor);
1815 /* ensure the file has a newline at the end */
1816 if (fp->final_new_line)
1817 editor_ensure_final_newline(doc->editor);
1818 /* ensure newlines are consistent */
1819 if (fp->ensure_convert_new_lines)
1820 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1822 /* notify plugins which may wish to modify the document before it's saved */
1823 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1825 len = sci_get_length(doc->editor->sci) + 1;
1826 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1827 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1828 * encoding, it will be converted to doc->encoding below and this conversion
1829 * also changes the BOM */
1830 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1831 data[0] = (gchar) 0xef;
1832 data[1] = (gchar) 0xbb;
1833 data[2] = (gchar) 0xbf;
1834 sci_get_text(doc->editor->sci, len, data + 3);
1835 len += 3;
1837 else
1839 data = (gchar*) g_malloc(len);
1840 sci_get_text(doc->editor->sci, len, data);
1843 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1844 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1845 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1847 if (! save_convert_to_encoding(doc, &data, &len))
1849 g_free(data);
1850 return FALSE;
1853 else
1855 len = strlen(data);
1858 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1860 /* ignore file changed notification when the file is written */
1861 doc->priv->file_disk_status = FILE_IGNORE;
1863 /* actually write the content of data to the file on disk */
1864 errmsg = save_doc(doc, locale_filename, data, len);
1865 g_free(data);
1867 if (errmsg != NULL)
1869 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1871 if (!file_prefs.use_safe_file_saving)
1873 SETPTR(errmsg,
1874 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1876 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1877 doc->priv->file_disk_status = FILE_OK;
1878 utils_beep();
1879 g_free(locale_filename);
1880 g_free(errmsg);
1881 return FALSE;
1884 /* store the opened encoding for undo/redo */
1885 store_saved_encoding(doc);
1887 /* ignore the following things if we are quitting */
1888 if (! main_status.quitting)
1890 sci_set_savepoint(doc->editor->sci);
1892 if (file_prefs.disk_check_timeout > 0)
1893 document_update_timestamp(doc, locale_filename);
1895 /* update filetype-related things */
1896 document_set_filetype(doc, doc->file_type);
1898 document_update_tab_label(doc);
1900 msgwin_status_add(_("File %s saved."), doc->file_name);
1901 ui_update_statusbar(doc, -1);
1902 #ifdef HAVE_VTE
1903 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1904 #endif
1906 g_free(locale_filename);
1908 g_signal_emit_by_name(geany_object, "document-save", doc);
1910 return TRUE;
1914 /* special search function, used from the find entry in the toolbar
1915 * return TRUE if text was found otherwise FALSE
1916 * return also TRUE if text is empty */
1917 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1918 gboolean backwards)
1920 gint start_pos, search_pos;
1921 struct Sci_TextToFind ttf;
1923 g_return_val_if_fail(text != NULL, FALSE);
1924 g_return_val_if_fail(doc != NULL, FALSE);
1925 if (! *text)
1926 return TRUE;
1928 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1929 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1931 /* search cursor to end or start */
1932 ttf.chrg.cpMin = start_pos;
1933 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1934 ttf.lpstrText = (gchar *)text;
1935 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1937 /* if no match, search start (or end) to cursor */
1938 if (search_pos == -1)
1940 if (backwards)
1942 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1943 ttf.chrg.cpMax = start_pos;
1945 else
1947 ttf.chrg.cpMin = 0;
1948 ttf.chrg.cpMax = start_pos + strlen(text);
1950 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1953 if (search_pos != -1)
1955 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1957 /* unfold maybe folded results */
1958 sci_ensure_line_is_visible(doc->editor->sci, line);
1960 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1961 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1963 if (! editor_line_in_view(doc->editor, line))
1964 { /* we need to force scrolling in case the cursor is outside of the current visible area
1965 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1966 * while searching */
1967 editor_scroll_to_line(doc->editor, -1, 0.3F);
1969 else
1970 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1971 return TRUE;
1973 else
1975 if (! inc)
1977 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1979 utils_beep();
1980 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1981 return FALSE;
1986 /* General search function, used from the find dialog.
1987 * Returns -1 on failure or the start position of the matching text.
1988 * Will skip past any selection, ignoring it.
1990 * @param text Text to find.
1991 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1993 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
1994 gint flags, gboolean search_backwards, GeanyMatchInfo **match_,
1995 gboolean scroll, GtkWidget *parent)
1997 gint selection_end, selection_start, search_pos;
1999 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2000 if (! *text)
2001 return -1;
2003 /* Sci doesn't support searching backwards with a regex */
2004 if (flags & SCFIND_REGEXP)
2005 search_backwards = FALSE;
2007 if (!original_text)
2008 original_text = text;
2010 selection_start = sci_get_selection_start(doc->editor->sci);
2011 selection_end = sci_get_selection_end(doc->editor->sci);
2012 if ((selection_end - selection_start) > 0)
2013 { /* there's a selection so go to the end */
2014 if (search_backwards)
2015 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2016 else
2017 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2020 sci_set_search_anchor(doc->editor->sci);
2021 if (search_backwards)
2022 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2023 else
2024 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2026 if (search_pos != -1)
2028 /* unfold maybe folded results */
2029 sci_ensure_line_is_visible(doc->editor->sci,
2030 sci_get_line_from_position(doc->editor->sci, search_pos));
2031 if (scroll)
2032 doc->editor->scroll_percent = 0.3F;
2034 else
2036 gint sci_len = sci_get_length(doc->editor->sci);
2038 /* if we just searched the whole text, give up searching. */
2039 if ((selection_end == 0 && ! search_backwards) ||
2040 (selection_end == sci_len && search_backwards))
2042 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2043 utils_beep();
2044 return -1;
2047 /* we searched only part of the document, so ask whether to wraparound. */
2048 if (search_prefs.always_wrap ||
2049 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2050 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2052 gint ret;
2054 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2055 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2056 if (ret == -1)
2057 { /* return to original cursor position if not found */
2058 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2060 return ret;
2063 return search_pos;
2067 /* Replaces the selection if it matches, otherwise just finds the next match.
2068 * Returns: start of replaced text, or -1 if no replacement was made
2070 * @param find_text Text to find.
2071 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2073 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2074 const gchar *replace_text, gint flags, gboolean search_backwards)
2076 gint selection_end, selection_start, search_pos;
2077 GeanyMatchInfo *match = NULL;
2079 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2081 if (! *find_text)
2082 return -1;
2084 /* Sci doesn't support searching backwards with a regex */
2085 if (flags & SCFIND_REGEXP)
2086 search_backwards = FALSE;
2088 if (!original_find_text)
2089 original_find_text = find_text;
2091 selection_start = sci_get_selection_start(doc->editor->sci);
2092 selection_end = sci_get_selection_end(doc->editor->sci);
2093 if (selection_end == selection_start)
2095 /* no selection so just find the next match */
2096 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2097 return -1;
2099 /* there's a selection so go to the start before finding to search through it
2100 * this ensures there is a match */
2101 if (search_backwards)
2102 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2103 else
2104 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2106 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2107 /* return if the original selected text did not match (at the start of the selection) */
2108 if (search_pos != selection_start)
2110 if (search_pos != -1)
2111 geany_match_info_free(match);
2112 return -1;
2115 if (search_pos != -1)
2117 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2118 /* select the replacement - find text will skip past the selected text */
2119 sci_set_selection_start(doc->editor->sci, search_pos);
2120 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2121 geany_match_info_free(match);
2123 else
2125 /* no match in the selection */
2126 utils_beep();
2128 return search_pos;
2132 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2133 const gchar *original_replace_text)
2135 gchar *filename;
2137 if (count == 0)
2139 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2140 return;
2143 filename = g_path_get_basename(DOC_FILENAME(doc));
2144 ui_set_statusbar(TRUE, ngettext(
2145 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2146 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2147 count), filename, count, original_find_text, original_replace_text);
2148 g_free(filename);
2152 /* Replace all text matches in a certain range within document.
2153 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2154 * or -1 if no text was found.
2155 * scroll_to_match is whether to scroll the last replacement in view (which also
2156 * clears the selection).
2157 * Returns: the number of replacements made. */
2158 static guint
2159 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2160 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2162 gint count = 0;
2163 struct Sci_TextToFind ttf;
2164 ScintillaObject *sci;
2166 if (new_range_end != NULL)
2167 *new_range_end = -1;
2169 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2171 if (! *find_text || doc->readonly)
2172 return 0;
2174 sci = doc->editor->sci;
2176 ttf.chrg.cpMin = start;
2177 ttf.chrg.cpMax = end;
2178 ttf.lpstrText = (gchar*)find_text;
2180 sci_start_undo_action(sci);
2181 count = search_replace_range(sci, &ttf, flags, replace_text);
2182 sci_end_undo_action(sci);
2184 if (count > 0)
2185 { /* scroll last match in view, will destroy the existing selection */
2186 if (scroll_to_match)
2187 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2189 if (new_range_end != NULL)
2190 *new_range_end = ttf.chrg.cpMax;
2192 return count;
2196 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2197 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2199 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2200 gint max_column = 0, count = 0;
2201 gboolean replaced = FALSE;
2203 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2205 if (! *find_text)
2206 return;
2208 selection_start = sci_get_selection_start(doc->editor->sci);
2209 selection_end = sci_get_selection_end(doc->editor->sci);
2210 /* do we have a selection? */
2211 if ((selection_end - selection_start) == 0)
2213 utils_beep();
2214 return;
2217 selection_mode = sci_get_selection_mode(doc->editor->sci);
2218 selected_lines = sci_get_lines_selected(doc->editor->sci);
2219 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2220 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2222 gint first_line, line;
2224 sci_start_undo_action(doc->editor->sci);
2226 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2227 /* Find the last line with chars selected (not EOL char) */
2228 last_line = sci_get_line_from_position(doc->editor->sci,
2229 selection_end - editor_get_eol_char_len(doc->editor));
2230 last_line = MAX(first_line, last_line);
2231 for (line = first_line; line < (first_line + selected_lines); line++)
2233 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2234 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2236 /* skip line if there is no selection */
2237 if (line_start != INVALID_POSITION)
2239 /* don't let document_replace_range() scroll to match to keep our selection */
2240 gint new_sel_end;
2242 count += document_replace_range(doc, find_text, replace_text, flags,
2243 line_start, line_end, FALSE, &new_sel_end);
2244 if (new_sel_end != -1)
2246 replaced = TRUE;
2247 /* this gets the greatest column within the selection after replacing */
2248 max_column = MAX(max_column,
2249 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2253 sci_end_undo_action(doc->editor->sci);
2255 else /* handle normal line selection */
2257 count += document_replace_range(doc, find_text, replace_text, flags,
2258 selection_start, selection_end, TRUE, &selection_end);
2259 if (selection_end != -1)
2260 replaced = TRUE;
2263 if (replaced)
2264 { /* update the selection for the new endpoint */
2266 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2268 /* now we can scroll to the selection and destroy it because we rebuild it later */
2269 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2271 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2272 * the highest column on the last line. The wrapped selection is completely different
2273 * from the original one, so skip the selection at all */
2274 /* TODO is there a better way to handle the wrapped selection? */
2275 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2276 { /* for keeping and adjusting the selection in multi line rectangle selection we
2277 * need the last line of the original selection and the greatest column number after
2278 * replacing and set the selection end to the last line at the greatest column */
2279 sci_set_selection_start(doc->editor->sci, selection_start);
2280 sci_set_selection_end(doc->editor->sci,
2281 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2282 sci_set_selection_mode(doc->editor->sci, selection_mode);
2285 else
2287 sci_set_selection_start(doc->editor->sci, selection_start);
2288 sci_set_selection_end(doc->editor->sci, selection_end);
2291 else /* no replacements */
2292 utils_beep();
2294 show_replace_summary(doc, count, original_find_text, original_replace_text);
2298 /* returns number of replacements made. */
2299 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2300 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2302 gint len, count;
2303 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2305 if (! *find_text)
2306 return FALSE;
2308 len = sci_get_length(doc->editor->sci);
2309 count = document_replace_range(
2310 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2312 show_replace_summary(doc, count, original_find_text, original_replace_text);
2313 return count;
2318 * Parses or re-parses the document's buffer and updates the type
2319 * keywords and symbol list.
2321 * @param doc The document.
2323 void document_update_tags(GeanyDocument *doc)
2325 guchar *buffer_ptr;
2326 gsize len;
2328 g_return_if_fail(DOC_VALID(doc));
2329 g_return_if_fail(app->tm_workspace != NULL);
2331 /* early out if it's a new file or doesn't support tags */
2332 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2334 /* We must call sidebar_update_tag_list() before returning,
2335 * to ensure that the symbol list is always updated properly (e.g.
2336 * when creating a new document with a partial filename set. */
2337 sidebar_update_tag_list(doc, FALSE);
2338 return;
2341 /* create a new TM file if there isn't one yet */
2342 if (! doc->tm_file)
2344 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2345 const gchar *name;
2347 /* lookup the name rather than using filetype name to support custom filetypes */
2348 name = tm_source_file_get_lang_name(doc->file_type->lang);
2349 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2350 g_free(locale_filename);
2352 if (doc->tm_file && !tm_workspace_add_object(doc->tm_file))
2354 tm_work_object_free(doc->tm_file);
2355 doc->tm_file = NULL;
2359 /* early out if there's no work object and we couldn't create one */
2360 if (doc->tm_file == NULL)
2362 /* We must call sidebar_update_tag_list() before returning,
2363 * to ensure that the symbol list is always updated properly (e.g.
2364 * when creating a new document with a partial filename set. */
2365 sidebar_update_tag_list(doc, FALSE);
2366 return;
2369 len = sci_get_length(doc->editor->sci);
2370 /* tm_source_file_buffer_update() below don't support 0-length data,
2371 * so just empty the tags array and leave */
2372 if (len < 1)
2374 tm_tags_array_free(doc->tm_file->tags_array, FALSE);
2375 sidebar_update_tag_list(doc, FALSE);
2376 return;
2379 /* Parse Scintilla's buffer directly using TagManager
2380 * Note: this buffer *MUST NOT* be modified */
2381 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2382 tm_source_file_buffer_update(doc->tm_file, buffer_ptr, len, TRUE);
2384 sidebar_update_tag_list(doc, TRUE);
2385 document_highlight_tags(doc);
2389 /* Re-highlights type keywords without re-parsing the whole document. */
2390 void document_highlight_tags(GeanyDocument *doc)
2392 GString *keywords_str;
2393 gchar *keywords;
2394 gint keyword_idx;
2396 /* some filetypes support type keywords (such as struct names), but not
2397 * necessarily all filetypes for a particular scintilla lexer. this
2398 * tells us whether the filetype supports keywords, and if so
2399 * which index to use for the scintilla keywords set. */
2400 switch (doc->file_type->id)
2402 case GEANY_FILETYPES_C:
2403 case GEANY_FILETYPES_CPP:
2404 case GEANY_FILETYPES_CS:
2405 case GEANY_FILETYPES_D:
2406 case GEANY_FILETYPES_JAVA:
2407 case GEANY_FILETYPES_OBJECTIVEC:
2408 case GEANY_FILETYPES_VALA:
2409 case GEANY_FILETYPES_RUST:
2412 /* index of the keyword set in the Scintilla lexer, for
2413 * example in LexCPP.cxx, see "cppWordLists" global array.
2414 * TODO: this magic number should be a member of the filetype */
2415 keyword_idx = 3;
2416 break;
2418 default:
2419 return; /* early out if type keywords are not supported */
2421 if (!app->tm_workspace->work_object.tags_array)
2422 return;
2424 /* get any type keywords and tell scintilla about them
2425 * this will cause the type keywords to be colourized in scintilla */
2426 keywords_str = symbols_find_tags_as_string(app->tm_workspace->work_object.tags_array,
2427 TM_GLOBAL_TYPE_MASK, doc->file_type->lang);
2428 if (keywords_str)
2430 keywords = g_string_free(keywords_str, FALSE);
2431 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2432 g_free(keywords);
2433 queue_colourise(doc); /* force re-highlighting the entire document */
2438 static gboolean on_document_update_tag_list_idle(gpointer data)
2440 GeanyDocument *doc = data;
2442 if (! DOC_VALID(doc))
2443 return FALSE;
2445 if (! main_status.quitting)
2446 document_update_tags(doc);
2448 doc->priv->tag_list_update_source = 0;
2450 /* don't update the tags until another modification of the buffer */
2451 return FALSE;
2455 void document_update_tag_list_in_idle(GeanyDocument *doc)
2457 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2458 return;
2460 /* prevent "stacking up" callback handlers, we only need one to run soon */
2461 if (doc->priv->tag_list_update_source != 0)
2462 g_source_remove(doc->priv->tag_list_update_source);
2464 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2465 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2469 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2470 gboolean filetype_changed)
2472 g_return_if_fail(doc);
2473 if (type == NULL)
2474 type = filetypes[GEANY_FILETYPES_NONE];
2476 if (filetype_changed)
2478 doc->file_type = type;
2480 /* delete tm file object to force creation of a new one */
2481 if (doc->tm_file != NULL)
2483 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2484 doc->tm_file = NULL;
2486 /* load tags files before highlighting (some lexers highlight global typenames) */
2487 if (type->id != GEANY_FILETYPES_NONE)
2488 symbols_global_tags_loaded(type->id);
2490 highlighting_set_styles(doc->editor->sci, type);
2491 editor_set_indentation_guides(doc->editor);
2492 build_menu_update(doc);
2493 queue_colourise(doc);
2494 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2497 document_update_tags(doc);
2501 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2502 * @param doc The document to use.
2503 * @param type The filetype. */
2504 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2506 gboolean ft_changed;
2507 GeanyFiletype *old_ft;
2509 g_return_if_fail(doc);
2510 if (type == NULL)
2511 type = filetypes[GEANY_FILETYPES_NONE];
2513 old_ft = doc->file_type;
2514 geany_debug("%s : %s (%s)",
2515 (doc->file_name != NULL) ? doc->file_name : "unknown",
2516 type->name,
2517 (doc->encoding != NULL) ? doc->encoding : "unknown");
2519 ft_changed = (doc->file_type != type); /* filetype has changed */
2520 document_load_config(doc, type, ft_changed);
2522 if (ft_changed)
2524 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2526 /* assume that if previous filetype was none and the settings are the default ones, this
2527 * is the first time the filetype is carefully set, so we should apply indent settings */
2528 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2529 doc->editor->indent_type == iprefs->type &&
2530 doc->editor->indent_width == iprefs->width)
2532 document_apply_indent_settings(doc);
2533 ui_document_show_hide(doc);
2536 sidebar_openfiles_update(doc); /* to update the icon */
2537 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2542 void document_reload_config(GeanyDocument *doc)
2544 document_load_config(doc, doc->file_type, TRUE);
2549 * Sets the encoding of a document.
2550 * This function only set the encoding of the %document, it does not any conversions. The new
2551 * encoding is used when e.g. saving the file.
2553 * @param doc The document to use.
2554 * @param new_encoding The encoding to be set for the document.
2556 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2558 if (doc == NULL || new_encoding == NULL ||
2559 utils_str_equal(new_encoding, doc->encoding))
2560 return;
2562 g_free(doc->encoding);
2563 doc->encoding = g_strdup(new_encoding);
2565 ui_update_statusbar(doc, -1);
2566 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2567 encodings_is_unicode_charset(doc->encoding));
2571 /* own Undo / Redo implementation to be able to undo / redo changes
2572 * to the encoding or the Unicode BOM (which are Scintilla independet).
2573 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2575 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2576 void document_undo_clear(GeanyDocument *doc)
2578 undo_action *a;
2580 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2582 a = g_trash_stack_pop(&doc->priv->undo_actions);
2583 if (G_LIKELY(a != NULL))
2585 switch (a->type)
2587 case UNDO_ENCODING: g_free(a->data); break;
2588 default: break;
2590 g_free(a);
2593 doc->priv->undo_actions = NULL;
2595 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2597 a = g_trash_stack_pop(&doc->priv->redo_actions);
2598 if (G_LIKELY(a != NULL))
2600 switch (a->type)
2602 case UNDO_ENCODING: g_free(a->data); break;
2603 default: break;
2605 g_free(a);
2608 doc->priv->redo_actions = NULL;
2610 if (! main_status.quitting && doc->editor != NULL)
2611 document_set_text_changed(doc, FALSE);
2615 /* note: this is called on SCN_MODIFIED notifications */
2616 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2618 undo_action *action;
2620 g_return_if_fail(doc != NULL);
2622 action = g_new0(undo_action, 1);
2623 action->type = type;
2624 action->data = data;
2626 g_trash_stack_push(&doc->priv->undo_actions, action);
2628 /* avoid unnecessary redraws */
2629 if (type != UNDO_SCINTILLA || !doc->changed)
2630 document_set_text_changed(doc, TRUE);
2632 ui_update_popup_reundo_items(doc);
2636 gboolean document_can_undo(GeanyDocument *doc)
2638 g_return_val_if_fail(doc != NULL, FALSE);
2640 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2641 return TRUE;
2642 else
2643 return FALSE;
2647 static void update_changed_state(GeanyDocument *doc)
2649 doc->changed =
2650 (sci_is_modified(doc->editor->sci) ||
2651 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2652 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2653 document_set_text_changed(doc, doc->changed);
2657 void document_undo(GeanyDocument *doc)
2659 undo_action *action;
2661 g_return_if_fail(doc != NULL);
2663 action = g_trash_stack_pop(&doc->priv->undo_actions);
2665 if (G_UNLIKELY(action == NULL))
2667 /* fallback, should not be necessary */
2668 geany_debug("%s: fallback used", G_STRFUNC);
2669 sci_undo(doc->editor->sci);
2671 else
2673 switch (action->type)
2675 case UNDO_SCINTILLA:
2677 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2679 sci_undo(doc->editor->sci);
2680 break;
2682 case UNDO_BOM:
2684 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2686 doc->has_bom = GPOINTER_TO_INT(action->data);
2687 ui_update_statusbar(doc, -1);
2688 ui_document_show_hide(doc);
2689 break;
2691 case UNDO_ENCODING:
2693 /* use the "old" encoding */
2694 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2696 document_set_encoding(doc, (const gchar*)action->data);
2698 ignore_callback = TRUE;
2699 encodings_select_radio_item((const gchar*)action->data);
2700 ignore_callback = FALSE;
2702 g_free(action->data);
2703 break;
2705 default: break;
2708 g_free(action); /* free the action which was taken from the stack */
2710 update_changed_state(doc);
2711 ui_update_popup_reundo_items(doc);
2715 gboolean document_can_redo(GeanyDocument *doc)
2717 g_return_val_if_fail(doc != NULL, FALSE);
2719 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2720 return TRUE;
2721 else
2722 return FALSE;
2726 void document_redo(GeanyDocument *doc)
2728 undo_action *action;
2730 g_return_if_fail(doc != NULL);
2732 action = g_trash_stack_pop(&doc->priv->redo_actions);
2734 if (G_UNLIKELY(action == NULL))
2736 /* fallback, should not be necessary */
2737 geany_debug("%s: fallback used", G_STRFUNC);
2738 sci_redo(doc->editor->sci);
2740 else
2742 switch (action->type)
2744 case UNDO_SCINTILLA:
2746 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2748 sci_redo(doc->editor->sci);
2749 break;
2751 case UNDO_BOM:
2753 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2755 doc->has_bom = GPOINTER_TO_INT(action->data);
2756 ui_update_statusbar(doc, -1);
2757 ui_document_show_hide(doc);
2758 break;
2760 case UNDO_ENCODING:
2762 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2764 document_set_encoding(doc, (const gchar*)action->data);
2766 ignore_callback = TRUE;
2767 encodings_select_radio_item((const gchar*)action->data);
2768 ignore_callback = FALSE;
2770 g_free(action->data);
2771 break;
2773 default: break;
2776 g_free(action); /* free the action which was taken from the stack */
2778 update_changed_state(doc);
2779 ui_update_popup_reundo_items(doc);
2783 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2785 undo_action *action;
2787 g_return_if_fail(doc != NULL);
2789 action = g_new0(undo_action, 1);
2790 action->type = type;
2791 action->data = data;
2793 g_trash_stack_push(&doc->priv->redo_actions, action);
2795 if (type != UNDO_SCINTILLA || !doc->changed)
2796 document_set_text_changed(doc, TRUE);
2798 ui_update_popup_reundo_items(doc);
2802 enum
2804 STATUS_CHANGED,
2805 #ifdef USE_GIO_FILEMON
2806 STATUS_DISK_CHANGED,
2807 #endif
2808 STATUS_READONLY
2810 static struct
2812 const gchar *name;
2813 GdkColor color;
2814 gboolean loaded;
2815 } document_status_styles[] = {
2816 { "geany-document-status-changed", {0}, FALSE },
2817 #ifdef USE_GIO_FILEMON
2818 { "geany-document-status-disk-changed", {0}, FALSE },
2819 #endif
2820 { "geany-document-status-readonly", {0}, FALSE }
2824 static gint document_get_status_id(GeanyDocument *doc)
2826 if (doc->changed)
2827 return STATUS_CHANGED;
2828 #ifdef USE_GIO_FILEMON
2829 else if (doc->priv->file_disk_status == FILE_CHANGED)
2830 return STATUS_DISK_CHANGED;
2831 #endif
2832 else if (doc->readonly)
2833 return STATUS_READONLY;
2835 return -1;
2839 /* returns an identifier that is to be set as a widget name or class to get it styled
2840 * depending on the document status (changed, readonly, etc.)
2841 * a NULL return value means default (unchanged) style */
2842 const gchar *document_get_status_widget_class(GeanyDocument *doc)
2844 gint status;
2846 g_return_val_if_fail(doc != NULL, NULL);
2848 status = document_get_status_id(doc);
2849 if (status < 0)
2850 return NULL;
2851 else
2852 return document_status_styles[status].name;
2857 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2858 * Returned colors are red if the document has changes, green if the document is read-only
2859 * or simply @c NULL if the document is unmodified but writable.
2861 * @param doc The document to use.
2863 * @return The color for the document or @c NULL if the default color should be used. The color
2864 * object is owned by Geany and should not be modified or freed.
2866 * @since 0.16
2868 const GdkColor *document_get_status_color(GeanyDocument *doc)
2870 gint status;
2872 g_return_val_if_fail(doc != NULL, NULL);
2874 status = document_get_status_id(doc);
2875 if (status < 0)
2876 return NULL;
2877 if (! document_status_styles[status].loaded)
2879 #if GTK_CHECK_VERSION(3, 0, 0)
2880 GdkRGBA color;
2881 GtkWidgetPath *path = gtk_widget_path_new();
2882 GtkStyleContext *ctx = gtk_style_context_new();
2883 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
2884 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
2885 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
2886 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
2887 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
2888 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
2889 gtk_style_context_set_path(ctx, path);
2890 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
2891 document_status_styles[status].color.red = 0xffff * color.red;
2892 document_status_styles[status].color.green = 0xffff * color.green;
2893 document_status_styles[status].color.blue = 0xffff * color.blue;
2894 document_status_styles[status].loaded = TRUE;
2895 gtk_widget_path_unref(path);
2896 g_object_unref(ctx);
2897 #else
2898 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
2899 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
2900 document_status_styles[status].name, NULL);
2901 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
2903 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
2904 document_status_styles[status].loaded = TRUE;
2905 g_free(path);
2906 #endif
2908 return &document_status_styles[status].color;
2912 /** Accessor function for @ref documents_array items.
2913 * @warning Always check the returned document is valid (@c doc->is_valid).
2914 * @param idx @c documents_array index.
2915 * @return The document, or @c NULL if @a idx is out of range.
2917 * @since 0.16
2919 GeanyDocument *document_index(gint idx)
2921 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2925 /* create a new file and copy file content and properties */
2926 G_MODULE_EXPORT void on_clone1_activate(GtkMenuItem *menuitem, gpointer user_data)
2928 GeanyDocument *old_doc = document_get_current();
2930 if (old_doc)
2931 document_clone(old_doc);
2935 GeanyDocument *document_clone(GeanyDocument *old_doc)
2937 gchar *text;
2938 GeanyDocument *doc;
2939 ScintillaObject *old_sci;
2941 g_return_val_if_fail(old_doc, NULL);
2942 old_sci = old_doc->editor->sci;
2943 if (sci_has_selection(old_sci))
2944 text = sci_get_selection_contents(old_sci);
2945 else
2946 text = sci_get_contents(old_sci, -1);
2948 doc = document_new_file(NULL, old_doc->file_type, text);
2949 g_free(text);
2950 document_set_text_changed(doc, TRUE);
2952 /* copy file properties */
2953 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2954 doc->editor->line_breaking = old_doc->editor->line_breaking;
2955 doc->editor->auto_indent = old_doc->editor->auto_indent;
2956 editor_set_indent(doc->editor, old_doc->editor->indent_type,
2957 old_doc->editor->indent_width);
2958 doc->readonly = old_doc->readonly;
2959 doc->has_bom = old_doc->has_bom;
2960 doc->priv->protected = 0;
2961 document_set_encoding(doc, old_doc->encoding);
2962 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2963 sci_set_readonly(doc->editor->sci, doc->readonly);
2965 /* update ui */
2966 ui_document_show_hide(doc);
2967 return doc;
2971 /* @note If successful, this should always be followed up with a call to
2972 * document_close_all().
2973 * @return TRUE if all files were saved or had their changes discarded. */
2974 gboolean document_account_for_unsaved(void)
2976 guint i, p, page_count;
2978 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2979 /* iterate over documents in tabs order */
2980 for (p = 0; p < page_count; p++)
2982 GeanyDocument *doc = document_get_from_page(p);
2984 if (DOC_VALID(doc) && doc->changed)
2986 if (! dialogs_show_unsaved_file(doc))
2987 return FALSE;
2990 /* all documents should now be accounted for, so ignore any changes */
2991 foreach_document (i)
2993 documents[i]->changed = FALSE;
2995 return TRUE;
2999 static void force_close_all(void)
3001 guint i, len = documents_array->len;
3003 /* check all documents have been accounted for */
3004 for (i = 0; i < len; i++)
3006 if (documents[i]->is_valid)
3008 g_return_if_fail(!documents[i]->changed);
3011 main_status.closing_all = TRUE;
3013 foreach_document(i)
3015 document_close(documents[i]);
3018 main_status.closing_all = FALSE;
3022 gboolean document_close_all(void)
3024 if (! document_account_for_unsaved())
3025 return FALSE;
3027 force_close_all();
3029 return TRUE;
3033 /* *
3034 * Shows a message related to a document.
3036 * Use this whenever the user needs to see a document-related message,
3037 * for example when the file was externally modified or deleted.
3039 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3040 * @a response_1 response will be the default for the @c GtkInfoBar or
3041 * @c GtkDialog.
3043 * @param doc @c GeanyDocument.
3044 * @param msgtype The type of message.
3045 * @param response_cb A callback function called when there's a response.
3046 * @param btn_1 The first action area button.
3047 * @param response_1 The response for @a btn_1.
3048 * @param btn_2 The second action area button.
3049 * @param response_2 The response for @a btn_2.
3050 * @param btn_3 The third action area button.
3051 * @param response_3 The response for @a btn_3.
3052 * @param extra_text Text to show below the main message.
3053 * @param format The text format for the main message.
3054 * @param ... Used with @a format as in @c printf.
3056 * @since 1.25
3057 * */
3058 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3059 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3060 const gchar *btn_1, GtkResponseType response_1,
3061 const gchar *btn_2, GtkResponseType response_2,
3062 const gchar *btn_3, GtkResponseType response_3,
3063 const gchar *extra_text, const gchar *format, ...)
3065 va_list args;
3066 gchar *text, *markup;
3067 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3068 GtkWidget *info_widget, *ok_button, *cancel_button, *parent;
3069 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook),
3070 document_get_notebook_page(doc));
3072 va_start(args, format);
3073 text = g_strdup_vprintf(format, args);
3074 va_end(args);
3076 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3077 g_free(text);
3079 info_widget = gtk_info_bar_new();
3080 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3081 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3083 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3085 if (btn_1)
3086 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3087 if (btn_2)
3088 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3089 if (btn_3)
3090 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3092 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3094 label = geany_wrap_label_new(NULL);
3096 gtk_label_set_markup(GTK_LABEL(label), markup);
3097 g_free(markup);
3099 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3100 g_signal_connect_after(info_widget, "response", G_CALLBACK(gtk_widget_destroy), NULL);
3102 hbox = gtk_hbox_new(FALSE, 12);
3103 gtk_container_add(GTK_CONTAINER(content_area), hbox);
3105 switch (msgtype)
3107 case GTK_MESSAGE_INFO:
3108 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3109 break;
3110 case GTK_MESSAGE_WARNING:
3111 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3112 break;
3113 case GTK_MESSAGE_QUESTION:
3114 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3115 break;
3116 case GTK_MESSAGE_ERROR:
3117 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3118 break;
3119 default:
3120 icon = NULL;
3121 break;
3124 if (icon)
3125 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3127 if (extra_text)
3129 vbox = gtk_vbox_new(FALSE, 6);
3130 extra_label = geany_wrap_label_new(extra_text);
3131 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3132 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3133 gtk_container_add(GTK_CONTAINER(hbox), vbox);
3135 else
3136 gtk_container_add(GTK_CONTAINER(hbox), label);
3138 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3140 gtk_widget_show_all(info_widget);
3142 return info_widget;
3145 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3147 unprotect_document(doc);
3149 if (response_id == GTK_RESPONSE_ACCEPT)
3150 document_reload_file(doc, doc->encoding);
3152 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3156 static void monitor_reload_file(GeanyDocument *doc)
3158 gchar *base_name = g_path_get_basename(doc->file_name);
3160 /* show this message only once */
3161 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3163 GtkWidget *bar;
3165 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3166 _("_Reload"), GTK_RESPONSE_ACCEPT,
3167 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3168 NULL, GTK_RESPONSE_NONE,
3169 _("Do you want to reload it?"),
3170 _("The file '%s' on the disk is more recent than the current buffer."),
3171 base_name);
3173 protect_document(doc);
3174 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3176 g_free(base_name);
3180 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3181 gint response_id,
3182 GeanyDocument *doc)
3184 gboolean file_saved = FALSE;
3186 unprotect_document(doc);
3188 if (response_id == GTK_RESPONSE_ACCEPT)
3189 file_saved = dialogs_show_save_as();
3191 if (!file_saved)
3193 document_set_text_changed(doc, TRUE);
3194 /* don't prompt more than once */
3195 SETPTR(doc->real_path, NULL);
3198 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3202 static void monitor_resave_missing_file(GeanyDocument *doc)
3204 GtkWidget *bar;
3206 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3208 GtkWidget *bar;
3209 bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3210 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3211 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3213 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3214 on_monitor_resave_missing_file_response,
3215 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
3216 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3217 NULL, GTK_RESPONSE_NONE,
3218 _("Try to resave the file?"),
3219 _("File \"%s\" was not found on disk!"),
3220 doc->file_name);
3222 protect_document(doc);
3223 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3228 /* Set force to force a disk check, otherwise it is ignored if there was a check
3229 * in the last file_prefs.disk_check_timeout seconds.
3230 * @return @c TRUE if the file has changed. */
3231 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3233 gboolean ret = FALSE;
3234 gboolean use_gio_filemon;
3235 time_t cur_time = 0;
3236 struct stat st;
3237 gchar *locale_filename;
3238 FileDiskStatus old_status;
3240 g_return_val_if_fail(doc != NULL, FALSE);
3242 /* ignore remote files and documents that have never been saved to disk */
3243 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3244 || doc->real_path == NULL || doc->priv->is_remote)
3245 return FALSE;
3247 use_gio_filemon = (doc->priv->monitor != NULL);
3249 if (use_gio_filemon)
3251 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3252 return FALSE;
3254 else
3256 cur_time = time(NULL);
3257 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3258 return FALSE;
3260 doc->priv->last_check = cur_time;
3263 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3264 if (g_stat(locale_filename, &st) != 0)
3266 monitor_resave_missing_file(doc);
3267 /* doc may be closed now */
3268 ret = TRUE;
3270 else if (! use_gio_filemon && /* ignore check when using GIO */
3271 doc->priv->mtime > cur_time)
3273 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3274 /* Note: on Windows st.st_mtime can be newer than cur_time */
3276 else if (doc->priv->mtime < st.st_mtime)
3278 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3279 doc->priv->mtime = st.st_mtime;
3280 monitor_reload_file(doc);
3281 /* doc may be closed now */
3282 ret = TRUE;
3284 g_free(locale_filename);
3286 if (DOC_VALID(doc))
3287 { /* doc can get invalid when a document was closed */
3288 old_status = doc->priv->file_disk_status;
3289 doc->priv->file_disk_status = FILE_OK;
3290 if (old_status != doc->priv->file_disk_status)
3291 ui_update_tab_status(doc);
3293 return ret;
3297 /** Compares documents by their display names.
3298 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3299 * @note 'Display name' means the base name of the document's filename.
3301 * @param a @c GeanyDocument**.
3302 * @param b @c GeanyDocument**.
3303 * @warning The arguments take the address of each document pointer.
3304 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3306 * @since 0.21
3308 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3310 GeanyDocument *doc_a = *((GeanyDocument**) a);
3311 GeanyDocument *doc_b = *((GeanyDocument**) b);
3312 gchar *base_name_a, *base_name_b;
3313 gint result;
3315 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3316 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3318 result = strcmp(base_name_a, base_name_b);
3320 g_free(base_name_a);
3321 g_free(base_name_b);
3323 return result;
3327 /** Compares documents by their tab order.
3328 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3330 * @param a @c GeanyDocument**.
3331 * @param b @c GeanyDocument**.
3332 * @warning The arguments take the address of each document pointer.
3333 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3335 * @since 0.21 (GEANY_API_VERSION 209)
3337 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3339 GeanyDocument *doc_a = *((GeanyDocument**) a);
3340 GeanyDocument *doc_b = *((GeanyDocument**) b);
3341 gint notebook_position_doc_a;
3342 gint notebook_position_doc_b;
3344 notebook_position_doc_a = document_get_notebook_page(doc_a);
3345 notebook_position_doc_b = document_get_notebook_page(doc_b);
3347 if (notebook_position_doc_a < notebook_position_doc_b)
3348 return -1;
3349 if (notebook_position_doc_a > notebook_position_doc_b)
3350 return 1;
3351 /* equality */
3352 return 0;
3356 /** Compares documents by their tab order, in reverse order.
3357 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3359 * @param a @c GeanyDocument**.
3360 * @param b @c GeanyDocument**.
3361 * @warning The arguments take the address of each document pointer.
3362 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3364 * @since 0.21 (GEANY_API_VERSION 209)
3366 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3368 GeanyDocument *doc_a = *((GeanyDocument**) a);
3369 GeanyDocument *doc_b = *((GeanyDocument**) b);
3370 gint notebook_position_doc_a;
3371 gint notebook_position_doc_b;
3373 notebook_position_doc_a = document_get_notebook_page(doc_a);
3374 notebook_position_doc_b = document_get_notebook_page(doc_b);
3376 if (notebook_position_doc_a < notebook_position_doc_b)
3377 return 1;
3378 if (notebook_position_doc_a > notebook_position_doc_b)
3379 return -1;
3380 /* equality */
3381 return 0;
3385 void document_grab_focus(GeanyDocument *doc)
3387 g_return_if_fail(doc != NULL);
3389 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));