Update HACKING for changed doc generation instructions
[geany-mirror.git] / src / document.c
blob317d52a1b2e394f2f3a5dc1a6b393cbbc51ddd5c
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"
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"
55 #include "win32.h"
57 #include "gtkcompat.h"
59 #ifdef HAVE_SYS_TIME_H
60 # include <sys/time.h>
61 #endif
62 #include <time.h>
64 #include <unistd.h>
65 #include <string.h>
66 #include <errno.h>
68 #ifdef HAVE_SYS_TYPES_H
69 # include <sys/types.h>
70 #endif
72 #include <stdlib.h>
74 /* gstdio.h also includes sys/stat.h */
75 #include <glib/gstdio.h>
77 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
78 /*#define USE_GIO_FILEMON 1*/
79 #include <gio/gio.h>
81 #include <gdk/gdkkeysyms.h>
83 GeanyFilePrefs file_prefs;
86 /** Dynamic array of GeanyDocument pointers.
87 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
88 * to a document over time, but it may represent a different
89 * document later on, or may have been closed and become invalid.
91 * @warning You must check @c GeanyDocument::is_valid when iterating over this array.
92 * This is done automatically if you use the foreach_document() macro.
94 * @note
95 * Never assume that the order of document pointers is the same as the order of notebook tabs.
96 * One reason is that notebook tabs can be reordered.
97 * Use @c document_get_from_page() to lookup a document from a notebook tab number.
99 * @see documents. */
100 GPtrArray *documents_array = NULL;
103 /* an undo action, also used for redo actions */
104 typedef struct
106 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
107 guint type; /* to identify the action */
108 gpointer *data; /* the old value (before the change), in case of a redo action
109 * it contains the new value */
110 } undo_action;
113 static void document_undo_clear(GeanyDocument *doc);
114 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
115 static gboolean remove_page(guint page_num);
116 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
117 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
118 const gchar *btn_1, GtkResponseType response_1,
119 const gchar *btn_2, GtkResponseType response_2,
120 const gchar *btn_3, GtkResponseType response_3,
121 const gchar *extra_text, const gchar *format, ...) G_GNUC_PRINTF(11, 12);
125 * Finds a document whose @c real_path field matches the given filename.
127 * @param realname The filename to search, which should be identical to the
128 * string returned by @c tm_get_real_path().
130 * @return The matching document, or @c NULL.
131 * @note This is only really useful when passing a @c TMWorkObject::file_name.
132 * @see GeanyDocument::real_path.
133 * @see document_find_by_filename().
135 * @since 0.15
137 GeanyDocument* document_find_by_real_path(const gchar *realname)
139 guint i;
141 if (! realname)
142 return NULL; /* file doesn't exist on disk */
144 for (i = 0; i < documents_array->len; i++)
146 GeanyDocument *doc = documents[i];
148 if (! doc->is_valid || ! doc->real_path)
149 continue;
151 if (utils_filenamecmp(realname, doc->real_path) == 0)
153 return doc;
156 return NULL;
160 /* dereference symlinks, /../ junk in path and return locale encoding */
161 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
163 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
164 gchar *realname = tm_get_real_path(locale_name);
166 g_free(locale_name);
167 return realname;
172 * Finds a document with the given filename.
173 * This matches either an exact GeanyDocument::file_name string, or variant
174 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
175 * match @c "/name").
177 * @param utf8_filename The filename to search (in UTF-8 encoding).
179 * @return The matching document, or @c NULL.
180 * @see document_find_by_real_path().
182 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
184 guint i;
185 GeanyDocument *doc;
186 gchar *realname;
188 g_return_val_if_fail(utf8_filename != NULL, NULL);
190 /* First search GeanyDocument::file_name, so we can find documents with a
191 * filename set but not saved on disk, like vcdiff produces */
192 for (i = 0; i < documents_array->len; i++)
194 doc = documents[i];
196 if (! doc->is_valid || doc->file_name == NULL)
197 continue;
199 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
201 return doc;
204 /* Now try matching based on the realpath(), which is unique per file on disk */
205 realname = get_real_path_from_utf8(utf8_filename);
206 doc = document_find_by_real_path(realname);
207 g_free(realname);
208 return doc;
212 /* returns the document which has sci, or NULL. */
213 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
215 guint i;
217 g_return_val_if_fail(sci != NULL, NULL);
219 for (i = 0; i < documents_array->len; i++)
221 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
222 return documents[i];
224 return NULL;
228 /** Gets the notebook page index for a document.
229 * @param doc The document.
230 * @return The index.
231 * @since 0.19 */
232 gint document_get_notebook_page(GeanyDocument *doc)
234 GtkWidget *parent;
235 GtkWidget *child;
237 g_return_val_if_fail(doc != NULL, -1);
239 child = GTK_WIDGET(doc->editor->sci);
240 parent = gtk_widget_get_parent(child);
241 /* search for the direct notebook child, mirroring document_get_from_page() */
242 while (parent && ! GTK_IS_NOTEBOOK(parent))
244 child = parent;
245 parent = gtk_widget_get_parent(child);
248 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
253 * Recursively searches a containers children until it finds a
254 * Scintilla widget, or NULL if one was not found.
256 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
258 ScintillaObject *sci = NULL;
259 GList *children, *iter;
261 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
263 children = gtk_container_get_children(GTK_CONTAINER(container));
264 for (iter = children; iter != NULL; iter = g_list_next(iter))
266 if (IS_SCINTILLA(iter->data))
268 sci = SCINTILLA(iter->data);
269 break;
271 else if (GTK_IS_CONTAINER(iter->data))
273 sci = locate_sci_in_container(iter->data);
274 if (IS_SCINTILLA(sci))
275 break;
276 sci = NULL;
279 g_list_free(children);
281 return sci;
286 * Finds the document for the given notebook page @a page_num.
288 * @param page_num The notebook page number to search.
290 * @return The corresponding document for the given notebook page, or @c NULL.
292 GeanyDocument *document_get_from_page(guint page_num)
294 GtkWidget *parent;
295 ScintillaObject *sci;
297 if (page_num >= documents_array->len)
298 return NULL;
300 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
301 g_return_val_if_fail(GTK_IS_BOX(parent), NULL);
303 sci = locate_sci_in_container(parent);
304 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
306 return document_find_by_sci(sci);
311 * Finds the current document.
313 * @return A pointer to the current document or @c NULL if there are no opened documents.
315 GeanyDocument *document_get_current(void)
317 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
319 if (cur_page == -1)
320 return NULL;
321 else
322 return document_get_from_page((guint) cur_page);
326 void document_init_doclist(void)
328 documents_array = g_ptr_array_new();
332 void document_finalize(void)
334 guint i;
336 for (i = 0; i < documents_array->len; i++)
337 g_free(documents[i]);
338 g_ptr_array_free(documents_array, TRUE);
343 * Returns the last part of the filename of the given GeanyDocument. The result is also
344 * truncated to a maximum of @a length characters in case the filename is very long.
346 * @param doc The document to use.
347 * @param length The length of the resulting string or -1 to use a default value.
349 * @return The ellipsized last part of the filename of @a doc, should be freed when no
350 * longer needed.
352 * @since 0.17
354 /* TODO make more use of this */
355 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
357 gchar *base_name, *short_name;
359 g_return_val_if_fail(doc != NULL, NULL);
361 if (length < 0)
362 length = 30;
364 base_name = g_path_get_basename(DOC_FILENAME(doc));
365 short_name = utils_str_middle_truncate(base_name, (guint)length);
367 g_free(base_name);
369 return short_name;
373 void document_update_tab_label(GeanyDocument *doc)
375 gchar *short_name;
376 GtkWidget *parent;
378 g_return_if_fail(doc != NULL);
380 short_name = document_get_basename_for_display(doc, -1);
382 /* we need to use the event box for the tooltip, labels don't get the necessary events */
383 parent = gtk_widget_get_parent(doc->priv->tab_label);
384 parent = gtk_widget_get_parent(parent);
386 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
388 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
390 g_free(short_name);
395 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
396 * according to the document's save state.
397 * This is called by Geany mostly when opening or saving files.
399 * @param doc The document to use.
400 * @param changed Whether the document state should indicate changes have been made.
402 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
404 g_return_if_fail(doc != NULL);
406 doc->changed = changed;
408 if (! main_status.quitting)
410 ui_update_tab_status(doc);
411 ui_save_buttons_toggle(changed);
412 ui_set_window_title(doc);
413 ui_update_statusbar(doc, -1);
418 /* returns the next free place in the document list,
419 * or -1 if the documents_array is full */
420 static gint document_get_new_idx(void)
422 guint i;
424 for (i = 0; i < documents_array->len; i++)
426 if (documents[i]->editor == NULL)
428 return (gint) i;
431 return -1;
435 static void queue_colourise(GeanyDocument *doc)
437 /* Colourise the editor before it is next drawn */
438 doc->priv->colourise_needed = TRUE;
440 /* If the editor doesn't need drawing (e.g. after saving the current
441 * document), we need to force a redraw, so the expose event is triggered.
442 * This ensures we don't start colourising before all documents are opened/saved,
443 * only once the editor is drawn. */
444 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
448 #ifdef USE_GIO_FILEMON
449 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
450 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
451 GeanyDocument *doc)
453 g_return_if_fail(doc != NULL);
455 if (file_prefs.disk_check_timeout == 0)
456 return;
458 geany_debug("%s: event: %d previous file status: %d",
459 G_STRFUNC, event, doc->priv->file_disk_status);
460 switch (event)
462 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
464 if (doc->priv->file_disk_status == FILE_IGNORE)
465 doc->priv->file_disk_status = FILE_OK;
466 else
467 doc->priv->file_disk_status = FILE_CHANGED;
468 g_message("%s: FILE_CHANGED", G_STRFUNC);
469 break;
471 case G_FILE_MONITOR_EVENT_DELETED:
473 doc->priv->file_disk_status = FILE_CHANGED;
474 g_message("%s: FILE_MISSING", G_STRFUNC);
475 break;
477 default:
478 break;
480 if (doc->priv->file_disk_status != FILE_OK)
482 ui_update_tab_status(doc);
485 #endif
488 static void document_stop_file_monitoring(GeanyDocument *doc)
490 g_return_if_fail(doc != NULL);
492 if (doc->priv->monitor != NULL)
494 g_object_unref(doc->priv->monitor);
495 doc->priv->monitor = NULL;
500 static void monitor_file_setup(GeanyDocument *doc)
502 g_return_if_fail(doc != NULL);
503 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
504 * doesn't work at all for remote files and legacy polling is too slow. */
505 if (! doc->priv->is_remote)
507 #ifdef USE_GIO_FILEMON
508 gchar *locale_filename;
510 /* stop any previous monitoring */
511 document_stop_file_monitoring(doc);
513 locale_filename = utils_get_locale_from_utf8(doc->file_name);
514 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
516 /* get a file monitor and connect to the 'changed' signal */
517 GFile *file = g_file_new_for_path(locale_filename);
518 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
519 g_signal_connect(doc->priv->monitor, "changed",
520 G_CALLBACK(monitor_file_changed_cb), doc);
522 /* we set the rate limit according to the GUI pref but it's most probably not used */
523 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
525 g_object_unref(file);
527 g_free(locale_filename);
528 #endif
530 doc->priv->file_disk_status = FILE_OK;
534 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
536 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
537 if (DOC_VALID(doc))
539 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
540 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
542 if (source_widget == NULL)
543 source_widget = doc->priv->tag_tree;
545 if (focusw == source_widget)
546 gtk_widget_grab_focus(sci);
551 static gboolean on_idle_focus(gpointer doc)
553 document_try_focus(doc, NULL);
554 return FALSE;
558 /* Creates a new document and editor, adding a tab in the notebook.
559 * @return The created document */
560 static GeanyDocument *document_create(const gchar *utf8_filename)
562 GeanyDocument *doc;
563 gint new_idx;
564 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
566 if (cur_pages == 1)
568 doc = document_get_current();
569 /* remove the empty document first */
570 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
571 /* prevent immediately opening another new doc with
572 * new_document_after_close pref */
573 remove_page(0);
576 new_idx = document_get_new_idx();
577 if (new_idx == -1) /* expand the array, no free places */
579 doc = g_new0(GeanyDocument, 1);
581 new_idx = documents_array->len;
582 g_ptr_array_add(documents_array, doc);
585 doc = documents[new_idx];
587 /* initialize default document settings */
588 doc->priv = g_new0(GeanyDocumentPrivate, 1);
589 doc->index = new_idx;
590 doc->file_name = g_strdup(utf8_filename);
591 doc->editor = editor_create(doc);
592 #ifndef USE_GIO_FILEMON
593 doc->priv->last_check = time(NULL);
594 #endif
596 sidebar_openfiles_add(doc); /* sets doc->iter */
598 notebook_new_tab(doc);
600 /* select document in sidebar */
602 GtkTreeSelection *sel;
604 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
605 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
608 ui_document_buttons_update();
610 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
611 return doc;
616 * Closes the given document.
618 * @param doc The document to remove.
620 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
622 * @since 0.15
624 gboolean document_close(GeanyDocument *doc)
626 g_return_val_if_fail(doc, FALSE);
628 return document_remove_page(document_get_notebook_page(doc));
632 /* Call document_remove_page() instead, this is only needed for document_create()
633 * to prevent re-opening a new document when the last document is closed (if enabled). */
634 static gboolean remove_page(guint page_num)
636 GeanyDocument *doc = document_get_from_page(page_num);
638 g_return_val_if_fail(doc != NULL, FALSE);
640 if (doc->changed && ! dialogs_show_unsaved_file(doc))
641 return FALSE;
643 /* tell any plugins that the document is about to be closed */
644 g_signal_emit_by_name(geany_object, "document-close", doc);
646 /* Checking real_path makes it likely the file exists on disk */
647 if (! main_status.closing_all && doc->real_path != NULL)
648 ui_add_recent_document(doc);
650 doc->is_valid = FALSE;
652 if (main_status.quitting)
654 /* we need to destroy the ScintillaWidget so our handlers on it are
655 * disconnected before we free any data they may use (like the editor).
656 * when not quitting, this is handled by removing the notebook page. */
657 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
659 else
661 notebook_remove_page(page_num);
662 sidebar_remove_document(doc);
663 navqueue_remove_file(doc->file_name);
664 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
666 g_free(doc->encoding);
667 g_free(doc->priv->saved_encoding.encoding);
668 g_free(doc->file_name);
669 g_free(doc->real_path);
670 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
672 if (doc->priv->tag_tree)
673 gtk_widget_destroy(doc->priv->tag_tree);
675 editor_destroy(doc->editor);
676 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
678 document_stop_file_monitoring(doc);
680 document_undo_clear(doc);
682 g_free(doc->priv);
684 /* reset document settings to defaults for re-use */
685 memset(doc, 0, sizeof(GeanyDocument));
687 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
689 sidebar_update_tag_list(NULL, FALSE);
690 ui_set_window_title(NULL);
691 ui_save_buttons_toggle(FALSE);
692 ui_update_popup_reundo_items(NULL);
693 ui_document_buttons_update();
694 build_menu_update(NULL);
696 return TRUE;
701 * Removes the given notebook tab at @a page_num and clears all related information
702 * in the document list.
704 * @param page_num The notebook page number to remove.
706 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
708 gboolean document_remove_page(guint page_num)
710 gboolean done = remove_page(page_num);
712 if (done && ui_prefs.new_document_after_close)
713 document_new_file_if_non_open();
715 return done;
719 /* used to keep a record of the unchanged document state encoding */
720 static void store_saved_encoding(GeanyDocument *doc)
722 g_free(doc->priv->saved_encoding.encoding);
723 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
724 doc->priv->saved_encoding.has_bom = doc->has_bom;
728 /* Opens a new empty document only if there are no other documents open */
729 GeanyDocument *document_new_file_if_non_open(void)
731 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
732 return document_new_file(NULL, NULL, NULL);
734 return NULL;
739 * Creates a new document.
740 * Line endings in @a text will be converted to the default setting.
741 * Afterwards, the @c "document-new" signal is emitted for plugins.
743 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
744 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
745 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
747 * @return The new document.
749 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
751 GeanyDocument *doc;
753 if (utf8_filename && g_path_is_absolute(utf8_filename))
755 gchar *tmp;
756 tmp = utils_strdupa(utf8_filename); /* work around const */
757 utils_tidy_path(tmp);
758 utf8_filename = tmp;
760 doc = document_create(utf8_filename);
762 g_assert(doc != NULL);
764 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
765 if (text)
767 GString *template = g_string_new(text);
768 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
770 sci_set_text(doc->editor->sci, template->str);
771 g_string_free(template, TRUE);
773 else
774 sci_clear_all(doc->editor->sci);
776 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
778 sci_set_undo_collection(doc->editor->sci, TRUE);
779 sci_empty_undo_buffer(doc->editor->sci);
781 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
782 /* store the opened encoding for undo/redo */
783 store_saved_encoding(doc);
785 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
786 ft = filetypes_detect_from_document(doc);
788 document_set_filetype(doc, ft); /* also re-parses tags */
790 ui_set_window_title(doc);
791 build_menu_update(doc);
792 document_set_text_changed(doc, FALSE);
793 ui_document_show_hide(doc); /* update the document menu */
795 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
796 /* bring it in front, jump to the start and grab the focus */
797 editor_goto_pos(doc->editor, 0, FALSE);
798 document_try_focus(doc, NULL);
800 #ifdef USE_GIO_FILEMON
801 monitor_file_setup(doc);
802 #else
803 doc->priv->mtime = time(NULL);
804 #endif
806 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
807 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
809 g_signal_emit_by_name(geany_object, "document-new", doc);
811 msgwin_status_add(_("New file \"%s\" opened."),
812 DOC_FILENAME(doc));
814 return doc;
819 * Opens a document specified by @a locale_filename.
820 * Afterwards, the @c "document-open" signal is emitted for plugins.
822 * @param locale_filename The filename of the document to load, in locale encoding.
823 * @param readonly Whether to open the document in read-only mode.
824 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
825 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
827 * @return The document opened or @c NULL.
829 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
830 GeanyFiletype *ft, const gchar *forced_enc)
832 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
836 typedef struct
838 gchar *data; /* null-terminated file data */
839 gsize len; /* string length of data */
840 gchar *enc;
841 gboolean bom;
842 time_t mtime; /* modification time, read by stat::st_mtime */
843 gboolean readonly;
844 } FileData;
847 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
848 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
849 FileData *filedata, const gchar *forced_enc)
851 GError *err = NULL;
852 struct stat st;
854 filedata->data = NULL;
855 filedata->len = 0;
856 filedata->enc = NULL;
857 filedata->bom = FALSE;
858 filedata->readonly = FALSE;
860 if (g_stat(locale_filename, &st) != 0)
862 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
863 display_filename, g_strerror(errno));
864 return FALSE;
867 filedata->mtime = st.st_mtime;
869 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
871 ui_set_statusbar(TRUE, "%s", err->message);
872 g_error_free(err);
873 return FALSE;
876 filedata->len = (gsize) st.st_size;
877 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
878 &filedata->enc, &filedata->bom, &filedata->readonly))
880 if (forced_enc)
882 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
883 display_filename, forced_enc);
885 else
887 ui_set_statusbar(TRUE,
888 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
889 display_filename);
891 g_free(filedata->data);
892 return FALSE;
895 if (filedata->readonly)
897 const gchar *warn_msg = _(
898 "The file \"%s\" could not be opened properly and has been truncated. " \
899 "This can occur if the file contains a NULL byte. " \
900 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
902 if (main_status.main_window_realized)
903 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
905 ui_set_statusbar(TRUE, warn_msg, display_filename);
908 return TRUE;
912 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
913 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
914 * if cl_options.goto_column is set.
916 * returns the new position which may have changed */
917 static gint set_cursor_position(GeanyEditor *editor, gint pos)
919 if (cl_options.goto_line >= 0)
920 { /* goto line which was specified on command line and then undefine the line */
921 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
922 editor->scroll_percent = 0.5F;
923 cl_options.goto_line = -1;
925 else if (pos > 0)
927 sci_set_current_position(editor->sci, pos, FALSE);
928 editor->scroll_percent = 0.5F;
931 if (cl_options.goto_column >= 0)
932 { /* goto column which was specified on command line and then undefine the column */
934 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
935 sci_set_current_position(editor->sci, new_pos, FALSE);
936 editor->scroll_percent = 0.5F;
937 cl_options.goto_column = -1;
938 return new_pos;
940 return sci_get_current_position(editor->sci);
944 /* Count lines that start with some hard tabs then a soft tab. */
945 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
947 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
948 ScintillaObject *sci = editor->sci;
949 gsize count = 0;
950 struct Sci_TextToFind ttf;
951 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
952 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
954 g_free(soft_tab);
956 ttf.chrg.cpMin = 0;
957 ttf.chrg.cpMax = sci_get_length(sci);
958 ttf.lpstrText = regex;
959 while (1)
961 gint pos;
963 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
964 if (pos == -1)
965 break; /* no more matches */
966 count++;
967 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
969 g_free(regex);
970 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
971 return count > sci_get_line_count(sci) * 0.02;
975 /* Detect the indent type based on counting the leading indent characters for each line.
976 * Returns whether detection succeeded, and the detected type in *type_ upon success */
977 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
979 GeanyEditor *editor = doc->editor;
980 ScintillaObject *sci = editor->sci;
981 gint line, line_count;
982 gsize tabs = 0, spaces = 0;
984 if (detect_tabs_and_spaces(editor))
986 *type_ = GEANY_INDENT_TYPE_BOTH;
987 return TRUE;
990 line_count = sci_get_line_count(sci);
991 for (line = 0; line < line_count; line++)
993 gint pos = sci_get_position_from_line(sci, line);
994 gchar c;
996 /* most code will have indent total <= 24, otherwise it's more likely to be
997 * alignment than indentation */
998 if (sci_get_line_indentation(sci, line) > 24)
999 continue;
1001 c = sci_get_char_at(sci, pos);
1002 if (c == '\t')
1003 tabs++;
1004 /* check for at least 2 spaces */
1005 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1006 spaces++;
1008 if (spaces == 0 && tabs == 0)
1009 return FALSE;
1011 /* the factors may need to be tweaked */
1012 if (spaces > tabs * 4)
1013 *type_ = GEANY_INDENT_TYPE_SPACES;
1014 else if (tabs > spaces * 4)
1015 *type_ = GEANY_INDENT_TYPE_TABS;
1016 else
1017 *type_ = GEANY_INDENT_TYPE_BOTH;
1019 return TRUE;
1023 /* Detect the indent width based on counting the leading indent characters for each line.
1024 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1025 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1027 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1028 ScintillaObject *sci = editor->sci;
1029 gint line, line_count;
1030 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1031 gint count, width, i;
1033 /* can't easily detect the supposed width of a tab, guess the default is OK */
1034 if (type == GEANY_INDENT_TYPE_TABS)
1035 return FALSE;
1037 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1038 sci_set_tab_width(sci, 8);
1040 line_count = sci_get_line_count(sci);
1041 for (line = 0; line < line_count; line++)
1043 gint pos = sci_get_line_indent_position(sci, line);
1045 /* We probably don't have style info yet, because we're generally called just after
1046 * the document got created, so we can't use highlighting_is_code_style().
1047 * That's not good, but the assumption below that concerning lines start with an
1048 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1049 * without removing too much legitimate lines. */
1050 if (sci_get_char_at(sci, pos) == '*')
1051 continue;
1053 width = sci_get_line_indentation(sci, line);
1054 /* most code will have indent total <= 24, otherwise it's more likely to be
1055 * alignment than indentation */
1056 if (width > 24)
1057 continue;
1058 /* < 2 is no indentation */
1059 if (width < 2)
1060 continue;
1062 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1064 if ((width % (i + 2)) == 0)
1065 widths[i]++;
1068 count = 0;
1069 width = iprefs->width;
1070 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1072 /* give large indents higher weight not to be fooled by spurious indents */
1073 if (widths[i] >= count * 1.5)
1075 width = i + 2;
1076 count = widths[i];
1080 if (count == 0)
1081 return FALSE;
1083 *width_ = width;
1084 return TRUE;
1088 /* same as detect_indent_width() but uses editor's indent type */
1089 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1091 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1095 void document_apply_indent_settings(GeanyDocument *doc)
1097 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1098 GeanyIndentType type = iprefs->type;
1099 gint width = iprefs->width;
1101 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1103 if (type != iprefs->type)
1105 const gchar *name = NULL;
1107 switch (type)
1109 case GEANY_INDENT_TYPE_SPACES:
1110 name = _("Spaces");
1111 break;
1112 case GEANY_INDENT_TYPE_TABS:
1113 name = _("Tabs");
1114 break;
1115 case GEANY_INDENT_TYPE_BOTH:
1116 name = _("Tabs and Spaces");
1117 break;
1119 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1120 * and Spaces), the second one is the filename */
1121 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1122 DOC_FILENAME(doc));
1125 else if (doc->file_type->indent_type > -1)
1126 type = doc->file_type->indent_type;
1128 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1130 if (width != iprefs->width)
1132 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1133 DOC_FILENAME(doc));
1136 else if (doc->file_type->indent_width > -1)
1137 width = doc->file_type->indent_width;
1139 editor_set_indent(doc->editor, type, width);
1143 void document_show_tab(GeanyDocument *doc)
1145 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1146 document_get_notebook_page(doc));
1150 /* To open a new file, set doc to NULL; filename should be locale encoded.
1151 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1152 * pos is the cursor position, which can be overridden by --line and --column.
1153 * forced_enc can be NULL to detect the file encoding.
1154 * Returns: doc of the opened file or NULL if an error occurred. */
1155 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1156 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1158 gint editor_mode;
1159 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1160 gchar *utf8_filename = NULL;
1161 gchar *display_filename = NULL;
1162 gchar *locale_filename = NULL;
1163 GeanyFiletype *use_ft;
1164 FileData filedata;
1166 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1168 if (reload)
1170 utf8_filename = g_strdup(doc->file_name);
1171 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1173 else
1175 /* filename must not be NULL when opening a file */
1176 g_return_val_if_fail(filename, NULL);
1178 #ifdef G_OS_WIN32
1179 /* if filename is a shortcut, try to resolve it */
1180 locale_filename = win32_get_shortcut_target(filename);
1181 #else
1182 locale_filename = g_strdup(filename);
1183 #endif
1184 /* remove relative junk */
1185 utils_tidy_path(locale_filename);
1187 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1188 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1190 /* if file is already open, switch to it and go */
1191 doc = document_find_by_filename(utf8_filename);
1192 if (doc != NULL)
1194 ui_add_recent_document(doc); /* either add or reorder recent item */
1195 /* show the doc before reload dialog */
1196 document_show_tab(doc);
1197 document_check_disk_status(doc, TRUE); /* force a file changed check */
1200 if (reload || doc == NULL)
1201 { /* doc possibly changed */
1202 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1204 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1206 g_free(display_filename);
1207 g_free(utf8_filename);
1208 g_free(locale_filename);
1209 return NULL;
1212 if (! reload)
1214 doc = document_create(utf8_filename);
1215 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1217 /* file exists on disk, set real_path */
1218 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1220 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1221 monitor_file_setup(doc);
1224 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1225 sci_empty_undo_buffer(doc->editor->sci);
1227 /* add the text to the ScintillaObject */
1228 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1229 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1230 queue_colourise(doc); /* Ensure the document gets colourised. */
1232 /* detect & set line endings */
1233 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1234 sci_set_eol_mode(doc->editor->sci, editor_mode);
1235 g_free(filedata.data);
1237 sci_set_undo_collection(doc->editor->sci, TRUE);
1239 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1240 g_free(doc->encoding); /* if reloading, free old encoding */
1241 doc->encoding = filedata.enc;
1242 doc->has_bom = filedata.bom;
1243 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1245 doc->readonly = readonly || filedata.readonly;
1246 sci_set_readonly(doc->editor->sci, doc->readonly);
1247 doc->priv->protected = 0;
1249 /* update line number margin width */
1250 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1251 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1253 if (! reload)
1256 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1257 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1258 doc->editor);
1260 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1262 else
1263 { /* reloading */
1264 document_undo_clear(doc);
1266 use_ft = ft;
1268 /* update taglist, typedef keywords and build menu if necessary */
1269 document_set_filetype(doc, use_ft);
1271 /* set indentation settings after setting the filetype */
1272 if (reload)
1273 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1274 else
1275 document_apply_indent_settings(doc);
1277 document_set_text_changed(doc, FALSE); /* also updates tab state */
1278 ui_document_show_hide(doc); /* update the document menu */
1280 /* finally add current file to recent files menu, but not the files from the last session */
1281 if (! main_status.opening_session_files)
1282 ui_add_recent_document(doc);
1284 if (reload)
1286 g_signal_emit_by_name(geany_object, "document-reload", doc);
1287 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1289 else
1291 g_signal_emit_by_name(geany_object, "document-open", doc);
1292 /* For translators: this is the status window message for opening a file. %d is the number
1293 * of the newly opened file, %s indicates whether the file is opened read-only
1294 * (it is replaced with the string ", read-only"). */
1295 msgwin_status_add(_("File %s opened(%d%s)."),
1296 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1297 (readonly) ? _(", read-only") : "");
1301 g_free(display_filename);
1302 g_free(utf8_filename);
1303 g_free(locale_filename);
1305 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1306 pos = set_cursor_position(doc->editor, pos);
1307 /* now bring the file in front */
1308 editor_goto_pos(doc->editor, pos, FALSE);
1310 /* finally, let the editor widget grab the focus so you can start coding
1311 * right away */
1312 g_idle_add(on_idle_focus, doc);
1313 return doc;
1317 /* Takes a new line separated list of filename URIs and opens each file.
1318 * length is the length of the string */
1319 void document_open_file_list(const gchar *data, gsize length)
1321 guint i;
1322 gchar *filename;
1323 gchar **list;
1325 g_return_if_fail(data != NULL);
1327 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1329 /* stop at the end or first empty item, because last item is empty but not null */
1330 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1332 filename = utils_get_path_from_uri(list[i]);
1333 if (filename == NULL)
1334 continue;
1335 document_open_file(filename, FALSE, NULL, NULL);
1336 g_free(filename);
1339 g_strfreev(list);
1344 * Opens each file in the list @a filenames.
1345 * Internally, document_open_file() is called for every list item.
1347 * @param filenames A list of filenames to load, in locale encoding.
1348 * @param readonly Whether to open the document in read-only mode.
1349 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1350 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1352 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1353 const gchar *forced_enc)
1355 const GSList *item;
1357 for (item = filenames; item != NULL; item = g_slist_next(item))
1359 document_open_file(item->data, readonly, ft, forced_enc);
1365 * Reloads the document with the specified file encoding
1366 * @a forced_enc or @c NULL to auto-detect the file encoding.
1368 * @param doc The document to reload.
1369 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1371 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1373 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1375 gint pos = 0;
1376 GeanyDocument *new_doc;
1378 g_return_val_if_fail(doc != NULL, FALSE);
1380 /* Use cancel because the response handler would call this recursively */
1381 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1382 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1384 /* try to set the cursor to the position before reloading */
1385 pos = sci_get_current_position(doc->editor->sci);
1386 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1388 return (new_doc != NULL);
1392 /* also used for reloading when forced_enc is NULL */
1393 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1395 gchar *base_name;
1396 gboolean result = FALSE;
1398 g_return_val_if_fail(doc != NULL, FALSE);
1400 /* No need to reload "untitled" (non-file-backed) documents */
1401 if (doc->file_name == NULL)
1402 return FALSE;
1404 if (forced_enc == NULL)
1405 forced_enc = doc->encoding;
1407 base_name = g_path_get_basename(doc->file_name);
1408 /* don't prompt if file hasn't been edited at all */
1409 if ((!doc->changed && !document_can_undo(doc) && !document_can_redo(doc)) ||
1410 dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1411 _("Any unsaved changes will be lost."),
1412 _("Are you sure you want to reload '%s'?"), base_name))
1414 result = document_reload_file(doc, forced_enc);
1415 if (forced_enc != NULL)
1416 ui_update_statusbar(doc, -1);
1418 g_free(base_name);
1420 return result;
1424 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1426 #ifndef USE_GIO_FILEMON
1427 struct stat st;
1429 g_return_val_if_fail(doc != NULL, FALSE);
1431 /* stat the file to get the timestamp, otherwise on Windows the actual
1432 * timestamp can be ahead of time(NULL) */
1433 if (g_stat(locale_filename, &st) != 0)
1435 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1436 g_strerror(errno));
1437 return FALSE;
1440 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1441 #endif
1442 return TRUE;
1446 /* Sets line and column to the given position byte_pos in the document.
1447 * byte_pos is the position counted in bytes, not characters */
1448 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1450 gint i;
1451 gint line_start;
1453 /* for some reason we can use byte count instead of character count here */
1454 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1455 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1456 /* get the column in the line */
1457 *column = byte_pos - line_start;
1459 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1460 * skip one byte(i++) and decrease the column number which is based on byte count */
1461 for (i = line_start; i < (line_start + *column); i++)
1463 if (sci_get_char_at(doc->editor->sci, i) < 0)
1465 (*column)--;
1466 i++;
1472 static void replace_header_filename(GeanyDocument *doc)
1474 gchar *filebase;
1475 gchar *filename;
1476 struct Sci_TextToFind ttf;
1478 g_return_if_fail(doc != NULL);
1479 g_return_if_fail(doc->file_type != NULL);
1481 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1482 if (doc->file_type->extension)
1483 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1484 else
1485 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1487 filename = g_path_get_basename(doc->file_name);
1489 /* only search the first 3 lines */
1490 ttf.chrg.cpMin = 0;
1491 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1492 ttf.lpstrText = filebase;
1494 if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1496 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1497 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1498 sci_replace_target(doc->editor->sci, filename, FALSE);
1500 g_free(filebase);
1501 g_free(filename);
1506 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1507 * you still have to call @ref document_save_file_as() to change the @a doc object.
1508 * It also stops monitoring for file changes to prevent receiving too many file change events
1509 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1511 * @param doc The current document which should be renamed.
1512 * @param new_filename The new filename in UTF-8 encoding.
1514 * @since 0.16
1516 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1518 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1519 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1520 gint result;
1522 /* stop file monitoring to avoid getting events for deleting/creating files,
1523 * it's re-setup in document_save_file_as() */
1524 document_stop_file_monitoring(doc);
1526 result = g_rename(old_locale_filename, new_locale_filename);
1527 if (result != 0)
1529 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1530 _("Error renaming file."), g_strerror(errno));
1532 g_free(old_locale_filename);
1533 g_free(new_locale_filename);
1537 static void protect_document(GeanyDocument *doc)
1539 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1540 if (!doc->priv->protected++)
1541 sci_set_readonly(doc->editor->sci, TRUE);
1544 static void unprotect_document(GeanyDocument *doc)
1546 g_return_if_fail(doc->priv->protected > 0);
1548 if (!--doc->priv->protected && doc->readonly == FALSE)
1549 sci_set_readonly(doc->editor->sci, FALSE);
1553 /* Return TRUE if the document doesn't have a full filename set.
1554 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1555 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1556 * new files. */
1557 gboolean document_need_save_as(GeanyDocument *doc)
1559 g_return_val_if_fail(doc != NULL, FALSE);
1561 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1566 * Saves the document, detecting the filetype.
1568 * @param doc The document for the file to save.
1569 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1570 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1572 * @see document_save_file().
1574 * @since 0.16
1576 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1578 gboolean ret;
1579 gboolean new_file;
1581 g_return_val_if_fail(doc != NULL, FALSE);
1583 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1584 if (utf8_fname != NULL)
1585 SETPTR(doc->file_name, g_strdup(utf8_fname));
1587 /* reset real path, it's retrieved again in document_save() */
1588 SETPTR(doc->real_path, NULL);
1590 /* detect filetype */
1591 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1593 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1595 document_set_filetype(doc, ft);
1596 if (document_get_current() == doc)
1598 ignore_callback = TRUE;
1599 filetypes_select_radio_item(doc->file_type);
1600 ignore_callback = FALSE;
1604 if (new_file)
1606 sci_set_readonly(doc->editor->sci, FALSE);
1607 doc->readonly = FALSE;
1608 if (doc->priv->protected > 0)
1609 unprotect_document(doc);
1612 replace_header_filename(doc);
1614 ret = document_save_file(doc, TRUE);
1616 /* file monitoring support, add file monitoring after the file has been saved
1617 * to ignore any earlier events */
1618 monitor_file_setup(doc);
1619 doc->priv->file_disk_status = FILE_IGNORE;
1621 if (ret)
1622 ui_add_recent_document(doc);
1623 return ret;
1627 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1629 GError *conv_error = NULL;
1630 gchar* conv_file_contents = NULL;
1631 gsize bytes_read;
1632 gsize conv_len;
1634 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1635 g_return_val_if_fail(len != NULL, FALSE);
1637 /* try to convert it from UTF-8 to original encoding */
1638 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1639 &bytes_read, &conv_len, &conv_error);
1641 if (conv_error != NULL)
1643 gchar *text = g_strdup_printf(
1644 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1645 doc->encoding);
1646 gchar *error_text;
1648 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1650 gint line, column;
1651 gint context_len;
1652 gunichar unic;
1653 /* don't read over the doc length */
1654 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1655 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1656 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1658 /* take only one valid Unicode character from the context and discard the leftover */
1659 unic = g_utf8_get_char_validated(context, -1);
1660 context_len = g_unichar_to_utf8(unic, context);
1661 context[context_len] = '\0';
1662 get_line_column_from_pos(doc, bytes_read, &line, &column);
1664 error_text = g_strdup_printf(
1665 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1666 conv_error->message, context, line + 1, column);
1668 else
1669 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1671 geany_debug("encoding error: %s", conv_error->message);
1672 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1673 g_error_free(conv_error);
1674 g_free(text);
1675 g_free(error_text);
1676 return FALSE;
1678 else
1680 g_free(*data);
1681 *data = conv_file_contents;
1682 *len = conv_len;
1684 return TRUE;
1688 static gchar *write_data_to_disk(const gchar *locale_filename,
1689 const gchar *data, gsize len)
1691 GError *error = NULL;
1693 if (file_prefs.use_safe_file_saving)
1695 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1696 * This is the only option that handles disk space exhaustion. */
1697 if (g_file_set_contents(locale_filename, data, len, &error))
1698 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1700 else if (file_prefs.use_gio_unsafe_file_saving)
1702 GFile *fp;
1704 /* Use GIO API to save file (GVFS-safe)
1705 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1706 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1707 fp = g_file_new_for_path(locale_filename);
1708 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1709 G_FILE_CREATE_NONE, NULL, NULL, &error);
1710 g_object_unref(fp);
1712 else
1714 FILE *fp;
1715 int save_errno;
1716 gchar *display_name = g_filename_display_name(locale_filename);
1718 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1719 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1720 errno = 0;
1721 fp = g_fopen(locale_filename, "wb");
1722 if (fp == NULL)
1724 save_errno = errno;
1726 g_set_error(&error,
1727 G_FILE_ERROR,
1728 g_file_error_from_errno(save_errno),
1729 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1730 display_name,
1731 g_strerror(save_errno));
1733 else
1735 gsize bytes_written;
1737 errno = 0;
1738 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1740 if (len != bytes_written)
1742 save_errno = errno;
1744 g_set_error(&error,
1745 G_FILE_ERROR,
1746 g_file_error_from_errno(save_errno),
1747 _("Failed to write file '%s': fwrite() failed: %s"),
1748 display_name,
1749 g_strerror(save_errno));
1752 errno = 0;
1753 /* preserve the fwrite() error if any */
1754 if (fclose(fp) != 0 && error == NULL)
1756 save_errno = errno;
1758 g_set_error(&error,
1759 G_FILE_ERROR,
1760 g_file_error_from_errno(save_errno),
1761 _("Failed to close file '%s': fclose() failed: %s"),
1762 display_name,
1763 g_strerror(save_errno));
1767 g_free(display_name);
1769 if (error != NULL)
1771 gchar *msg = g_strdup(error->message);
1772 g_error_free(error);
1773 /* geany will warn about file truncation for unsafe saving below */
1774 return msg;
1776 return NULL;
1780 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1781 const gchar *data, gsize len)
1783 gchar *err;
1785 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1786 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1788 err = write_data_to_disk(locale_filename, data, len);
1789 if (err)
1790 return err;
1792 /* now the file is on disk, set real_path */
1793 if (doc->real_path == NULL)
1795 doc->real_path = tm_get_real_path(locale_filename);
1796 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1797 monitor_file_setup(doc);
1799 return NULL;
1803 * Saves the document.
1804 * Also shows the Save As dialog if necessary.
1805 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1807 * Saving may include replacing tabs with spaces,
1808 * stripping trailing spaces and adding a final new line at the end of the file, depending
1809 * on user preferences. Then the @c "document-before-save" signal is emitted,
1810 * allowing plugins to modify the document before it is saved, and data is
1811 * actually written to disk.
1813 * On successful saving:
1814 * - GeanyDocument::real_path is set.
1815 * - The filetype is set again or auto-detected if it wasn't set yet.
1816 * - The @c "document-save" signal is emitted for plugins.
1818 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1819 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1820 * added in Geany 1.22.
1822 * @param doc The document to save.
1823 * @param force Whether to save the file even if it is not modified.
1825 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1827 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1829 gchar *errmsg;
1830 gchar *data;
1831 gsize len;
1832 gchar *locale_filename;
1833 const GeanyFilePrefs *fp;
1835 g_return_val_if_fail(doc != NULL, FALSE);
1837 if (document_need_save_as(doc))
1839 /* ensure doc is the current tab before showing the dialog */
1840 document_show_tab(doc);
1841 return dialogs_show_save_as();
1844 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1845 if (doc->readonly || doc->priv->protected)
1846 return FALSE;
1847 if (!force && !doc->changed)
1848 return FALSE;
1850 fp = project_get_file_prefs();
1851 /* replaces tabs with spaces but only if the current file is not a Makefile */
1852 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1853 editor_replace_tabs(doc->editor);
1854 /* strip trailing spaces */
1855 if (fp->strip_trailing_spaces)
1856 editor_strip_trailing_spaces(doc->editor);
1857 /* ensure the file has a newline at the end */
1858 if (fp->final_new_line)
1859 editor_ensure_final_newline(doc->editor);
1860 /* ensure newlines are consistent */
1861 if (fp->ensure_convert_new_lines)
1862 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1864 /* notify plugins which may wish to modify the document before it's saved */
1865 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1867 len = sci_get_length(doc->editor->sci) + 1;
1868 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1869 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1870 * encoding, it will be converted to doc->encoding below and this conversion
1871 * also changes the BOM */
1872 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1873 data[0] = (gchar) 0xef;
1874 data[1] = (gchar) 0xbb;
1875 data[2] = (gchar) 0xbf;
1876 sci_get_text(doc->editor->sci, len, data + 3);
1877 len += 3;
1879 else
1881 data = (gchar*) g_malloc(len);
1882 sci_get_text(doc->editor->sci, len, data);
1885 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1886 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1887 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1889 if (! save_convert_to_encoding(doc, &data, &len))
1891 g_free(data);
1892 return FALSE;
1895 else
1897 len = strlen(data);
1900 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1902 /* ignore file changed notification when the file is written */
1903 doc->priv->file_disk_status = FILE_IGNORE;
1905 /* actually write the content of data to the file on disk */
1906 errmsg = save_doc(doc, locale_filename, data, len);
1907 g_free(data);
1909 if (errmsg != NULL)
1911 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1913 if (!file_prefs.use_safe_file_saving)
1915 SETPTR(errmsg,
1916 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1918 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1919 doc->priv->file_disk_status = FILE_OK;
1920 utils_beep();
1921 g_free(locale_filename);
1922 g_free(errmsg);
1923 return FALSE;
1926 /* store the opened encoding for undo/redo */
1927 store_saved_encoding(doc);
1929 /* ignore the following things if we are quitting */
1930 if (! main_status.quitting)
1932 sci_set_savepoint(doc->editor->sci);
1934 if (file_prefs.disk_check_timeout > 0)
1935 document_update_timestamp(doc, locale_filename);
1937 /* update filetype-related things */
1938 document_set_filetype(doc, doc->file_type);
1940 document_update_tab_label(doc);
1942 msgwin_status_add(_("File %s saved."), doc->file_name);
1943 ui_update_statusbar(doc, -1);
1944 #ifdef HAVE_VTE
1945 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1946 #endif
1948 g_free(locale_filename);
1950 g_signal_emit_by_name(geany_object, "document-save", doc);
1952 return TRUE;
1956 /* special search function, used from the find entry in the toolbar
1957 * return TRUE if text was found otherwise FALSE
1958 * return also TRUE if text is empty */
1959 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1960 gboolean backwards)
1962 gint start_pos, search_pos;
1963 struct Sci_TextToFind ttf;
1965 g_return_val_if_fail(text != NULL, FALSE);
1966 g_return_val_if_fail(doc != NULL, FALSE);
1967 if (! *text)
1968 return TRUE;
1970 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1971 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1973 /* search cursor to end or start */
1974 ttf.chrg.cpMin = start_pos;
1975 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1976 ttf.lpstrText = (gchar *)text;
1977 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1979 /* if no match, search start (or end) to cursor */
1980 if (search_pos == -1)
1982 if (backwards)
1984 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1985 ttf.chrg.cpMax = start_pos;
1987 else
1989 ttf.chrg.cpMin = 0;
1990 ttf.chrg.cpMax = start_pos + strlen(text);
1992 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1995 if (search_pos != -1)
1997 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1999 /* unfold maybe folded results */
2000 sci_ensure_line_is_visible(doc->editor->sci, line);
2002 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2003 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2005 if (! editor_line_in_view(doc->editor, line))
2006 { /* we need to force scrolling in case the cursor is outside of the current visible area
2007 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2008 * while searching */
2009 editor_scroll_to_line(doc->editor, -1, 0.3F);
2011 else
2012 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2013 return TRUE;
2015 else
2017 if (! inc)
2019 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2021 utils_beep();
2022 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
2023 return FALSE;
2028 /* General search function, used from the find dialog.
2029 * Returns -1 on failure or the start position of the matching text.
2030 * Will skip past any selection, ignoring it.
2032 * @param text Text to find.
2033 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2035 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2036 gint flags, gboolean search_backwards, GeanyMatchInfo **match_,
2037 gboolean scroll, GtkWidget *parent)
2039 gint selection_end, selection_start, search_pos;
2041 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2042 if (! *text)
2043 return -1;
2045 /* Sci doesn't support searching backwards with a regex */
2046 if (flags & GEANY_FIND_REGEXP)
2047 search_backwards = FALSE;
2049 if (!original_text)
2050 original_text = text;
2052 selection_start = sci_get_selection_start(doc->editor->sci);
2053 selection_end = sci_get_selection_end(doc->editor->sci);
2054 if ((selection_end - selection_start) > 0)
2055 { /* there's a selection so go to the end */
2056 if (search_backwards)
2057 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2058 else
2059 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2062 sci_set_search_anchor(doc->editor->sci);
2063 if (search_backwards)
2064 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2065 else
2066 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2068 if (search_pos != -1)
2070 /* unfold maybe folded results */
2071 sci_ensure_line_is_visible(doc->editor->sci,
2072 sci_get_line_from_position(doc->editor->sci, search_pos));
2073 if (scroll)
2074 doc->editor->scroll_percent = 0.3F;
2076 else
2078 gint sci_len = sci_get_length(doc->editor->sci);
2080 /* if we just searched the whole text, give up searching. */
2081 if ((selection_end == 0 && ! search_backwards) ||
2082 (selection_end == sci_len && search_backwards))
2084 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2085 utils_beep();
2086 return -1;
2089 /* we searched only part of the document, so ask whether to wraparound. */
2090 if (search_prefs.always_wrap ||
2091 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2092 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2094 gint ret;
2096 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2097 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2098 if (ret == -1)
2099 { /* return to original cursor position if not found */
2100 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2102 return ret;
2105 return search_pos;
2109 /* Replaces the selection if it matches, otherwise just finds the next match.
2110 * Returns: start of replaced text, or -1 if no replacement was made
2112 * @param find_text Text to find.
2113 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2115 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2116 const gchar *replace_text, gint flags, gboolean search_backwards)
2118 gint selection_end, selection_start, search_pos;
2119 GeanyMatchInfo *match = NULL;
2121 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2123 if (! *find_text)
2124 return -1;
2126 /* Sci doesn't support searching backwards with a regex */
2127 if (flags & GEANY_FIND_REGEXP)
2128 search_backwards = FALSE;
2130 if (!original_find_text)
2131 original_find_text = find_text;
2133 selection_start = sci_get_selection_start(doc->editor->sci);
2134 selection_end = sci_get_selection_end(doc->editor->sci);
2135 if (selection_end == selection_start)
2137 /* no selection so just find the next match */
2138 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2139 return -1;
2141 /* there's a selection so go to the start before finding to search through it
2142 * this ensures there is a match */
2143 if (search_backwards)
2144 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2145 else
2146 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2148 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2149 /* return if the original selected text did not match (at the start of the selection) */
2150 if (search_pos != selection_start)
2152 if (search_pos != -1)
2153 geany_match_info_free(match);
2154 return -1;
2157 if (search_pos != -1)
2159 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2160 /* select the replacement - find text will skip past the selected text */
2161 sci_set_selection_start(doc->editor->sci, search_pos);
2162 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2163 geany_match_info_free(match);
2165 else
2167 /* no match in the selection */
2168 utils_beep();
2170 return search_pos;
2174 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2175 const gchar *original_replace_text)
2177 gchar *filename;
2179 if (count == 0)
2181 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2182 return;
2185 filename = g_path_get_basename(DOC_FILENAME(doc));
2186 ui_set_statusbar(TRUE, ngettext(
2187 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2188 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2189 count), filename, count, original_find_text, original_replace_text);
2190 g_free(filename);
2194 /* Replace all text matches in a certain range within document.
2195 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2196 * or -1 if no text was found.
2197 * scroll_to_match is whether to scroll the last replacement in view (which also
2198 * clears the selection).
2199 * Returns: the number of replacements made. */
2200 static guint
2201 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2202 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2204 gint count = 0;
2205 struct Sci_TextToFind ttf;
2206 ScintillaObject *sci;
2208 if (new_range_end != NULL)
2209 *new_range_end = -1;
2211 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2213 if (! *find_text || doc->readonly)
2214 return 0;
2216 sci = doc->editor->sci;
2218 ttf.chrg.cpMin = start;
2219 ttf.chrg.cpMax = end;
2220 ttf.lpstrText = (gchar*)find_text;
2222 sci_start_undo_action(sci);
2223 count = search_replace_range(sci, &ttf, flags, replace_text);
2224 sci_end_undo_action(sci);
2226 if (count > 0)
2227 { /* scroll last match in view, will destroy the existing selection */
2228 if (scroll_to_match)
2229 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2231 if (new_range_end != NULL)
2232 *new_range_end = ttf.chrg.cpMax;
2234 return count;
2238 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2239 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2241 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2242 gint max_column = 0, count = 0;
2243 gboolean replaced = FALSE;
2245 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2247 if (! *find_text)
2248 return;
2250 selection_start = sci_get_selection_start(doc->editor->sci);
2251 selection_end = sci_get_selection_end(doc->editor->sci);
2252 /* do we have a selection? */
2253 if ((selection_end - selection_start) == 0)
2255 utils_beep();
2256 return;
2259 selection_mode = sci_get_selection_mode(doc->editor->sci);
2260 selected_lines = sci_get_lines_selected(doc->editor->sci);
2261 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2262 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2264 gint first_line, line;
2266 sci_start_undo_action(doc->editor->sci);
2268 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2269 /* Find the last line with chars selected (not EOL char) */
2270 last_line = sci_get_line_from_position(doc->editor->sci,
2271 selection_end - editor_get_eol_char_len(doc->editor));
2272 last_line = MAX(first_line, last_line);
2273 for (line = first_line; line < (first_line + selected_lines); line++)
2275 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2276 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2278 /* skip line if there is no selection */
2279 if (line_start != INVALID_POSITION)
2281 /* don't let document_replace_range() scroll to match to keep our selection */
2282 gint new_sel_end;
2284 count += document_replace_range(doc, find_text, replace_text, flags,
2285 line_start, line_end, FALSE, &new_sel_end);
2286 if (new_sel_end != -1)
2288 replaced = TRUE;
2289 /* this gets the greatest column within the selection after replacing */
2290 max_column = MAX(max_column,
2291 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2295 sci_end_undo_action(doc->editor->sci);
2297 else /* handle normal line selection */
2299 count += document_replace_range(doc, find_text, replace_text, flags,
2300 selection_start, selection_end, TRUE, &selection_end);
2301 if (selection_end != -1)
2302 replaced = TRUE;
2305 if (replaced)
2306 { /* update the selection for the new endpoint */
2308 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2310 /* now we can scroll to the selection and destroy it because we rebuild it later */
2311 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2313 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2314 * the highest column on the last line. The wrapped selection is completely different
2315 * from the original one, so skip the selection at all */
2316 /* TODO is there a better way to handle the wrapped selection? */
2317 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2318 { /* for keeping and adjusting the selection in multi line rectangle selection we
2319 * need the last line of the original selection and the greatest column number after
2320 * replacing and set the selection end to the last line at the greatest column */
2321 sci_set_selection_start(doc->editor->sci, selection_start);
2322 sci_set_selection_end(doc->editor->sci,
2323 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2324 sci_set_selection_mode(doc->editor->sci, selection_mode);
2327 else
2329 sci_set_selection_start(doc->editor->sci, selection_start);
2330 sci_set_selection_end(doc->editor->sci, selection_end);
2333 else /* no replacements */
2334 utils_beep();
2336 show_replace_summary(doc, count, original_find_text, original_replace_text);
2340 /* returns number of replacements made. */
2341 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2342 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2344 gint len, count;
2345 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2347 if (! *find_text)
2348 return FALSE;
2350 len = sci_get_length(doc->editor->sci);
2351 count = document_replace_range(
2352 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2354 show_replace_summary(doc, count, original_find_text, original_replace_text);
2355 return count;
2360 * Parses or re-parses the document's buffer and updates the type
2361 * keywords and symbol list.
2363 * @param doc The document.
2365 void document_update_tags(GeanyDocument *doc)
2367 guchar *buffer_ptr;
2368 gsize len;
2370 g_return_if_fail(DOC_VALID(doc));
2371 g_return_if_fail(app->tm_workspace != NULL);
2373 /* early out if it's a new file or doesn't support tags */
2374 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2376 /* We must call sidebar_update_tag_list() before returning,
2377 * to ensure that the symbol list is always updated properly (e.g.
2378 * when creating a new document with a partial filename set. */
2379 sidebar_update_tag_list(doc, FALSE);
2380 return;
2383 /* create a new TM file if there isn't one yet */
2384 if (! doc->tm_file)
2386 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2387 const gchar *name;
2389 /* lookup the name rather than using filetype name to support custom filetypes */
2390 name = tm_source_file_get_lang_name(doc->file_type->lang);
2391 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2392 g_free(locale_filename);
2394 if (doc->tm_file && !tm_workspace_add_object(doc->tm_file))
2396 tm_work_object_free(doc->tm_file);
2397 doc->tm_file = NULL;
2401 /* early out if there's no work object and we couldn't create one */
2402 if (doc->tm_file == NULL)
2404 /* We must call sidebar_update_tag_list() before returning,
2405 * to ensure that the symbol list is always updated properly (e.g.
2406 * when creating a new document with a partial filename set. */
2407 sidebar_update_tag_list(doc, FALSE);
2408 return;
2411 len = sci_get_length(doc->editor->sci);
2412 /* tm_source_file_buffer_update() below don't support 0-length data,
2413 * so just empty the tags array and leave */
2414 if (len < 1)
2416 tm_tags_array_free(doc->tm_file->tags_array, FALSE);
2417 sidebar_update_tag_list(doc, FALSE);
2418 return;
2421 /* Parse Scintilla's buffer directly using TagManager
2422 * Note: this buffer *MUST NOT* be modified */
2423 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2424 tm_source_file_buffer_update(doc->tm_file, buffer_ptr, len, TRUE);
2426 sidebar_update_tag_list(doc, TRUE);
2427 document_highlight_tags(doc);
2431 /* Re-highlights type keywords without re-parsing the whole document. */
2432 void document_highlight_tags(GeanyDocument *doc)
2434 GString *keywords_str;
2435 gchar *keywords;
2436 gint keyword_idx;
2438 /* some filetypes support type keywords (such as struct names), but not
2439 * necessarily all filetypes for a particular scintilla lexer. this
2440 * tells us whether the filetype supports keywords, and if so
2441 * which index to use for the scintilla keywords set. */
2442 switch (doc->file_type->id)
2444 case GEANY_FILETYPES_C:
2445 case GEANY_FILETYPES_CPP:
2446 case GEANY_FILETYPES_CS:
2447 case GEANY_FILETYPES_D:
2448 case GEANY_FILETYPES_JAVA:
2449 case GEANY_FILETYPES_OBJECTIVEC:
2450 case GEANY_FILETYPES_VALA:
2451 case GEANY_FILETYPES_RUST:
2454 /* index of the keyword set in the Scintilla lexer, for
2455 * example in LexCPP.cxx, see "cppWordLists" global array.
2456 * TODO: this magic number should be a member of the filetype */
2457 keyword_idx = 3;
2458 break;
2460 default:
2461 return; /* early out if type keywords are not supported */
2463 if (!app->tm_workspace->work_object.tags_array)
2464 return;
2466 /* get any type keywords and tell scintilla about them
2467 * this will cause the type keywords to be colourized in scintilla */
2468 keywords_str = symbols_find_tags_as_string(app->tm_workspace->work_object.tags_array,
2469 TM_GLOBAL_TYPE_MASK, doc->file_type->lang);
2470 if (keywords_str)
2472 keywords = g_string_free(keywords_str, FALSE);
2473 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2474 g_free(keywords);
2475 queue_colourise(doc); /* force re-highlighting the entire document */
2480 static gboolean on_document_update_tag_list_idle(gpointer data)
2482 GeanyDocument *doc = data;
2484 if (! DOC_VALID(doc))
2485 return FALSE;
2487 if (! main_status.quitting)
2488 document_update_tags(doc);
2490 doc->priv->tag_list_update_source = 0;
2492 /* don't update the tags until another modification of the buffer */
2493 return FALSE;
2497 void document_update_tag_list_in_idle(GeanyDocument *doc)
2499 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2500 return;
2502 /* prevent "stacking up" callback handlers, we only need one to run soon */
2503 if (doc->priv->tag_list_update_source != 0)
2504 g_source_remove(doc->priv->tag_list_update_source);
2506 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2507 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2511 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2512 gboolean filetype_changed)
2514 g_return_if_fail(doc);
2515 if (type == NULL)
2516 type = filetypes[GEANY_FILETYPES_NONE];
2518 if (filetype_changed)
2520 doc->file_type = type;
2522 /* delete tm file object to force creation of a new one */
2523 if (doc->tm_file != NULL)
2525 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2526 doc->tm_file = NULL;
2528 /* load tags files before highlighting (some lexers highlight global typenames) */
2529 if (type->id != GEANY_FILETYPES_NONE)
2530 symbols_global_tags_loaded(type->id);
2532 highlighting_set_styles(doc->editor->sci, type);
2533 editor_set_indentation_guides(doc->editor);
2534 build_menu_update(doc);
2535 queue_colourise(doc);
2536 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2539 document_update_tags(doc);
2543 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2544 * @param doc The document to use.
2545 * @param type The filetype. */
2546 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2548 gboolean ft_changed;
2549 GeanyFiletype *old_ft;
2551 g_return_if_fail(doc);
2552 if (type == NULL)
2553 type = filetypes[GEANY_FILETYPES_NONE];
2555 old_ft = doc->file_type;
2556 geany_debug("%s : %s (%s)",
2557 (doc->file_name != NULL) ? doc->file_name : "unknown",
2558 type->name,
2559 (doc->encoding != NULL) ? doc->encoding : "unknown");
2561 ft_changed = (doc->file_type != type); /* filetype has changed */
2562 document_load_config(doc, type, ft_changed);
2564 if (ft_changed)
2566 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2568 /* assume that if previous filetype was none and the settings are the default ones, this
2569 * is the first time the filetype is carefully set, so we should apply indent settings */
2570 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2571 doc->editor->indent_type == iprefs->type &&
2572 doc->editor->indent_width == iprefs->width)
2574 document_apply_indent_settings(doc);
2575 ui_document_show_hide(doc);
2578 sidebar_openfiles_update(doc); /* to update the icon */
2579 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2584 void document_reload_config(GeanyDocument *doc)
2586 document_load_config(doc, doc->file_type, TRUE);
2591 * Sets the encoding of a document.
2592 * This function only set the encoding of the %document, it does not any conversions. The new
2593 * encoding is used when e.g. saving the file.
2595 * @param doc The document to use.
2596 * @param new_encoding The encoding to be set for the document.
2598 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2600 if (doc == NULL || new_encoding == NULL ||
2601 utils_str_equal(new_encoding, doc->encoding))
2602 return;
2604 g_free(doc->encoding);
2605 doc->encoding = g_strdup(new_encoding);
2607 ui_update_statusbar(doc, -1);
2608 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2609 encodings_is_unicode_charset(doc->encoding));
2613 /* own Undo / Redo implementation to be able to undo / redo changes
2614 * to the encoding or the Unicode BOM (which are Scintilla independet).
2615 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2617 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2618 void document_undo_clear(GeanyDocument *doc)
2620 undo_action *a;
2622 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2624 a = g_trash_stack_pop(&doc->priv->undo_actions);
2625 if (G_LIKELY(a != NULL))
2627 switch (a->type)
2629 case UNDO_ENCODING: g_free(a->data); break;
2630 default: break;
2632 g_free(a);
2635 doc->priv->undo_actions = NULL;
2637 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2639 a = g_trash_stack_pop(&doc->priv->redo_actions);
2640 if (G_LIKELY(a != NULL))
2642 switch (a->type)
2644 case UNDO_ENCODING: g_free(a->data); break;
2645 default: break;
2647 g_free(a);
2650 doc->priv->redo_actions = NULL;
2652 if (! main_status.quitting && doc->editor != NULL)
2653 document_set_text_changed(doc, FALSE);
2657 /* note: this is called on SCN_MODIFIED notifications */
2658 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2660 undo_action *action;
2662 g_return_if_fail(doc != NULL);
2664 action = g_new0(undo_action, 1);
2665 action->type = type;
2666 action->data = data;
2668 g_trash_stack_push(&doc->priv->undo_actions, action);
2670 /* avoid unnecessary redraws */
2671 if (type != UNDO_SCINTILLA || !doc->changed)
2672 document_set_text_changed(doc, TRUE);
2674 ui_update_popup_reundo_items(doc);
2678 gboolean document_can_undo(GeanyDocument *doc)
2680 g_return_val_if_fail(doc != NULL, FALSE);
2682 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2683 return TRUE;
2684 else
2685 return FALSE;
2689 static void update_changed_state(GeanyDocument *doc)
2691 doc->changed =
2692 (sci_is_modified(doc->editor->sci) ||
2693 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2694 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2695 document_set_text_changed(doc, doc->changed);
2699 void document_undo(GeanyDocument *doc)
2701 undo_action *action;
2703 g_return_if_fail(doc != NULL);
2705 action = g_trash_stack_pop(&doc->priv->undo_actions);
2707 if (G_UNLIKELY(action == NULL))
2709 /* fallback, should not be necessary */
2710 geany_debug("%s: fallback used", G_STRFUNC);
2711 sci_undo(doc->editor->sci);
2713 else
2715 switch (action->type)
2717 case UNDO_SCINTILLA:
2719 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2721 sci_undo(doc->editor->sci);
2722 break;
2724 case UNDO_BOM:
2726 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2728 doc->has_bom = GPOINTER_TO_INT(action->data);
2729 ui_update_statusbar(doc, -1);
2730 ui_document_show_hide(doc);
2731 break;
2733 case UNDO_ENCODING:
2735 /* use the "old" encoding */
2736 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2738 document_set_encoding(doc, (const gchar*)action->data);
2740 ignore_callback = TRUE;
2741 encodings_select_radio_item((const gchar*)action->data);
2742 ignore_callback = FALSE;
2744 g_free(action->data);
2745 break;
2747 default: break;
2750 g_free(action); /* free the action which was taken from the stack */
2752 update_changed_state(doc);
2753 ui_update_popup_reundo_items(doc);
2757 gboolean document_can_redo(GeanyDocument *doc)
2759 g_return_val_if_fail(doc != NULL, FALSE);
2761 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2762 return TRUE;
2763 else
2764 return FALSE;
2768 void document_redo(GeanyDocument *doc)
2770 undo_action *action;
2772 g_return_if_fail(doc != NULL);
2774 action = g_trash_stack_pop(&doc->priv->redo_actions);
2776 if (G_UNLIKELY(action == NULL))
2778 /* fallback, should not be necessary */
2779 geany_debug("%s: fallback used", G_STRFUNC);
2780 sci_redo(doc->editor->sci);
2782 else
2784 switch (action->type)
2786 case UNDO_SCINTILLA:
2788 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2790 sci_redo(doc->editor->sci);
2791 break;
2793 case UNDO_BOM:
2795 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2797 doc->has_bom = GPOINTER_TO_INT(action->data);
2798 ui_update_statusbar(doc, -1);
2799 ui_document_show_hide(doc);
2800 break;
2802 case UNDO_ENCODING:
2804 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2806 document_set_encoding(doc, (const gchar*)action->data);
2808 ignore_callback = TRUE;
2809 encodings_select_radio_item((const gchar*)action->data);
2810 ignore_callback = FALSE;
2812 g_free(action->data);
2813 break;
2815 default: break;
2818 g_free(action); /* free the action which was taken from the stack */
2820 update_changed_state(doc);
2821 ui_update_popup_reundo_items(doc);
2825 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2827 undo_action *action;
2829 g_return_if_fail(doc != NULL);
2831 action = g_new0(undo_action, 1);
2832 action->type = type;
2833 action->data = data;
2835 g_trash_stack_push(&doc->priv->redo_actions, action);
2837 if (type != UNDO_SCINTILLA || !doc->changed)
2838 document_set_text_changed(doc, TRUE);
2840 ui_update_popup_reundo_items(doc);
2844 enum
2846 STATUS_CHANGED,
2847 #ifdef USE_GIO_FILEMON
2848 STATUS_DISK_CHANGED,
2849 #endif
2850 STATUS_READONLY
2852 static struct
2854 const gchar *name;
2855 GdkColor color;
2856 gboolean loaded;
2857 } document_status_styles[] = {
2858 { "geany-document-status-changed", {0}, FALSE },
2859 #ifdef USE_GIO_FILEMON
2860 { "geany-document-status-disk-changed", {0}, FALSE },
2861 #endif
2862 { "geany-document-status-readonly", {0}, FALSE }
2866 static gint document_get_status_id(GeanyDocument *doc)
2868 if (doc->changed)
2869 return STATUS_CHANGED;
2870 #ifdef USE_GIO_FILEMON
2871 else if (doc->priv->file_disk_status == FILE_CHANGED)
2872 return STATUS_DISK_CHANGED;
2873 #endif
2874 else if (doc->readonly)
2875 return STATUS_READONLY;
2877 return -1;
2881 /* returns an identifier that is to be set as a widget name or class to get it styled
2882 * depending on the document status (changed, readonly, etc.)
2883 * a NULL return value means default (unchanged) style */
2884 const gchar *document_get_status_widget_class(GeanyDocument *doc)
2886 gint status;
2888 g_return_val_if_fail(doc != NULL, NULL);
2890 status = document_get_status_id(doc);
2891 if (status < 0)
2892 return NULL;
2893 else
2894 return document_status_styles[status].name;
2899 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2900 * Returned colors are red if the document has changes, green if the document is read-only
2901 * or simply @c NULL if the document is unmodified but writable.
2903 * @param doc The document to use.
2905 * @return The color for the document or @c NULL if the default color should be used. The color
2906 * object is owned by Geany and should not be modified or freed.
2908 * @since 0.16
2910 const GdkColor *document_get_status_color(GeanyDocument *doc)
2912 gint status;
2914 g_return_val_if_fail(doc != NULL, NULL);
2916 status = document_get_status_id(doc);
2917 if (status < 0)
2918 return NULL;
2919 if (! document_status_styles[status].loaded)
2921 #if GTK_CHECK_VERSION(3, 0, 0)
2922 GdkRGBA color;
2923 GtkWidgetPath *path = gtk_widget_path_new();
2924 GtkStyleContext *ctx = gtk_style_context_new();
2925 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
2926 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
2927 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
2928 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
2929 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
2930 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
2931 gtk_style_context_set_path(ctx, path);
2932 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
2933 document_status_styles[status].color.red = 0xffff * color.red;
2934 document_status_styles[status].color.green = 0xffff * color.green;
2935 document_status_styles[status].color.blue = 0xffff * color.blue;
2936 document_status_styles[status].loaded = TRUE;
2937 gtk_widget_path_unref(path);
2938 g_object_unref(ctx);
2939 #else
2940 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
2941 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
2942 document_status_styles[status].name, NULL);
2943 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
2945 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
2946 document_status_styles[status].loaded = TRUE;
2947 g_free(path);
2948 #endif
2950 return &document_status_styles[status].color;
2954 /** Accessor function for @ref documents_array items.
2955 * @warning Always check the returned document is valid (@c doc->is_valid).
2956 * @param idx @c documents_array index.
2957 * @return The document, or @c NULL if @a idx is out of range.
2959 * @since 0.16
2961 GeanyDocument *document_index(gint idx)
2963 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2967 GeanyDocument *document_clone(GeanyDocument *old_doc)
2969 gchar *text;
2970 GeanyDocument *doc;
2971 ScintillaObject *old_sci;
2973 g_return_val_if_fail(old_doc, NULL);
2974 old_sci = old_doc->editor->sci;
2975 if (sci_has_selection(old_sci))
2976 text = sci_get_selection_contents(old_sci);
2977 else
2978 text = sci_get_contents(old_sci, -1);
2980 doc = document_new_file(NULL, old_doc->file_type, text);
2981 g_free(text);
2982 document_set_text_changed(doc, TRUE);
2984 /* copy file properties */
2985 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2986 doc->editor->line_breaking = old_doc->editor->line_breaking;
2987 doc->editor->auto_indent = old_doc->editor->auto_indent;
2988 editor_set_indent(doc->editor, old_doc->editor->indent_type,
2989 old_doc->editor->indent_width);
2990 doc->readonly = old_doc->readonly;
2991 doc->has_bom = old_doc->has_bom;
2992 doc->priv->protected = 0;
2993 document_set_encoding(doc, old_doc->encoding);
2994 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2995 sci_set_readonly(doc->editor->sci, doc->readonly);
2997 /* update ui */
2998 ui_document_show_hide(doc);
2999 return doc;
3003 /* @note If successful, this should always be followed up with a call to
3004 * document_close_all().
3005 * @return TRUE if all files were saved or had their changes discarded. */
3006 gboolean document_account_for_unsaved(void)
3008 guint i, p, page_count;
3010 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3011 /* iterate over documents in tabs order */
3012 for (p = 0; p < page_count; p++)
3014 GeanyDocument *doc = document_get_from_page(p);
3016 if (DOC_VALID(doc) && doc->changed)
3018 if (! dialogs_show_unsaved_file(doc))
3019 return FALSE;
3022 /* all documents should now be accounted for, so ignore any changes */
3023 foreach_document (i)
3025 documents[i]->changed = FALSE;
3027 return TRUE;
3031 static void force_close_all(void)
3033 guint i, len = documents_array->len;
3035 /* check all documents have been accounted for */
3036 for (i = 0; i < len; i++)
3038 if (documents[i]->is_valid)
3040 g_return_if_fail(!documents[i]->changed);
3043 main_status.closing_all = TRUE;
3045 foreach_document(i)
3047 document_close(documents[i]);
3050 main_status.closing_all = FALSE;
3054 gboolean document_close_all(void)
3056 if (! document_account_for_unsaved())
3057 return FALSE;
3059 force_close_all();
3061 return TRUE;
3065 /* *
3066 * Shows a message related to a document.
3068 * Use this whenever the user needs to see a document-related message,
3069 * for example when the file was externally modified or deleted.
3071 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3072 * @a response_1 response will be the default for the @c GtkInfoBar or
3073 * @c GtkDialog.
3075 * @param doc @c GeanyDocument.
3076 * @param msgtype The type of message.
3077 * @param response_cb A callback function called when there's a response.
3078 * @param btn_1 The first action area button.
3079 * @param response_1 The response for @a btn_1.
3080 * @param btn_2 The second action area button.
3081 * @param response_2 The response for @a btn_2.
3082 * @param btn_3 The third action area button.
3083 * @param response_3 The response for @a btn_3.
3084 * @param extra_text Text to show below the main message.
3085 * @param format The text format for the main message.
3086 * @param ... Used with @a format as in @c printf.
3088 * @since 1.25
3089 * */
3090 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3091 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3092 const gchar *btn_1, GtkResponseType response_1,
3093 const gchar *btn_2, GtkResponseType response_2,
3094 const gchar *btn_3, GtkResponseType response_3,
3095 const gchar *extra_text, const gchar *format, ...)
3097 va_list args;
3098 gchar *text, *markup;
3099 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3100 GtkWidget *info_widget, *parent;
3101 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook),
3102 document_get_notebook_page(doc));
3104 va_start(args, format);
3105 text = g_strdup_vprintf(format, args);
3106 va_end(args);
3108 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3109 g_free(text);
3111 info_widget = gtk_info_bar_new();
3112 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3113 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3115 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3117 if (btn_1)
3118 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3119 if (btn_2)
3120 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3121 if (btn_3)
3122 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3124 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3126 label = geany_wrap_label_new(NULL);
3127 gtk_label_set_markup(GTK_LABEL(label), markup);
3128 g_free(markup);
3130 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3131 g_signal_connect_after(info_widget, "response", G_CALLBACK(gtk_widget_destroy), NULL);
3133 hbox = gtk_hbox_new(FALSE, 12);
3134 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3136 switch (msgtype)
3138 case GTK_MESSAGE_INFO:
3139 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3140 break;
3141 case GTK_MESSAGE_WARNING:
3142 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3143 break;
3144 case GTK_MESSAGE_QUESTION:
3145 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3146 break;
3147 case GTK_MESSAGE_ERROR:
3148 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3149 break;
3150 default:
3151 icon = NULL;
3152 break;
3155 if (icon)
3156 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3158 if (extra_text)
3160 vbox = gtk_vbox_new(FALSE, 6);
3161 extra_label = geany_wrap_label_new(extra_text);
3162 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3163 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3164 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3166 else
3167 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3169 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3171 gtk_widget_show_all(info_widget);
3173 return info_widget;
3176 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3178 unprotect_document(doc);
3179 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3181 if (response_id == GTK_RESPONSE_REJECT)
3182 document_reload_file(doc, doc->encoding);
3183 else if (response_id == GTK_RESPONSE_ACCEPT)
3184 document_save_file(doc, FALSE);
3187 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3189 GtkInfoBar *bar = GTK_INFO_BAR(data);
3191 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3193 switch (event->keyval)
3195 case GDK_Tab:
3196 case GDK_ISO_Left_Tab:
3198 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3199 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3200 gtk_widget_child_focus(action_area, dir);
3201 return TRUE;
3203 case GDK_Escape:
3205 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3206 return TRUE;
3208 default:
3209 return FALSE;
3214 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3215 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3217 /* automatically focus editor again on bar close */
3218 g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3219 G_CONNECT_SWAPPED);
3220 g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3224 static void monitor_reload_file(GeanyDocument *doc)
3226 gchar *base_name = g_path_get_basename(doc->file_name);
3228 /* show this message only once */
3229 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3231 GtkWidget *bar;
3233 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3234 _("_Reload"), GTK_RESPONSE_REJECT,
3235 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
3236 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3237 _("Do you want to reload it?"),
3238 _("The file '%s' on the disk is more recent than the current buffer."),
3239 base_name);
3241 document_set_text_changed(doc, TRUE);
3242 protect_document(doc);
3243 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3244 enable_key_intercept(doc, bar);
3246 g_free(base_name);
3250 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3251 gint response_id,
3252 GeanyDocument *doc)
3254 unprotect_document(doc);
3256 if (response_id == GTK_RESPONSE_ACCEPT)
3257 dialogs_show_save_as();
3259 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3263 static void monitor_resave_missing_file(GeanyDocument *doc)
3265 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3267 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3269 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3270 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3272 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3273 on_monitor_resave_missing_file_response,
3274 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
3275 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3276 NULL, GTK_RESPONSE_NONE,
3277 _("Try to resave the file?"),
3278 _("File \"%s\" was not found on disk!"),
3279 doc->file_name);
3281 protect_document(doc);
3282 document_set_text_changed(doc, TRUE);
3283 /* don't prompt more than once */
3284 SETPTR(doc->real_path, NULL);
3285 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3286 enable_key_intercept(doc, bar);
3291 /* Set force to force a disk check, otherwise it is ignored if there was a check
3292 * in the last file_prefs.disk_check_timeout seconds.
3293 * @return @c TRUE if the file has changed. */
3294 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3296 gboolean ret = FALSE;
3297 gboolean use_gio_filemon;
3298 time_t cur_time = 0;
3299 struct stat st;
3300 gchar *locale_filename;
3301 FileDiskStatus old_status;
3303 g_return_val_if_fail(doc != NULL, FALSE);
3305 /* ignore remote files and documents that have never been saved to disk */
3306 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3307 || doc->real_path == NULL || doc->priv->is_remote)
3308 return FALSE;
3310 use_gio_filemon = (doc->priv->monitor != NULL);
3312 if (use_gio_filemon)
3314 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3315 return FALSE;
3317 else
3319 cur_time = time(NULL);
3320 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3321 return FALSE;
3323 doc->priv->last_check = cur_time;
3326 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3327 if (g_stat(locale_filename, &st) != 0)
3329 monitor_resave_missing_file(doc);
3330 /* doc may be closed now */
3331 ret = TRUE;
3333 else if (! use_gio_filemon && /* ignore check when using GIO */
3334 doc->priv->mtime > cur_time)
3336 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3337 /* Note: on Windows st.st_mtime can be newer than cur_time */
3339 else if (doc->priv->mtime < st.st_mtime)
3341 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3342 doc->priv->mtime = st.st_mtime;
3343 monitor_reload_file(doc);
3344 /* doc may be closed now */
3345 ret = TRUE;
3347 g_free(locale_filename);
3349 if (DOC_VALID(doc))
3350 { /* doc can get invalid when a document was closed */
3351 old_status = doc->priv->file_disk_status;
3352 doc->priv->file_disk_status = FILE_OK;
3353 if (old_status != doc->priv->file_disk_status)
3354 ui_update_tab_status(doc);
3356 return ret;
3360 /** Compares documents by their display names.
3361 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3362 * @note 'Display name' means the base name of the document's filename.
3364 * @param a @c GeanyDocument**.
3365 * @param b @c GeanyDocument**.
3366 * @warning The arguments take the address of each document pointer.
3367 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3369 * @since 0.21
3371 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3373 GeanyDocument *doc_a = *((GeanyDocument**) a);
3374 GeanyDocument *doc_b = *((GeanyDocument**) b);
3375 gchar *base_name_a, *base_name_b;
3376 gint result;
3378 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3379 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3381 result = strcmp(base_name_a, base_name_b);
3383 g_free(base_name_a);
3384 g_free(base_name_b);
3386 return result;
3390 /** Compares documents by their tab order.
3391 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3393 * @param a @c GeanyDocument**.
3394 * @param b @c GeanyDocument**.
3395 * @warning The arguments take the address of each document pointer.
3396 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3398 * @since 0.21 (GEANY_API_VERSION 209)
3400 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3402 GeanyDocument *doc_a = *((GeanyDocument**) a);
3403 GeanyDocument *doc_b = *((GeanyDocument**) b);
3404 gint notebook_position_doc_a;
3405 gint notebook_position_doc_b;
3407 notebook_position_doc_a = document_get_notebook_page(doc_a);
3408 notebook_position_doc_b = document_get_notebook_page(doc_b);
3410 if (notebook_position_doc_a < notebook_position_doc_b)
3411 return -1;
3412 if (notebook_position_doc_a > notebook_position_doc_b)
3413 return 1;
3414 /* equality */
3415 return 0;
3419 /** Compares documents by their tab order, in reverse order.
3420 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3422 * @param a @c GeanyDocument**.
3423 * @param b @c GeanyDocument**.
3424 * @warning The arguments take the address of each document pointer.
3425 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3427 * @since 0.21 (GEANY_API_VERSION 209)
3429 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3431 GeanyDocument *doc_a = *((GeanyDocument**) a);
3432 GeanyDocument *doc_b = *((GeanyDocument**) b);
3433 gint notebook_position_doc_a;
3434 gint notebook_position_doc_b;
3436 notebook_position_doc_a = document_get_notebook_page(doc_a);
3437 notebook_position_doc_b = document_get_notebook_page(doc_b);
3439 if (notebook_position_doc_a < notebook_position_doc_b)
3440 return 1;
3441 if (notebook_position_doc_a > notebook_position_doc_b)
3442 return -1;
3443 /* equality */
3444 return 0;
3448 void document_grab_focus(GeanyDocument *doc)
3450 g_return_if_fail(doc != NULL);
3452 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));